50 #include <initializer_list>
61 #include <unordered_set>
83 #elif defined(GTEST_OS_ZOS)
89 #elif defined(GTEST_OS_WINDOWS_MOBILE) // We are on Windows CE.
94 #elif defined(GTEST_OS_WINDOWS) // We are on Windows proper.
104 #include <sys/stat.h>
105 #include <sys/timeb.h>
106 #include <sys/types.h>
108 #ifdef GTEST_OS_WINDOWS_MINGW
109 #include <sys/time.h>
110 #endif // GTEST_OS_WINDOWS_MINGW
116 #include <sys/time.h>
119 #endif // GTEST_OS_LINUX
121 #if GTEST_HAS_EXCEPTIONS
125 #if GTEST_CAN_STREAM_RESULTS_
126 #include <arpa/inet.h>
128 #include <sys/socket.h>
129 #include <sys/types.h>
134 #ifdef GTEST_OS_WINDOWS
135 #define vsnprintf _vsnprintf
136 #endif // GTEST_OS_WINDOWS
140 #include <crt_externs.h>
144 #ifdef GTEST_HAS_ABSL
145 #include "absl/container/flat_hash_set.h"
146 #include "absl/debugging/failure_signal_handler.h"
147 #include "absl/debugging/stacktrace.h"
148 #include "absl/debugging/symbolize.h"
149 #include "absl/flags/parse.h"
150 #include "absl/flags/usage.h"
151 #include "absl/strings/str_cat.h"
152 #include "absl/strings/str_replace.h"
153 #include "absl/strings/string_view.h"
154 #include "absl/strings/strip.h"
155 #endif // GTEST_HAS_ABSL
159 #if defined(__has_builtin)
160 #define GTEST_HAS_BUILTIN(x) __has_builtin(x)
162 #define GTEST_HAS_BUILTIN(x) 0
163 #endif // defined(__has_builtin)
165 #if defined(GTEST_HAS_ABSL) && !defined(GTEST_NO_ABSL_FLAGS)
166 #define GTEST_HAS_ABSL_FLAGS
212 #if GTEST_HAS_FILE_SYSTEM
214 static FILE* OpenFileForWriting(
const std::string& output_file) {
215 FILE* fileout =
nullptr;
216 FilePath output_file_path(output_file);
217 FilePath output_dir(output_file_path.RemoveFileName());
219 if (output_dir.CreateDirectoriesRecursively()) {
222 if (fileout ==
nullptr) {
223 GTEST_LOG_(FATAL) <<
"Unable to open file \"" << output_file <<
"\"";
227 #endif // GTEST_HAS_FILE_SYSTEM
234 const char*
const testbridge_test_only =
236 if (testbridge_test_only !=
nullptr) {
237 return testbridge_test_only;
245 const char*
const testbridge_test_runner_fail_fast =
247 if (testbridge_test_runner_fail_fast !=
nullptr) {
248 return strcmp(testbridge_test_runner_fail_fast,
"1") == 0;
259 "True if and only if a test failure should stop further test execution.");
262 also_run_disabled_tests,
264 "Run disabled tests too, in addition to the tests normally being run.");
269 "True if and only if a failed assertion should be a debugger "
276 " should catch exceptions and treat them as test failures.");
280 "Whether to use colors in the output. Valid values: yes, no, "
281 "and auto. 'auto' means to use colors if the output is "
282 "being sent to a terminal and the TERM environment variable "
283 "is set to a terminal type that supports colors.");
289 "A colon-separated list of glob (not regex) patterns "
290 "for filtering the tests to run, optionally followed by a "
291 "'-' and a : separated list of negative patterns (tests to "
292 "exclude). A test is run if it matches one of the positive "
293 "patterns and does not match any of the negative patterns.");
296 install_failure_signal_handler,
299 "If true and supported on the current platform, " GTEST_NAME_
301 "install a signal handler that dumps debugging information when fatal "
302 "signals are raised.");
315 "A format (defaults to \"xml\" but can be specified to be \"json\"), "
316 "optionally followed by a colon and an output file name or directory. "
317 "A directory is indicated by a trailing pathname separator. "
318 "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
319 "If a directory is specified, output files will be created "
320 "within that directory, with file-names based on the test "
321 "executable's name and, if necessary, made unique by adding "
326 "True if only test failures should be displayed in text output.");
331 " should display elapsed time in text output.");
336 " prints UTF8 characters as text.");
340 "Random number seed to use when shuffling test orders. Must be in range "
341 "[1, 99999], or 0 to use a seed based on the current time.");
345 "How many times to repeat each test. Specify a negative number "
346 "for repeating forever. Useful for shaking out flaky tests.");
349 recreate_environments_when_repeating,
352 "Controls whether global test environments are recreated for each repeat "
353 "of the tests. If set to false the global test environments are only set "
354 "up once, for the first iteration, and only torn down once, for the last. "
355 "Useful for shaking out flaky tests with stable, expensive test "
356 "environments. If --gtest_repeat is set to a negative number, meaning "
357 "there is no last run, the environments will always be recreated to avoid "
362 " should include internal stack frames when "
363 "printing test failure stack traces.");
368 " should randomize tests' order on every run.");
374 "The maximum number of stack frames to print when an "
375 "assertion fails. The valid range is 0 through 100, inclusive.");
380 "This flag specifies the host name and the port number on which to stream "
381 "test results. Example: \"localhost:555\". The flag is effective only on "
387 "When this flag is specified, a failed assertion will throw an exception "
388 "if exceptions are enabled or exit the program with a non-zero code "
389 "otherwise. For use with an external test framework.");
391 #if GTEST_USE_OWN_FLAGFILE_FLAG_
394 "This flag specifies the flagfile to read command-line flags from.");
395 #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
410 GTEST_CHECK_(range > 0) <<
"Cannot generate a number in the range [0, 0).";
412 <<
"Generation of a number in [0, " << range <<
") was requested, "
413 <<
"but this can only generate numbers in [0, " <<
kMaxRange <<
").";
432 for (
size_t i = 0;
i < case_list.size();
i++) {
433 sum += (case_list[
i]->*method)();
458 bool ShouldEmitStackTraceForResultType(TestPartResult::Type type) {
462 return type != TestPartResult::kSuccess && type != TestPartResult::kSkip;
469 int line,
const char* message)
479 ShouldEmitStackTraceForResultType(
data_->
type)
493 constexpr
bool kErrorOnUninstantiatedParameterizedTest =
true;
494 constexpr
bool kErrorOnUninstantiatedTypeParameterizedTest =
true;
497 class FailureTest :
public Test {
499 explicit FailureTest(
const CodeLocation& loc, std::string error_message,
505 void TestBody()
override {
507 AssertHelper(TestPartResult::kNonFatalFailure,
loc_.file.c_str(),
536 if (ignored.find(name) != ignored.end())
return;
538 const char kMissingInstantiation[] =
539 " is defined via TEST_P, but never instantiated. None of the test "
541 "will run. Either no INSTANTIATE_TEST_SUITE_P is provided or the only "
542 "ones provided expand to nothing."
544 "Ideally, TEST_P definitions should only ever be included as part of "
545 "binaries that intend to use them. (As opposed to, for example, being "
546 "placed in a library that may be linked in to get other utilities.)";
548 const char kMissingTestCase[] =
549 " is instantiated via INSTANTIATE_TEST_SUITE_P, but no tests are "
550 "defined via TEST_P . No test cases will run."
552 "Ideally, INSTANTIATE_TEST_SUITE_P should only ever be invoked from "
553 "code that always depend on code that provides TEST_P. Failing to do "
554 "so is often an indication of dead code, e.g. the last TEST_P was "
555 "removed but the rest got left behind.";
557 std::string message =
558 "Parameterized test suite " + name +
559 (has_test_p ? kMissingInstantiation : kMissingTestCase) +
561 "To suppress this error for this test suite, insert the following line "
562 "(in a non-header) in the namespace it is defined in:"
564 "GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(" +
567 std::string full_name =
"UninstantiatedParameterizedTestSuite<" + name +
">";
569 "GoogleTestVerification", full_name.c_str(),
572 location.
file.c_str(), location.
line, [message, location] {
573 return new FailureTest(location, message,
574 kErrorOnUninstantiatedParameterizedTest);
581 test_suite_name, std::move(code_location));
590 const char* test_suite_name,
CodeLocation code_location) {
591 suites_.emplace(std::string(test_suite_name),
596 const char* test_suite_name) {
597 auto it =
suites_.find(std::string(test_suite_name));
599 it->second.instantiated =
true;
601 GTEST_LOG_(ERROR) <<
"Unknown type parameterized test suit '"
602 << test_suite_name <<
"'";
608 for (
const auto& testcase :
suites_) {
609 if (testcase.second.instantiated)
continue;
610 if (ignored.find(testcase.first) != ignored.end())
continue;
612 std::string message =
613 "Type parameterized test suite " + testcase.first +
614 " is defined via REGISTER_TYPED_TEST_SUITE_P, but never instantiated "
615 "via INSTANTIATE_TYPED_TEST_SUITE_P. None of the test cases will run."
617 "Ideally, TYPED_TEST_P definitions should only ever be included as "
618 "part of binaries that intend to use them. (As opposed to, for "
619 "example, being placed in a library that may be linked in to get "
623 "To suppress this error for this test suite, insert the following "
625 "(in a non-header) in the namespace it is defined in:"
627 "GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(" +
628 testcase.first +
");";
630 std::string full_name =
631 "UninstantiatedTypeParameterizedTestSuite<" + testcase.first +
">";
633 "GoogleTestVerification", full_name.c_str(),
636 testcase.second.code_location.file.c_str(),
637 testcase.second.code_location.line, [message, testcase] {
638 return new FailureTest(testcase.second.code_location, message,
639 kErrorOnUninstantiatedTypeParameterizedTest);
648 #if defined(GTEST_CUSTOM_GET_ARGVS_)
651 const auto& custom = GTEST_CUSTOM_GET_ARGVS_();
652 return ::std::vector<std::string>(custom.begin(), custom.end());
653 #else // defined(GTEST_CUSTOM_GET_ARGVS_)
655 #endif // defined(GTEST_CUSTOM_GET_ARGVS_)
658 #if GTEST_HAS_FILE_SYSTEM
661 FilePath GetCurrentExecutableName() {
666 #if defined(GTEST_OS_WINDOWS) || defined(GTEST_OS_OS2)
667 result.Set(FilePath(args[0]).RemoveExtension(
"exe"));
669 result.Set(FilePath(args[0]));
670 #endif // GTEST_OS_WINDOWS
673 return result.RemoveDirectoryName();
675 #endif // GTEST_HAS_FILE_SYSTEM
682 const char*
const gtest_output_flag = s.c_str();
683 const char*
const colon = strchr(gtest_output_flag,
':');
684 return (colon ==
nullptr)
685 ? std::string(gtest_output_flag)
686 : std::string(gtest_output_flag,
687 static_cast<size_t>(colon - gtest_output_flag));
690 #if GTEST_HAS_FILE_SYSTEM
695 const char*
const gtest_output_flag = s.c_str();
700 const char*
const colon = strchr(gtest_output_flag,
':');
701 if (colon ==
nullptr)
702 return internal::FilePath::MakeFileName(
708 internal::FilePath output_name(colon + 1);
709 if (!output_name.IsAbsolutePath())
710 output_name = internal::FilePath::ConcatPaths(
712 internal::FilePath(colon + 1));
714 if (!output_name.IsDirectory())
return output_name.string();
716 internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
717 output_name, internal::GetCurrentExecutableName(),
719 return result.string();
721 #endif // GTEST_HAS_FILE_SYSTEM
730 const char* pattern,
const char* pattern_end) {
731 const char* name = name_str.c_str();
732 const char*
const name_begin = name;
733 const char*
const name_end = name + name_str.size();
735 const char* pattern_next = pattern;
736 const char* name_next = name;
738 while (pattern < pattern_end || name < name_end) {
739 if (pattern < pattern_end) {
742 if (name < name_end && *name == *pattern) {
749 if (name < name_end) {
759 pattern_next = pattern;
760 name_next = name + 1;
766 if (name_begin < name_next && name_next <= name_end) {
767 pattern = pattern_next;
778 bool IsGlobPattern(
const std::string& pattern) {
779 return std::any_of(pattern.begin(), pattern.end(),
780 [](
const char c) {
return c ==
'?' ||
c ==
'*'; });
783 class UnitTestFilter {
785 UnitTestFilter() =
default;
788 explicit UnitTestFilter(
const std::string& filter) {
790 std::vector<std::string> all_patterns;
792 const auto exact_match_patterns_begin = std::partition(
793 all_patterns.begin(), all_patterns.end(), &IsGlobPattern);
796 std::distance(all_patterns.begin(), exact_match_patterns_begin)));
797 std::move(all_patterns.begin(), exact_match_patterns_begin,
800 exact_match_patterns_begin, all_patterns.end(),
806 bool MatchesName(
const std::string& name)
const {
809 [&name](
const std::string& pattern) {
811 name, pattern.c_str(),
812 pattern.c_str() + pattern.size());
821 class PositiveAndNegativeUnitTestFilter {
828 explicit PositiveAndNegativeUnitTestFilter(
const std::string& filter) {
829 std::vector<std::string> positive_and_negative_filters;
832 SplitString(filter,
'-', &positive_and_negative_filters);
833 const auto& positive_filter = positive_and_negative_filters.front();
835 if (positive_and_negative_filters.size() > 1) {
842 auto negative_filter_string = positive_and_negative_filters[1];
843 for (std::size_t
i = 2;
i < positive_and_negative_filters.size();
i++)
844 negative_filter_string =
845 negative_filter_string +
'-' + positive_and_negative_filters[
i];
858 bool MatchesTest(
const std::string& test_suite_name,
859 const std::string& test_name)
const {
860 return MatchesName(test_suite_name +
"." + test_name);
865 bool MatchesName(
const std::string& name)
const {
877 const char* filter) {
878 return UnitTestFilter(filter).MatchesName(name_str);
884 const std::string& test_name) {
888 .MatchesTest(test_suite_name, test_name);
892 static std::string FormatSehExceptionMessage(DWORD exception_code,
893 const char* location) {
895 message <<
"SEH exception with code 0x" << std::setbase(16) << exception_code
896 << std::setbase(10) <<
" thrown in " << location <<
".";
900 int UnitTestOptions::GTestProcessSEH(DWORD seh_code,
const char* location) {
909 const DWORD kCxxExceptionCode = 0xe06d7363;
911 if (!
GTEST_FLAG_GET(catch_exceptions) || seh_code == kCxxExceptionCode ||
912 seh_code == EXCEPTION_BREAKPOINT ||
913 seh_code == EXCEPTION_STACK_OVERFLOW) {
914 return EXCEPTION_CONTINUE_SEARCH;
918 TestPartResult::kFatalFailure,
919 FormatSehExceptionMessage(seh_code, location) +
924 return EXCEPTION_EXECUTE_HANDLER;
926 #endif // GTEST_HAS_SEH
933 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
934 TestPartResultArray* result)
935 : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD), result_(result) {
942 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
943 InterceptMode intercept_mode, TestPartResultArray* result)
944 : intercept_mode_(intercept_mode), result_(result) {
948 void ScopedFakeTestPartResultReporter::Init() {
950 if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
951 old_reporter_ = impl->GetGlobalTestPartResultReporter();
952 impl->SetGlobalTestPartResultReporter(
this);
954 old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
955 impl->SetTestPartResultReporterForCurrentThread(
this);
961 ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
963 if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
964 impl->SetGlobalTestPartResultReporter(old_reporter_);
966 impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
972 void ScopedFakeTestPartResultReporter::ReportTestPartResult(
973 const TestPartResult& result) {
974 result_->Append(result);
1000 const TestPartResultArray& results,
1001 TestPartResult::Type type,
1002 const std::string& substr) {
1003 const std::string
expected(type == TestPartResult::kFatalFailure
1005 :
"1 non-fatal failure");
1007 if (results.size() != 1) {
1008 msg <<
"Expected: " << expected <<
"\n"
1009 <<
" Actual: " << results.size() <<
" failures";
1010 for (
int i = 0;
i < results.size();
i++) {
1011 msg <<
"\n" << results.GetTestPartResult(
i);
1016 const TestPartResult& r = results.GetTestPartResult(0);
1017 if (r.type() != type) {
1023 if (strstr(r.message(), substr.c_str()) ==
nullptr) {
1025 <<
"Expected: " << expected <<
" containing \"" << substr <<
"\"\n"
1036 SingleFailureChecker::SingleFailureChecker(
const TestPartResultArray* results,
1037 TestPartResult::Type type,
1038 const std::string& substr)
1039 : results_(results), type_(type), substr_(substr) {}
1045 SingleFailureChecker::~SingleFailureChecker() {
1049 DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
1051 : unit_test_(unit_test) {}
1054 const TestPartResult& result) {
1061 : unit_test_(unit_test) {}
1064 const TestPartResult& result) {
1069 TestPartResultReporterInterface*
1077 TestPartResultReporterInterface* reporter) {
1083 TestPartResultReporterInterface*
1090 TestPartResultReporterInterface* reporter) {
1168 static_cast<int>(
GTEST_FLAG_GET(stack_trace_depth)), skip_count + 1
1181 return std::chrono::duration_cast<std::chrono::milliseconds>(clock::now() -
1189 #if defined(_NEWLIB_VERSION) && !defined(CLOCK_MONOTONIC)
1190 using clock = std::chrono::system_clock;
1192 using clock = std::chrono::steady_clock;
1201 return std::chrono::duration_cast<std::chrono::milliseconds>(
1202 std::chrono::system_clock::now() -
1203 std::chrono::system_clock::from_time_t(0))
1211 #ifdef GTEST_OS_WINDOWS_MOBILE
1216 LPCWSTR String::AnsiToUtf16(
const char* ansi) {
1217 if (!ansi)
return nullptr;
1218 const int length = strlen(ansi);
1219 const int unicode_length =
1220 MultiByteToWideChar(CP_ACP, 0, ansi, length,
nullptr, 0);
1221 WCHAR* unicode =
new WCHAR[unicode_length + 1];
1222 MultiByteToWideChar(CP_ACP, 0, ansi, length, unicode, unicode_length);
1223 unicode[unicode_length] = 0;
1231 const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
1232 if (!utf16_str)
return nullptr;
1233 const int ansi_length = WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
nullptr,
1234 0,
nullptr,
nullptr);
1235 char* ansi =
new char[ansi_length + 1];
1236 WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, ansi, ansi_length,
nullptr,
1238 ansi[ansi_length] = 0;
1242 #endif // GTEST_OS_WINDOWS_MOBILE
1251 if (lhs ==
nullptr)
return rhs ==
nullptr;
1253 if (rhs ==
nullptr)
return false;
1255 return strcmp(lhs, rhs) == 0;
1258 #if GTEST_HAS_STD_WSTRING
1262 static void StreamWideCharsToMessage(
const wchar_t* wstr,
size_t length,
1264 for (
size_t i = 0;
i != length;) {
1265 if (wstr[
i] != L
'\0') {
1266 *msg << WideStringToUtf8(wstr + i, static_cast<int>(length -
i));
1267 while (
i != length && wstr[
i] != L
'\0')
i++;
1275 #endif // GTEST_HAS_STD_WSTRING
1278 ::std::vector< ::std::string>* dest) {
1279 ::std::vector< ::std::string> parsed;
1280 ::std::string::size_type pos = 0;
1282 const ::std::string::size_type colon = str.find(delimiter, pos);
1283 if (colon == ::std::string::npos) {
1284 parsed.push_back(str.substr(pos));
1287 parsed.push_back(str.substr(pos, colon - pos));
1304 *ss_ << std::setprecision(std::numeric_limits<double>::digits10 + 2);
1316 #if GTEST_HAS_STD_WSTRING
1320 internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(),
this);
1323 #endif // GTEST_HAS_STD_WSTRING
1331 namespace internal {
1333 namespace edit_distance {
1335 const std::vector<size_t>& right) {
1336 std::vector<std::vector<double> > costs(
1337 left.size() + 1, std::vector<double>(right.size() + 1));
1338 std::vector<std::vector<EditType> > best_move(
1339 left.size() + 1, std::vector<EditType>(right.size() + 1));
1342 for (
size_t l_i = 0; l_i < costs.size(); ++l_i) {
1343 costs[l_i][0] =
static_cast<double>(l_i);
1347 for (
size_t r_i = 1; r_i < costs[0].size(); ++r_i) {
1348 costs[0][r_i] =
static_cast<double>(r_i);
1349 best_move[0][r_i] =
kAdd;
1352 for (
size_t l_i = 0; l_i < left.size(); ++l_i) {
1353 for (
size_t r_i = 0; r_i < right.size(); ++r_i) {
1354 if (left[l_i] == right[r_i]) {
1356 costs[l_i + 1][r_i + 1] = costs[l_i][r_i];
1357 best_move[l_i + 1][r_i + 1] =
kMatch;
1361 const double add = costs[l_i + 1][r_i];
1362 const double remove = costs[l_i][r_i + 1];
1363 const double replace = costs[l_i][r_i];
1364 if (add <
remove && add < replace) {
1365 costs[l_i + 1][r_i + 1] = add + 1;
1366 best_move[l_i + 1][r_i + 1] =
kAdd;
1367 }
else if (
remove < add &&
remove < replace) {
1368 costs[l_i + 1][r_i + 1] =
remove + 1;
1369 best_move[l_i + 1][r_i + 1] =
kRemove;
1373 costs[l_i + 1][r_i + 1] = replace + 1.00001;
1374 best_move[l_i + 1][r_i + 1] =
kReplace;
1380 std::vector<EditType> best_path;
1381 for (
size_t l_i = left.size(), r_i = right.size(); l_i > 0 || r_i > 0;) {
1382 EditType move = best_move[l_i][r_i];
1383 best_path.push_back(move);
1384 l_i -= move !=
kAdd;
1387 std::reverse(best_path.begin(), best_path.end());
1394 class InternalStrings {
1396 size_t GetId(
const std::string& str) {
1397 IdMap::iterator it =
ids_.find(str);
1398 if (it !=
ids_.end())
return it->second;
1399 size_t id =
ids_.size();
1400 return ids_[str] = id;
1404 typedef std::map<std::string, size_t> IdMap;
1411 const std::vector<std::string>& left,
1412 const std::vector<std::string>& right) {
1413 std::vector<size_t> left_ids, right_ids;
1415 InternalStrings intern_table;
1416 for (
size_t i = 0;
i < left.size(); ++
i) {
1417 left_ids.push_back(intern_table.GetId(left[
i]));
1419 for (
size_t i = 0;
i < right.size(); ++
i) {
1420 right_ids.push_back(intern_table.GetId(right[
i]));
1434 Hunk(
size_t left_start,
size_t right_start)
1441 void PushLine(
char edit,
const char* line) {
1446 hunk_.push_back(std::make_pair(
' ', line));
1454 hunk_adds_.push_back(std::make_pair(
'+', line));
1459 void PrintTo(std::ostream* os) {
1462 for (std::list<std::pair<char, const char*> >::const_iterator it =
1464 it !=
hunk_.end(); ++it) {
1465 *os << it->first << it->second <<
"\n";
1481 void PrintHeader(std::ostream* ss)
const {
1510 const std::vector<std::string>& right,
1514 size_t l_i = 0, r_i = 0, edit_i = 0;
1515 std::stringstream ss;
1516 while (edit_i < edits.size()) {
1518 while (edit_i < edits.size() && edits[edit_i] ==
kMatch) {
1525 const size_t prefix_context =
std::min(l_i, context);
1526 Hunk hunk(l_i - prefix_context + 1, r_i - prefix_context + 1);
1527 for (
size_t i = prefix_context;
i > 0; --
i) {
1528 hunk.PushLine(
' ', left[l_i -
i].c_str());
1533 size_t n_suffix = 0;
1534 for (; edit_i < edits.size(); ++edit_i) {
1535 if (n_suffix >= context) {
1537 auto it = edits.begin() +
static_cast<int>(edit_i);
1538 while (it != edits.end() && *it ==
kMatch) ++it;
1539 if (it == edits.end() ||
1540 static_cast<size_t>(it - edits.begin()) - edit_i >= context) {
1548 n_suffix = edit ==
kMatch ? n_suffix + 1 : 0;
1551 hunk.PushLine(edit ==
kMatch ?
' ' :
'-', left[l_i].c_str());
1554 hunk.PushLine(
'+', right[r_i].c_str());
1558 l_i += edit !=
kAdd;
1562 if (!hunk.has_edits()) {
1579 std::vector<std::string> SplitEscapedString(
const std::string& str) {
1580 std::vector<std::string> lines;
1581 size_t start = 0, end = str.size();
1582 if (end > 2 && str[0] ==
'"' && str[end - 1] ==
'"') {
1586 bool escaped =
false;
1587 for (
size_t i = start;
i + 1 < end; ++
i) {
1590 if (str[
i] ==
'n') {
1591 lines.push_back(str.substr(start,
i - start - 1));
1595 escaped = str[
i] ==
'\\';
1598 lines.push_back(str.substr(start, end - start));
1620 const char* rhs_expression,
1621 const std::string& lhs_value,
1622 const std::string& rhs_value,
bool ignoring_case) {
1624 msg <<
"Expected equality of these values:";
1625 msg <<
"\n " << lhs_expression;
1626 if (lhs_value != lhs_expression) {
1627 msg <<
"\n Which is: " << lhs_value;
1629 msg <<
"\n " << rhs_expression;
1630 if (rhs_value != rhs_expression) {
1631 msg <<
"\n Which is: " << rhs_value;
1634 if (ignoring_case) {
1635 msg <<
"\nIgnoring case";
1638 if (!lhs_value.empty() && !rhs_value.empty()) {
1639 const std::vector<std::string> lhs_lines = SplitEscapedString(lhs_value);
1640 const std::vector<std::string> rhs_lines = SplitEscapedString(rhs_value);
1641 if (lhs_lines.size() > 1 || rhs_lines.size() > 1) {
1642 msg <<
"\nWith diff:\n"
1652 const AssertionResult& assertion_result,
const char* expression_text,
1653 const char* actual_predicate_value,
const char* expected_predicate_value) {
1654 const char* actual_message = assertion_result.message();
1656 msg <<
"Value of: " << expression_text
1657 <<
"\n Actual: " << actual_predicate_value;
1658 if (actual_message[0] !=
'\0') msg <<
" (" << actual_message <<
")";
1659 msg <<
"\nExpected: " << expected_predicate_value;
1668 const char* abs_error_expr,
double val1,
1669 double val2,
double abs_error) {
1676 if (std::isinf(val1) && std::isinf(val2) &&
1677 (std::signbit(val1) == std::signbit(val2) ||
1678 (abs_error > 0.0 && std::isinf(abs_error)))) {
1682 const double diff =
fabs(val1 - val2);
1688 const double epsilon =
1689 nextafter(min_abs, std::numeric_limits<double>::infinity()) - min_abs;
1696 if (!(std::isnan)(val1) && !(std::isnan)(val2) && abs_error > 0 &&
1697 abs_error < epsilon) {
1699 <<
"The difference between " << expr1 <<
" and " << expr2 <<
" is "
1700 << diff <<
", where\n"
1701 << expr1 <<
" evaluates to " << val1 <<
",\n"
1702 << expr2 <<
" evaluates to " << val2 <<
".\nThe abs_error parameter "
1703 << abs_error_expr <<
" evaluates to " << abs_error
1704 <<
" which is smaller than the minimum distance between doubles for "
1705 "numbers of this magnitude which is "
1707 <<
", thus making this EXPECT_NEAR check equivalent to "
1708 "EXPECT_EQUAL. Consider using EXPECT_DOUBLE_EQ instead.";
1711 <<
"The difference between " << expr1 <<
" and " << expr2 <<
" is "
1712 << diff <<
", which exceeds " << abs_error_expr <<
", where\n"
1713 << expr1 <<
" evaluates to " << val1 <<
",\n"
1714 << expr2 <<
" evaluates to " << val2 <<
", and\n"
1715 << abs_error_expr <<
" evaluates to " << abs_error <<
".";
1719 template <
typename RawType>
1721 RawType val1, RawType val2) {
1729 if (lhs.AlmostEquals(rhs)) {
1737 ::std::stringstream val1_ss;
1738 val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
1741 ::std::stringstream val2_ss;
1742 val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
1746 <<
"Expected: (" << expr1 <<
") <= (" << expr2 <<
")\n"
1755 AssertionResult
FloatLE(
const char* expr1,
const char* expr2,
float val1,
1757 return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
1762 AssertionResult
DoubleLE(
const char* expr1,
const char* expr2,
double val1,
1764 return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
1767 namespace internal {
1771 const char* rhs_expression,
const char* lhs,
1783 const char* rhs_expression,
const char* lhs,
1795 const char* s2_expression,
const char* s1,
1801 <<
"Expected: (" << s1_expression <<
") != (" << s2_expression
1802 <<
"), actual: \"" << s1 <<
"\" vs \"" << s2 <<
"\"";
1808 const char* s2_expression,
const char* s1,
1814 <<
"Expected: (" << s1_expression <<
") != (" << s2_expression
1815 <<
") (ignoring case), actual: \"" << s1 <<
"\" vs \"" << s2 <<
"\"";
1829 bool IsSubstringPred(
const char* needle,
const char* haystack) {
1830 if (needle ==
nullptr || haystack ==
nullptr)
return needle == haystack;
1832 return strstr(haystack, needle) !=
nullptr;
1835 bool IsSubstringPred(
const wchar_t* needle,
const wchar_t* haystack) {
1836 if (needle ==
nullptr || haystack ==
nullptr)
return needle == haystack;
1838 return wcsstr(haystack, needle) !=
nullptr;
1842 template <
typename StringType>
1843 bool IsSubstringPred(
const StringType& needle,
const StringType& haystack) {
1844 return haystack.find(needle) != StringType::npos;
1851 template <
typename StringType>
1852 AssertionResult IsSubstringImpl(
bool expected_to_be_substring,
1853 const char* needle_expr,
1854 const char* haystack_expr,
1855 const StringType& needle,
1856 const StringType& haystack) {
1857 if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
1860 const bool is_wide_string =
sizeof(needle[0]) > 1;
1861 const char*
const begin_string_quote = is_wide_string ?
"L\"" :
"\"";
1863 <<
"Value of: " << needle_expr <<
"\n"
1864 <<
" Actual: " << begin_string_quote << needle <<
"\"\n"
1865 <<
"Expected: " << (expected_to_be_substring ?
"" :
"not ")
1866 <<
"a substring of " << haystack_expr <<
"\n"
1867 <<
"Which is: " << begin_string_quote << haystack <<
"\"";
1876 AssertionResult
IsSubstring(
const char* needle_expr,
const char* haystack_expr,
1877 const char* needle,
const char* haystack) {
1878 return IsSubstringImpl(
true, needle_expr, haystack_expr, needle, haystack);
1881 AssertionResult
IsSubstring(
const char* needle_expr,
const char* haystack_expr,
1882 const wchar_t* needle,
const wchar_t* haystack) {
1883 return IsSubstringImpl(
true, needle_expr, haystack_expr, needle, haystack);
1887 const char* haystack_expr,
const char* needle,
1888 const char* haystack) {
1889 return IsSubstringImpl(
false, needle_expr, haystack_expr, needle, haystack);
1893 const char* haystack_expr,
const wchar_t* needle,
1894 const wchar_t* haystack) {
1895 return IsSubstringImpl(
false, needle_expr, haystack_expr, needle, haystack);
1898 AssertionResult
IsSubstring(
const char* needle_expr,
const char* haystack_expr,
1899 const ::std::string& needle,
1900 const ::std::string& haystack) {
1901 return IsSubstringImpl(
true, needle_expr, haystack_expr, needle, haystack);
1905 const char* haystack_expr,
1906 const ::std::string& needle,
1907 const ::std::string& haystack) {
1908 return IsSubstringImpl(
false, needle_expr, haystack_expr, needle, haystack);
1911 #if GTEST_HAS_STD_WSTRING
1912 AssertionResult
IsSubstring(
const char* needle_expr,
const char* haystack_expr,
1913 const ::std::wstring& needle,
1914 const ::std::wstring& haystack) {
1915 return IsSubstringImpl(
true, needle_expr, haystack_expr, needle, haystack);
1919 const char* haystack_expr,
1920 const ::std::wstring& needle,
1921 const ::std::wstring& haystack) {
1922 return IsSubstringImpl(
false, needle_expr, haystack_expr, needle, haystack);
1924 #endif // GTEST_HAS_STD_WSTRING
1926 namespace internal {
1928 #ifdef GTEST_OS_WINDOWS
1933 AssertionResult HRESULTFailureHelper(
const char* expr,
const char*
expected,
1935 #if defined(GTEST_OS_WINDOWS_MOBILE) || defined(GTEST_OS_WINDOWS_TV_TITLE)
1938 const char error_text[] =
"";
1945 const DWORD kFlags =
1946 FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
1947 const DWORD kBufSize = 4096;
1949 char error_text[kBufSize] = {
'\0'};
1950 DWORD message_length = ::FormatMessageA(kFlags,
1952 static_cast<DWORD>(hr),
1958 for (; message_length &&
IsSpace(error_text[message_length - 1]);
1960 error_text[message_length - 1] =
'\0';
1963 #endif // GTEST_OS_WINDOWS_MOBILE
1967 <<
"Expected: " << expr <<
" " << expected <<
".\n"
1968 <<
" Actual: " << error_hex <<
" " << error_text <<
"\n";
1973 AssertionResult IsHRESULTSuccess(
const char* expr,
long hr) {
1974 if (SUCCEEDED(hr)) {
1977 return HRESULTFailureHelper(expr,
"succeeds", hr);
1980 AssertionResult IsHRESULTFailure(
const char* expr,
long hr) {
1984 return HRESULTFailureHelper(expr,
"fails", hr);
1987 #endif // GTEST_OS_WINDOWS
2009 (
static_cast<uint32_t
>(1) << (4 + 2 * 6)) - 1;
2013 (
static_cast<uint32_t
>(1) << (3 + 3 * 6)) - 1;
2019 const uint32_t low_bits = *bits & ((
static_cast<uint32_t
>(1) << n) - 1);
2038 str[0] =
static_cast<char>(code_point);
2041 str[1] =
static_cast<char>(0x80 |
ChopLowBits(&code_point, 6));
2042 str[0] =
static_cast<char>(0xC0 | code_point);
2045 str[2] =
static_cast<char>(0x80 |
ChopLowBits(&code_point, 6));
2046 str[1] =
static_cast<char>(0x80 |
ChopLowBits(&code_point, 6));
2047 str[0] =
static_cast<char>(0xE0 | code_point);
2050 str[3] =
static_cast<char>(0x80 |
ChopLowBits(&code_point, 6));
2051 str[2] =
static_cast<char>(0x80 |
ChopLowBits(&code_point, 6));
2052 str[1] =
static_cast<char>(0x80 |
ChopLowBits(&code_point, 6));
2053 str[0] =
static_cast<char>(0xF0 | code_point);
2066 return sizeof(wchar_t) == 2 && (first & 0xFC00) == 0xD800 &&
2067 (second & 0xFC00) == 0xDC00;
2073 const auto first_u =
static_cast<uint32_t
>(first);
2074 const auto second_u =
static_cast<uint32_t
>(second);
2075 const uint32_t mask = (1 << 10) - 1;
2076 return (
sizeof(
wchar_t) == 2)
2077 ? (((first_u & mask) << 10) | (second_u & mask)) + 0x10000
2098 if (num_chars == -1) num_chars =
static_cast<int>(wcslen(str));
2100 ::std::stringstream stream;
2101 for (
int i = 0;
i < num_chars; ++
i) {
2102 uint32_t unicode_code_point;
2104 if (str[
i] == L
'\0') {
2107 unicode_code_point =
2111 unicode_code_point =
static_cast<uint32_t
>(str[
i]);
2122 if (wide_c_str ==
nullptr)
return "(null)";
2134 if (lhs ==
nullptr)
return rhs ==
nullptr;
2136 if (rhs ==
nullptr)
return false;
2138 return wcscmp(lhs, rhs) == 0;
2143 const char* rhs_expression,
const wchar_t* lhs,
2144 const wchar_t* rhs) {
2155 const char* s2_expression,
const wchar_t* s1,
2156 const wchar_t* s2) {
2162 <<
"Expected: (" << s1_expression <<
") != (" << s2_expression
2173 if (lhs ==
nullptr)
return rhs ==
nullptr;
2174 if (rhs ==
nullptr)
return false;
2191 const wchar_t* rhs) {
2192 if (lhs ==
nullptr)
return rhs ==
nullptr;
2194 if (rhs ==
nullptr)
return false;
2196 #ifdef GTEST_OS_WINDOWS
2197 return _wcsicmp(lhs, rhs) == 0;
2198 #elif defined(GTEST_OS_LINUX) && !defined(GTEST_OS_LINUX_ANDROID)
2199 return wcscasecmp(lhs, rhs) == 0;
2205 left = towlower(static_cast<wint_t>(*lhs++));
2206 right = towlower(static_cast<wint_t>(*rhs++));
2207 }
while (left && left == right);
2208 return left == right;
2209 #endif // OS selector
2215 const std::string& suffix) {
2216 const size_t str_len = str.length();
2217 const size_t suffix_len = suffix.length();
2218 return (str_len >= suffix_len) &&
2230 std::stringstream ss;
2231 ss << std::setfill(
'0') << std::setw(width) <<
value;
2237 std::stringstream ss;
2238 ss << std::hex << std::uppercase <<
value;
2249 std::stringstream ss;
2250 ss << std::setfill(
'0') << std::setw(2) << std::hex << std::uppercase
2251 <<
static_cast<unsigned int>(
value);
2258 const ::std::string& str = ss->str();
2259 const char*
const start = str.c_str();
2260 const char*
const end = start + str.length();
2263 result.reserve(static_cast<size_t>(2 * (end - start)));
2264 for (
const char*
ch = start;
ch != end; ++
ch) {
2279 const std::string user_msg_string = user_msg.
GetString();
2280 if (user_msg_string.empty()) {
2283 if (gtest_msg.empty()) {
2284 return user_msg_string;
2286 return gtest_msg +
"\n" + user_msg_string;
2295 : death_test_count_(0), start_timestamp_(0), elapsed_time_(0) {}
2333 const std::vector<TestProperty>::iterator property_with_matching_key =
2340 property_with_matching_key->SetValue(test_property.
value());
2346 "disabled",
"errors",
"failures",
"name",
2347 "random_seed",
"tests",
"time",
"timestamp"};
2352 "disabled",
"errors",
"failures",
"name",
2353 "tests",
"time",
"timestamp",
"skipped"};
2357 "classname",
"name",
"status",
"time",
2358 "type_param",
"value_param",
"file",
"line"};
2363 "classname",
"name",
"status",
"time",
"type_param",
2364 "value_param",
"file",
"line",
"result",
"timestamp"};
2366 template <
size_t kSize>
2368 return std::vector<std::string>(array, array + kSize);
2372 const std::string& xml_element) {
2373 if (xml_element ==
"testsuites") {
2375 }
else if (xml_element ==
"testsuite") {
2377 }
else if (xml_element ==
"testcase") {
2380 GTEST_CHECK_(
false) <<
"Unrecognized xml_element provided: " << xml_element;
2383 return std::vector<std::string>();
2386 #if GTEST_HAS_FILE_SYSTEM
2389 static std::vector<std::string> GetReservedOutputAttributesForElement(
2390 const std::string& xml_element) {
2391 if (xml_element ==
"testsuites") {
2393 }
else if (xml_element ==
"testsuite") {
2395 }
else if (xml_element ==
"testcase") {
2398 GTEST_CHECK_(
false) <<
"Unrecognized xml_element provided: " << xml_element;
2401 return std::vector<std::string>();
2407 for (
size_t i = 0;
i < words.size(); ++
i) {
2408 if (
i > 0 && words.size() > 2) {
2411 if (
i == words.size() - 1) {
2412 word_list <<
"and ";
2414 word_list <<
"'" << words[
i] <<
"'";
2420 const std::string& property_name,
2421 const std::vector<std::string>& reserved_names) {
2422 if (std::find(reserved_names.begin(), reserved_names.end(), property_name) !=
2423 reserved_names.end()) {
2424 ADD_FAILURE() <<
"Reserved key used in RecordProperty(): " << property_name
2450 return result.skipped();
2468 return result.fatally_failed();
2478 return result.nonfatally_failed();
2524 namespace internal {
2527 const std::string& message) {
2552 const char*
const first_test_name = first_test_info->
name();
2557 const char*
const this_test_name = this_test_info->
name();
2559 if (this_fixture_id != first_fixture_id) {
2565 if (first_is_TEST || this_is_TEST) {
2572 const char*
const TEST_name =
2573 first_is_TEST ? first_test_name : this_test_name;
2574 const char*
const TEST_F_name =
2575 first_is_TEST ? this_test_name : first_test_name;
2578 <<
"All tests in the same test suite must use the same test fixture\n"
2579 <<
"class, so mixing TEST_F and TEST in the same test suite is\n"
2582 <<
"test " << TEST_F_name <<
" is defined using TEST_F but\n"
2583 <<
"test " << TEST_name <<
" is defined using TEST. You probably\n"
2584 <<
"want to change the TEST to TEST_F or move it to another test\n"
2590 <<
"All tests in the same test suite must use the same test fixture\n"
2591 <<
"class. However, in test suite "
2593 <<
"you defined test " << first_test_name <<
" and test "
2594 << this_test_name <<
"\n"
2595 <<
"using two different test fixture classes. This can happen if\n"
2596 <<
"the two classes are from different namespaces or translation\n"
2597 <<
"units and have the same name. You should probably rename one\n"
2598 <<
"of the classes to put the tests into different test suites.";
2606 namespace internal {
2608 #if GTEST_HAS_EXCEPTIONS
2611 static std::string FormatCxxExceptionMessage(
const char* description,
2612 const char* location) {
2614 if (description !=
nullptr) {
2615 message <<
"C++ exception with description \"" << description <<
"\"";
2617 message <<
"Unknown C++ exception";
2619 message <<
" thrown in " << location <<
".";
2625 const TestPartResult& test_part_result);
2627 GoogleTestFailureException::GoogleTestFailureException(
2628 const TestPartResult& failure)
2631 #endif // GTEST_HAS_EXCEPTIONS
2641 template <
class T,
typename Result>
2643 const char* location) {
2646 return (object->*method)();
2647 } __except (internal::UnitTestOptions::GTestProcessSEH(
2648 GetExceptionCode(), location)) {
2649 return static_cast<Result
>(0);
2653 return (object->*method)();
2654 #endif // GTEST_HAS_SEH
2660 template <
class T,
typename Result>
2662 const char* location) {
2687 #if GTEST_HAS_EXCEPTIONS
2690 }
catch (
const AssertionException&) {
2692 }
catch (
const internal::GoogleTestFailureException&) {
2697 }
catch (
const std::exception& e) {
2699 TestPartResult::kFatalFailure,
2700 FormatCxxExceptionMessage(e.what(), location));
2703 TestPartResult::kFatalFailure,
2704 FormatCxxExceptionMessage(
nullptr, location));
2706 return static_cast<Result
>(0);
2709 #endif // GTEST_HAS_EXCEPTIONS
2711 return (object->*method)();
2719 if (!HasSameFixtureClass())
return;
2726 if (!HasFatalFailure() && !IsSkipped()) {
2741 bool Test::HasFatalFailure() {
2746 bool Test::HasNonfatalFailure() {
2753 bool Test::IsSkipped() {
2761 TestInfo::TestInfo(std::string a_test_suite_name, std::string a_name,
2762 const char* a_type_param,
const char* a_value_param,
2766 : test_suite_name_(std::move(a_test_suite_name)),
2767 name_(std::move(a_name)),
2768 type_param_(a_type_param ? new std::string(a_type_param) : nullptr),
2769 value_param_(a_value_param ? new std::string(a_value_param) : nullptr),
2770 location_(std::move(a_code_location)),
2771 fixture_class_id_(fixture_class_id),
2773 is_disabled_(
false),
2774 matches_filter_(
false),
2775 is_in_another_shard_(
false),
2782 namespace internal {
2803 std::string test_suite_name,
const char* name,
const char* type_param,
2808 new TestInfo(std::move(test_suite_name), name, type_param, value_param,
2809 std::move(code_location), fixture_class_id, factory);
2818 <<
"Attempted redefinition of test suite " << test_suite_name <<
".\n"
2819 <<
"All tests in the same test suite must use the same test fixture\n"
2820 <<
"class. However, in test suite " << test_suite_name <<
", you tried\n"
2821 <<
"to define a test using a fixture class different from the one\n"
2822 <<
"used earlier. This can happen if the two fixture classes are\n"
2823 <<
"from different namespaces and have the same name. You should\n"
2824 <<
"probably rename one of the classes to put the tests into different\n"
2866 "the test fixture's constructor");
2877 if (test !=
nullptr) {
2905 const TestPartResult test_part_result =
2906 TestPartResult(TestPartResult::kSkip, this->
file(), this->
line(),
"");
2909 ->ReportTestPartResult(test_part_result);
2971 type_param_(a_type_param ? new std::string(a_type_param) : nullptr),
2972 set_up_tc_(set_up_tc),
2973 tear_down_tc_(tear_down_tc),
2975 start_timestamp_(0),
2988 return index < 0 ? nullptr : test_info_list_[static_cast<size_t>(index)];
2995 return index < 0 ? nullptr : test_info_list_[static_cast<size_t>(index)];
3025 if (
const int result = std::strcmp(a->
file(), b->file())) {
3029 return a->
line() < b->line();
3035 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3037 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3043 const bool skip_all =
3071 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3073 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3089 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3091 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3100 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3102 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3131 const char* plural_form) {
3133 (count == 1 ? singular_form : plural_form);
3152 case TestPartResult::kSkip:
3154 case TestPartResult::kSuccess:
3157 case TestPartResult::kNonFatalFailure:
3158 case TestPartResult::kFatalFailure:
3165 return "Unknown result type";
3169 namespace internal {
3171 enum class GTestColor { kDefault, kRed, kGreen, kYellow };
3176 const TestPartResult& test_part_result) {
3178 test_part_result.file_name(),
3179 test_part_result.line_number())
3182 << test_part_result.message())
3189 printf(
"%s\n", result.c_str());
3195 #if defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_MOBILE)
3199 ::OutputDebugStringA(result.c_str());
3200 ::OutputDebugStringA(
"\n");
3205 #if defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_MOBILE) && \
3206 !defined(GTEST_OS_WINDOWS_GAMES) && !defined(GTEST_OS_WINDOWS_PHONE) && \
3207 !defined(GTEST_OS_WINDOWS_RT) && !defined(GTEST_OS_WINDOWS_MINGW)
3210 static WORD GetColorAttribute(GTestColor color) {
3212 case GTestColor::kRed:
3213 return FOREGROUND_RED;
3214 case GTestColor::kGreen:
3215 return FOREGROUND_GREEN;
3216 case GTestColor::kYellow:
3217 return FOREGROUND_RED | FOREGROUND_GREEN;
3223 static int GetBitOffset(WORD color_mask) {
3224 if (color_mask == 0)
return 0;
3227 while ((color_mask & 1) == 0) {
3234 static WORD GetNewColor(GTestColor color, WORD old_color_attrs) {
3236 static const WORD background_mask = BACKGROUND_BLUE | BACKGROUND_GREEN |
3237 BACKGROUND_RED | BACKGROUND_INTENSITY;
3238 static const WORD foreground_mask = FOREGROUND_BLUE | FOREGROUND_GREEN |
3239 FOREGROUND_RED | FOREGROUND_INTENSITY;
3240 const WORD existing_bg = old_color_attrs & background_mask;
3243 GetColorAttribute(color) | existing_bg | FOREGROUND_INTENSITY;
3244 static const int bg_bitOffset = GetBitOffset(background_mask);
3245 static const int fg_bitOffset = GetBitOffset(foreground_mask);
3247 if (((new_color & background_mask) >> bg_bitOffset) ==
3248 ((new_color & foreground_mask) >> fg_bitOffset)) {
3249 new_color ^= FOREGROUND_INTENSITY;
3260 case GTestColor::kRed:
3262 case GTestColor::kGreen:
3264 case GTestColor::kYellow:
3272 #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
3277 const char*
const gtest_color = c.c_str();
3280 #if defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_MINGW)
3283 return stdout_is_tty;
3287 const bool term_supports_color =
3298 return stdout_is_tty && term_supports_color;
3299 #endif // GTEST_OS_WINDOWS
3319 va_start(args, fmt);
3321 static const bool in_color_mode =
3326 const bool use_color = in_color_mode && (color != GTestColor::kDefault);
3334 #if defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_MOBILE) && \
3335 !defined(GTEST_OS_WINDOWS_GAMES) && !defined(GTEST_OS_WINDOWS_PHONE) && \
3336 !defined(GTEST_OS_WINDOWS_RT) && !defined(GTEST_OS_WINDOWS_MINGW)
3337 const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
3340 CONSOLE_SCREEN_BUFFER_INFO buffer_info;
3341 GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
3342 const WORD old_color_attrs = buffer_info.wAttributes;
3343 const WORD new_color = GetNewColor(color, old_color_attrs);
3349 SetConsoleTextAttribute(stdout_handle, new_color);
3355 SetConsoleTextAttribute(stdout_handle, old_color_attrs);
3360 #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
3370 const char*
const type_param = test_info.
type_param();
3371 const char*
const value_param = test_info.
value_param();
3373 if (type_param !=
nullptr || value_param !=
nullptr) {
3375 if (type_param !=
nullptr) {
3377 if (value_param !=
nullptr) printf(
" and ");
3379 if (value_param !=
nullptr) {
3392 printf(
"%s.%s", test_suite, test);
3400 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3404 #endif // OnTestCaseStart
3411 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3415 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3430 const UnitTest& unit_test,
int iteration) {
3432 printf(
"\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
3435 const char*
const filter = f.c_str();
3446 ColoredPrintf(GTestColor::kYellow,
"Note: This is test shard %d of %s.\n",
3447 static_cast<int>(shard_index) + 1,
3453 "Note: Randomizing tests' orders with a seed of %d .\n",
3458 printf(
"Running %s from %s.\n",
3467 printf(
"Global test environment set-up.\n");
3471 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3473 const std::string counts =
3476 printf(
"%s from %s", counts.c_str(), test_case.
name());
3487 const std::string counts =
3490 printf(
"%s from %s", counts.c_str(), test_suite.
name());
3498 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3516 const TestPartResult& result) {
3517 switch (result.type()) {
3519 case TestPartResult::kSuccess:
3541 printf(
" (%s ms)\n",
3550 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3554 const std::string counts =
3557 printf(
"%s from %s (%s ms total)\n\n", counts.c_str(), test_case.
name(),
3565 const std::string counts =
3568 printf(
"%s from %s (%s ms total)\n\n", counts.c_str(), test_suite.
name(),
3572 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3577 printf(
"Global test environment tear-down\n");
3585 printf(
"%s, listed below:\n",
FormatTestCount(failed_test_count).c_str());
3598 printf(
"%s.%s", test_suite.
name(), test_info.
name());
3603 printf(
"\n%2d FAILED %s\n", failed_test_count,
3604 failed_test_count == 1 ?
"TEST" :
"TESTS");
3611 int suite_failure_count = 0;
3619 printf(
"%s: SetUpTestSuite or TearDownTestSuite\n", test_suite.
name());
3620 ++suite_failure_count;
3623 if (suite_failure_count > 0) {
3624 printf(
"\n%2d FAILED TEST %s\n", suite_failure_count,
3625 suite_failure_count == 1 ?
"SUITE" :
"SUITES");
3632 if (skipped_test_count == 0) {
3647 printf(
"%s.%s", test_suite.
name(), test_info.
name());
3656 printf(
"%s from %s ran.",
3660 printf(
" (%s ms total)",
3668 if (skipped_test_count > 0) {
3670 printf(
"%s, listed below:\n",
FormatTestCount(skipped_test_count).c_str());
3674 if (!unit_test.
Passed()) {
3681 if (unit_test.
Passed()) {
3684 ColoredPrintf(GTestColor::kYellow,
" YOU HAVE %d DISABLED %s\n\n",
3685 num_disabled, num_disabled == 1 ?
"TEST" :
"TESTS");
3700 printf(
"%s.%s", test_suite, test);
3709 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3713 #endif // OnTestCaseStart
3720 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3724 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3734 const TestPartResult& result) {
3735 switch (result.type()) {
3737 case TestPartResult::kSuccess:
3754 printf(
" (%s ms)\n",
3767 printf(
"%s from %s ran.",
3771 printf(
" (%s ms total)",
3779 if (skipped_test_count > 0) {
3786 if (unit_test.
Passed()) {
3789 ColoredPrintf(GTestColor::kYellow,
" YOU HAVE %d DISABLED %s\n\n",
3790 num_disabled, num_disabled == 1 ?
"TEST" :
"TESTS");
3818 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3820 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3827 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3829 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3868 #define GTEST_REPEATER_METHOD_(Name, Type) \
3869 void TestEventRepeater::Name(const Type& parameter) { \
3870 if (forwarding_enabled_) { \
3871 for (size_t i = 0; i < listeners_.size(); i++) { \
3872 listeners_[i]->Name(parameter); \
3878 #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
3879 void TestEventRepeater::Name(const Type& parameter) { \
3880 if (forwarding_enabled_) { \
3881 for (size_t i = listeners_.size(); i != 0; i--) { \
3882 listeners_[i - 1]->Name(parameter); \
3890 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3892 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3902 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3904 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3908 #undef GTEST_REPEATER_METHOD_
3909 #undef GTEST_REVERSE_REPEATER_METHOD_
3915 listeners_[
i]->OnTestIterationStart(unit_test, iteration);
3924 listeners_[
i - 1]->OnTestIterationEnd(unit_test, iteration);
3931 #if GTEST_HAS_FILE_SYSTEM
3935 explicit XmlUnitTestResultPrinter(
const char* output_file);
3937 void OnTestIterationEnd(
const UnitTest& unit_test,
int iteration)
override;
3938 void ListTestsMatchingFilter(
const std::vector<TestSuite*>& test_suites);
3941 static void PrintXmlTestsList(std::ostream* stream,
3942 const std::vector<TestSuite*>& test_suites);
3947 static bool IsNormalizableWhitespace(
unsigned char c) {
3948 return c ==
'\t' || c ==
'\n' || c ==
'\r';
3953 static bool IsValidXmlCharacter(
unsigned char c) {
3954 return IsNormalizableWhitespace(c) || c >= 0x20;
3961 static std::string EscapeXml(
const std::string& str,
bool is_attribute);
3964 static std::string RemoveInvalidXmlCharacters(
const std::string& str);
3967 static std::string EscapeXmlAttribute(
const std::string& str) {
3968 return EscapeXml(str,
true);
3972 static std::string EscapeXmlText(
const char* str) {
3973 return EscapeXml(str,
false);
3978 static void OutputXmlAttribute(std::ostream* stream,
3979 const std::string& element_name,
3980 const std::string& name,
3981 const std::string&
value);
3984 static void OutputXmlCDataSection(::std::ostream* stream,
const char* data);
3989 static void OutputXmlTestSuiteForTestResult(::std::ostream* stream,
3990 const TestResult& result);
3995 static void OutputXmlTestCaseForTestResult(::std::ostream* stream,
3996 const TestResult& result);
3999 static void OutputXmlTestResult(::std::ostream* stream,
4000 const TestResult& result);
4003 static void OutputXmlTestInfo(::std::ostream* stream,
4004 const char* test_suite_name,
4005 const TestInfo& test_info);
4008 static void PrintXmlTestSuite(::std::ostream* stream,
4009 const TestSuite& test_suite);
4012 static void PrintXmlUnitTest(::std::ostream* stream,
4013 const UnitTest& unit_test);
4017 static void OutputXmlTestProperties(std::ostream* stream,
4018 const TestResult& result,
4019 const std::string& indent);
4022 const std::string output_file_;
4024 XmlUnitTestResultPrinter(
const XmlUnitTestResultPrinter&) =
delete;
4025 XmlUnitTestResultPrinter& operator=(
const XmlUnitTestResultPrinter&) =
delete;
4029 XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(
const char* output_file)
4030 : output_file_(output_file) {
4031 if (output_file_.empty()) {
4032 GTEST_LOG_(FATAL) <<
"XML output file may not be null";
4037 void XmlUnitTestResultPrinter::OnTestIterationEnd(
const UnitTest& unit_test,
4039 FILE* xmlout = OpenFileForWriting(output_file_);
4040 std::stringstream stream;
4041 PrintXmlUnitTest(&stream, unit_test);
4046 void XmlUnitTestResultPrinter::ListTestsMatchingFilter(
4047 const std::vector<TestSuite*>& test_suites) {
4048 FILE* xmlout = OpenFileForWriting(output_file_);
4049 std::stringstream stream;
4050 PrintXmlTestsList(&stream, test_suites);
4065 std::string XmlUnitTestResultPrinter::EscapeXml(
const std::string& str,
4066 bool is_attribute) {
4069 for (
size_t i = 0;
i < str.size(); ++
i) {
4070 const char ch = str[
i];
4094 if (IsValidXmlCharacter(static_cast<unsigned char>(ch))) {
4096 IsNormalizableWhitespace(static_cast<unsigned char>(ch)))
4106 return m.GetString();
4112 std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(
4113 const std::string& str) {
4115 output.reserve(str.size());
4116 for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
4117 if (IsValidXmlCharacter(static_cast<unsigned char>(*it)))
4118 output.push_back(*it);
4141 ::std::stringstream ss;
4146 << std::setprecision(
4147 ms % 1000 == 0 ? 0 : (ms % 100 == 0 ? 1 : (ms % 10 == 0 ? 2 : 3)))
4149 ss << (static_cast<double>(ms) * 1e-3);
4153 static bool PortableLocaltime(time_t seconds,
struct tm* out) {
4154 #if defined(_MSC_VER)
4155 return localtime_s(out, &seconds) == 0;
4156 #elif defined(__MINGW32__) || defined(__MINGW64__)
4159 struct tm* tm_ptr = localtime(&seconds);
4160 if (tm_ptr ==
nullptr)
return false;
4163 #elif defined(__STDC_LIB_EXT1__)
4166 return localtime_s(&seconds, out) !=
nullptr;
4168 return localtime_r(&seconds, out) !=
nullptr;
4175 struct tm time_struct;
4176 if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))
4189 void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
4191 const char* segment = data;
4192 *stream <<
"<![CDATA[";
4194 const char*
const next_segment = strstr(segment,
"]]>");
4195 if (next_segment !=
nullptr) {
4196 stream->write(segment,
4197 static_cast<std::streamsize>(next_segment - segment));
4198 *stream <<
"]]>]]><![CDATA[";
4199 segment = next_segment + strlen(
"]]>");
4208 void XmlUnitTestResultPrinter::OutputXmlAttribute(
4209 std::ostream* stream,
const std::string& element_name,
4210 const std::string& name,
const std::string&
value) {
4211 const std::vector<std::string>& allowed_names =
4212 GetReservedOutputAttributesForElement(element_name);
4214 GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
4215 allowed_names.end())
4216 <<
"Attribute " << name <<
" is not allowed for element <" << element_name
4219 *stream <<
" " << name <<
"=\"" << EscapeXmlAttribute(value) <<
"\"";
4223 void XmlUnitTestResultPrinter::OutputXmlTestSuiteForTestResult(
4224 ::std::ostream* stream,
const TestResult& result) {
4226 *stream <<
" <testsuite";
4227 OutputXmlAttribute(stream,
"testsuite",
"name",
"NonTestSuiteFailure");
4228 OutputXmlAttribute(stream,
"testsuite",
"tests",
"1");
4229 OutputXmlAttribute(stream,
"testsuite",
"failures",
"1");
4230 OutputXmlAttribute(stream,
"testsuite",
"disabled",
"0");
4231 OutputXmlAttribute(stream,
"testsuite",
"skipped",
"0");
4232 OutputXmlAttribute(stream,
"testsuite",
"errors",
"0");
4233 OutputXmlAttribute(stream,
"testsuite",
"time",
4236 stream,
"testsuite",
"timestamp",
4240 OutputXmlTestCaseForTestResult(stream, result);
4243 *stream <<
" </testsuite>\n";
4247 void XmlUnitTestResultPrinter::OutputXmlTestCaseForTestResult(
4248 ::std::ostream* stream,
const TestResult& result) {
4250 *stream <<
" <testcase";
4251 OutputXmlAttribute(stream,
"testcase",
"name",
"");
4252 OutputXmlAttribute(stream,
"testcase",
"status",
"run");
4253 OutputXmlAttribute(stream,
"testcase",
"result",
"completed");
4254 OutputXmlAttribute(stream,
"testcase",
"classname",
"");
4255 OutputXmlAttribute(stream,
"testcase",
"time",
4258 stream,
"testcase",
"timestamp",
4262 OutputXmlTestResult(stream, result);
4266 void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
4267 const char* test_suite_name,
4268 const TestInfo& test_info) {
4269 const TestResult& result = *test_info.result();
4270 const std::string kTestsuite =
"testcase";
4272 if (test_info.is_in_another_shard()) {
4276 *stream <<
" <testcase";
4277 OutputXmlAttribute(stream, kTestsuite,
"name", test_info.name());
4279 if (test_info.value_param() !=
nullptr) {
4280 OutputXmlAttribute(stream, kTestsuite,
"value_param",
4281 test_info.value_param());
4283 if (test_info.type_param() !=
nullptr) {
4284 OutputXmlAttribute(stream, kTestsuite,
"type_param",
4285 test_info.type_param());
4288 OutputXmlAttribute(stream, kTestsuite,
"file", test_info.file());
4289 OutputXmlAttribute(stream, kTestsuite,
"line",
4296 OutputXmlAttribute(stream, kTestsuite,
"status",
4297 test_info.should_run() ?
"run" :
"notrun");
4298 OutputXmlAttribute(stream, kTestsuite,
"result",
4299 test_info.should_run()
4300 ? (result.Skipped() ?
"skipped" :
"completed")
4302 OutputXmlAttribute(stream, kTestsuite,
"time",
4305 stream, kTestsuite,
"timestamp",
4307 OutputXmlAttribute(stream, kTestsuite,
"classname", test_suite_name);
4309 OutputXmlTestResult(stream, result);
4312 void XmlUnitTestResultPrinter::OutputXmlTestResult(::std::ostream* stream,
4313 const TestResult& result) {
4316 for (
int i = 0;
i < result.total_part_count(); ++
i) {
4317 const TestPartResult& part = result.GetTestPartResult(
i);
4318 if (part.failed()) {
4319 if (++failures == 1 && skips == 0) {
4322 const std::string location =
4324 part.line_number());
4325 const std::string summary = location +
"\n" + part.summary();
4326 *stream <<
" <failure message=\"" << EscapeXmlAttribute(summary)
4328 const std::string detail = location +
"\n" + part.message();
4329 OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
4330 *stream <<
"</failure>\n";
4331 }
else if (part.skipped()) {
4332 if (++skips == 1 && failures == 0) {
4335 const std::string location =
4337 part.line_number());
4338 const std::string summary = location +
"\n" + part.summary();
4339 *stream <<
" <skipped message=\""
4340 << EscapeXmlAttribute(summary.c_str()) <<
"\">";
4341 const std::string detail = location +
"\n" + part.message();
4342 OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
4343 *stream <<
"</skipped>\n";
4347 if (failures == 0 && skips == 0 && result.test_property_count() == 0) {
4350 if (failures == 0 && skips == 0) {
4353 OutputXmlTestProperties(stream, result,
" ");
4354 *stream <<
" </testcase>\n";
4359 void XmlUnitTestResultPrinter::PrintXmlTestSuite(std::ostream* stream,
4360 const TestSuite& test_suite) {
4361 const std::string kTestsuite =
"testsuite";
4362 *stream <<
" <" << kTestsuite;
4363 OutputXmlAttribute(stream, kTestsuite,
"name", test_suite.name());
4364 OutputXmlAttribute(stream, kTestsuite,
"tests",
4367 OutputXmlAttribute(stream, kTestsuite,
"failures",
4370 stream, kTestsuite,
"disabled",
4372 OutputXmlAttribute(stream, kTestsuite,
"skipped",
4375 OutputXmlAttribute(stream, kTestsuite,
"errors",
"0");
4377 OutputXmlAttribute(stream, kTestsuite,
"time",
4380 stream, kTestsuite,
"timestamp",
4384 OutputXmlTestProperties(stream, test_suite.ad_hoc_test_result(),
4386 for (
int i = 0;
i < test_suite.total_test_count(); ++
i) {
4387 if (test_suite.GetTestInfo(
i)->is_reportable())
4388 OutputXmlTestInfo(stream, test_suite.name(), *test_suite.GetTestInfo(
i));
4390 if (test_suite.ad_hoc_test_result().Failed()) {
4391 OutputXmlTestCaseForTestResult(stream, test_suite.ad_hoc_test_result());
4394 *stream <<
" </" << kTestsuite <<
">\n";
4398 void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream,
4399 const UnitTest& unit_test) {
4400 const std::string kTestsuites =
"testsuites";
4402 *stream <<
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
4403 *stream <<
"<" << kTestsuites;
4405 OutputXmlAttribute(stream, kTestsuites,
"tests",
4407 OutputXmlAttribute(stream, kTestsuites,
"failures",
4410 stream, kTestsuites,
"disabled",
4412 OutputXmlAttribute(stream, kTestsuites,
"errors",
"0");
4413 OutputXmlAttribute(stream, kTestsuites,
"time",
4416 stream, kTestsuites,
"timestamp",
4420 OutputXmlAttribute(stream, kTestsuites,
"random_seed",
4424 OutputXmlAttribute(stream, kTestsuites,
"name",
"AllTests");
4427 OutputXmlTestProperties(stream, unit_test.ad_hoc_test_result(),
4429 for (
int i = 0;
i < unit_test.total_test_suite_count(); ++
i) {
4430 if (unit_test.GetTestSuite(
i)->reportable_test_count() > 0)
4431 PrintXmlTestSuite(stream, *unit_test.GetTestSuite(
i));
4436 if (unit_test.ad_hoc_test_result().Failed()) {
4437 OutputXmlTestSuiteForTestResult(stream, unit_test.ad_hoc_test_result());
4440 *stream <<
"</" << kTestsuites <<
">\n";
4443 void XmlUnitTestResultPrinter::PrintXmlTestsList(
4444 std::ostream* stream,
const std::vector<TestSuite*>& test_suites) {
4445 const std::string kTestsuites =
"testsuites";
4447 *stream <<
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
4448 *stream <<
"<" << kTestsuites;
4450 int total_tests = 0;
4451 for (
auto test_suite : test_suites) {
4452 total_tests += test_suite->total_test_count();
4454 OutputXmlAttribute(stream, kTestsuites,
"tests",
4456 OutputXmlAttribute(stream, kTestsuites,
"name",
"AllTests");
4459 for (
auto test_suite : test_suites) {
4460 PrintXmlTestSuite(stream, *test_suite);
4462 *stream <<
"</" << kTestsuites <<
">\n";
4465 void XmlUnitTestResultPrinter::OutputXmlTestProperties(
4466 std::ostream* stream,
const TestResult& result,
const std::string& indent) {
4467 const std::string kProperties =
"properties";
4468 const std::string kProperty =
"property";
4470 if (result.test_property_count() <= 0) {
4474 *stream << indent <<
"<" << kProperties <<
">\n";
4475 for (
int i = 0;
i < result.test_property_count(); ++
i) {
4476 const TestProperty&
property = result.GetTestProperty(
i);
4477 *stream << indent <<
" <" << kProperty;
4478 *stream <<
" name=\"" << EscapeXmlAttribute(property.key()) <<
"\"";
4479 *stream <<
" value=\"" << EscapeXmlAttribute(property.value()) <<
"\"";
4482 *stream << indent <<
"</" << kProperties <<
">\n";
4486 #endif // GTEST_HAS_FILE_SYSTEM
4488 #if GTEST_HAS_FILE_SYSTEM
4490 class JsonUnitTestResultPrinter :
public EmptyTestEventListener {
4492 explicit JsonUnitTestResultPrinter(
const char* output_file);
4494 void OnTestIterationEnd(
const UnitTest& unit_test,
int iteration)
override;
4497 static void PrintJsonTestList(::std::ostream* stream,
4498 const std::vector<TestSuite*>& test_suites);
4502 static std::string EscapeJson(
const std::string& str);
4506 static void OutputJsonKey(std::ostream* stream,
4507 const std::string& element_name,
4508 const std::string& name,
const std::string& value,
4509 const std::string& indent,
bool comma =
true);
4510 static void OutputJsonKey(std::ostream* stream,
4511 const std::string& element_name,
4512 const std::string& name,
int value,
4513 const std::string& indent,
bool comma =
true);
4518 static void OutputJsonTestSuiteForTestResult(::std::ostream* stream,
4519 const TestResult& result);
4524 static void OutputJsonTestCaseForTestResult(::std::ostream* stream,
4525 const TestResult& result);
4528 static void OutputJsonTestResult(::std::ostream* stream,
4529 const TestResult& result);
4532 static void OutputJsonTestInfo(::std::ostream* stream,
4533 const char* test_suite_name,
4534 const TestInfo& test_info);
4537 static void PrintJsonTestSuite(::std::ostream* stream,
4538 const TestSuite& test_suite);
4541 static void PrintJsonUnitTest(::std::ostream* stream,
4542 const UnitTest& unit_test);
4546 static std::string TestPropertiesAsJson(
const TestResult& result,
4547 const std::string& indent);
4550 const std::string output_file_;
4552 JsonUnitTestResultPrinter(
const JsonUnitTestResultPrinter&) =
delete;
4553 JsonUnitTestResultPrinter& operator=(
const JsonUnitTestResultPrinter&) =
4558 JsonUnitTestResultPrinter::JsonUnitTestResultPrinter(
const char* output_file)
4559 : output_file_(output_file) {
4560 if (output_file_.empty()) {
4561 GTEST_LOG_(FATAL) <<
"JSON output file may not be null";
4565 void JsonUnitTestResultPrinter::OnTestIterationEnd(
const UnitTest& unit_test,
4567 FILE* jsonout = OpenFileForWriting(output_file_);
4568 std::stringstream stream;
4569 PrintJsonUnitTest(&stream, unit_test);
4575 std::string JsonUnitTestResultPrinter::EscapeJson(
const std::string& str) {
4578 for (
size_t i = 0;
i < str.size(); ++
i) {
4579 const char ch = str[
i];
4611 return m.GetString();
4618 static std::string FormatTimeInMillisAsDuration(
TimeInMillis ms) {
4619 ::std::stringstream ss;
4620 ss << (static_cast<double>(ms) * 1e-3) <<
"s";
4626 static std::string FormatEpochTimeInMillisAsRFC3339(
TimeInMillis ms) {
4627 struct tm time_struct;
4628 if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))
4639 static inline std::string Indent(
size_t width) {
4640 return std::string(width,
' ');
4643 void JsonUnitTestResultPrinter::OutputJsonKey(std::ostream* stream,
4644 const std::string& element_name,
4645 const std::string& name,
4646 const std::string& value,
4647 const std::string& indent,
4649 const std::vector<std::string>& allowed_names =
4650 GetReservedOutputAttributesForElement(element_name);
4652 GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
4653 allowed_names.end())
4654 <<
"Key \"" << name <<
"\" is not allowed for value \"" << element_name
4657 *stream << indent <<
"\"" << name <<
"\": \"" << EscapeJson(value) <<
"\"";
4658 if (comma) *stream <<
",\n";
4661 void JsonUnitTestResultPrinter::OutputJsonKey(
4662 std::ostream* stream,
const std::string& element_name,
4663 const std::string& name,
int value,
const std::string& indent,
bool comma) {
4664 const std::vector<std::string>& allowed_names =
4665 GetReservedOutputAttributesForElement(element_name);
4667 GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
4668 allowed_names.end())
4669 <<
"Key \"" << name <<
"\" is not allowed for value \"" << element_name
4673 if (comma) *stream <<
",\n";
4677 void JsonUnitTestResultPrinter::OutputJsonTestSuiteForTestResult(
4678 ::std::ostream* stream,
const TestResult& result) {
4680 *stream << Indent(4) <<
"{\n";
4681 OutputJsonKey(stream,
"testsuite",
"name",
"NonTestSuiteFailure", Indent(6));
4682 OutputJsonKey(stream,
"testsuite",
"tests", 1, Indent(6));
4684 OutputJsonKey(stream,
"testsuite",
"failures", 1, Indent(6));
4685 OutputJsonKey(stream,
"testsuite",
"disabled", 0, Indent(6));
4686 OutputJsonKey(stream,
"testsuite",
"skipped", 0, Indent(6));
4687 OutputJsonKey(stream,
"testsuite",
"errors", 0, Indent(6));
4688 OutputJsonKey(stream,
"testsuite",
"time",
4689 FormatTimeInMillisAsDuration(result.elapsed_time()),
4691 OutputJsonKey(stream,
"testsuite",
"timestamp",
4692 FormatEpochTimeInMillisAsRFC3339(result.start_timestamp()),
4695 *stream << Indent(6) <<
"\"testsuite\": [\n";
4697 OutputJsonTestCaseForTestResult(stream, result);
4700 *stream <<
"\n" << Indent(6) <<
"]\n" << Indent(4) <<
"}";
4704 void JsonUnitTestResultPrinter::OutputJsonTestCaseForTestResult(
4705 ::std::ostream* stream,
const TestResult& result) {
4707 *stream << Indent(8) <<
"{\n";
4708 OutputJsonKey(stream,
"testcase",
"name",
"", Indent(10));
4709 OutputJsonKey(stream,
"testcase",
"status",
"RUN", Indent(10));
4710 OutputJsonKey(stream,
"testcase",
"result",
"COMPLETED", Indent(10));
4711 OutputJsonKey(stream,
"testcase",
"timestamp",
4712 FormatEpochTimeInMillisAsRFC3339(result.start_timestamp()),
4714 OutputJsonKey(stream,
"testcase",
"time",
4715 FormatTimeInMillisAsDuration(result.elapsed_time()),
4717 OutputJsonKey(stream,
"testcase",
"classname",
"", Indent(10),
false);
4718 *stream << TestPropertiesAsJson(result, Indent(10));
4721 OutputJsonTestResult(stream, result);
4725 void JsonUnitTestResultPrinter::OutputJsonTestInfo(::std::ostream* stream,
4726 const char* test_suite_name,
4727 const TestInfo& test_info) {
4728 const TestResult& result = *test_info.result();
4729 const std::string kTestsuite =
"testcase";
4730 const std::string kIndent = Indent(10);
4732 *stream << Indent(8) <<
"{\n";
4733 OutputJsonKey(stream, kTestsuite,
"name", test_info.name(), kIndent);
4735 if (test_info.value_param() !=
nullptr) {
4736 OutputJsonKey(stream, kTestsuite,
"value_param", test_info.value_param(),
4739 if (test_info.type_param() !=
nullptr) {
4740 OutputJsonKey(stream, kTestsuite,
"type_param", test_info.type_param(),
4744 OutputJsonKey(stream, kTestsuite,
"file", test_info.file(), kIndent);
4745 OutputJsonKey(stream, kTestsuite,
"line", test_info.line(), kIndent,
false);
4747 *stream <<
"\n" << Indent(8) <<
"}";
4753 OutputJsonKey(stream, kTestsuite,
"status",
4754 test_info.should_run() ?
"RUN" :
"NOTRUN", kIndent);
4755 OutputJsonKey(stream, kTestsuite,
"result",
4756 test_info.should_run()
4757 ? (result.Skipped() ?
"SKIPPED" :
"COMPLETED")
4760 OutputJsonKey(stream, kTestsuite,
"timestamp",
4761 FormatEpochTimeInMillisAsRFC3339(result.start_timestamp()),
4763 OutputJsonKey(stream, kTestsuite,
"time",
4764 FormatTimeInMillisAsDuration(result.elapsed_time()), kIndent);
4765 OutputJsonKey(stream, kTestsuite,
"classname", test_suite_name, kIndent,
4767 *stream << TestPropertiesAsJson(result, kIndent);
4769 OutputJsonTestResult(stream, result);
4772 void JsonUnitTestResultPrinter::OutputJsonTestResult(::std::ostream* stream,
4773 const TestResult& result) {
4774 const std::string kIndent = Indent(10);
4778 for (
int i = 0;
i < result.total_part_count(); ++
i) {
4779 const TestPartResult& part = result.GetTestPartResult(
i);
4780 if (part.failed()) {
4782 if (++failures == 1) {
4783 *stream << kIndent <<
"\"" <<
"failures" <<
"\": [\n";
4785 const std::string location =
4787 part.line_number());
4788 const std::string message =
4789 EscapeJson(location +
"\n" + part.message());
4790 *stream << kIndent <<
" {\n"
4791 << kIndent <<
" \"failure\": \"" << message <<
"\",\n"
4792 << kIndent <<
" \"type\": \"\"\n"
4797 if (failures > 0) *stream <<
"\n" << kIndent <<
"]";
4802 for (
int i = 0;
i < result.total_part_count(); ++
i) {
4803 const TestPartResult& part = result.GetTestPartResult(
i);
4804 if (part.skipped()) {
4806 if (++skipped == 1) {
4807 *stream << kIndent <<
"\"" <<
"skipped" <<
"\": [\n";
4809 const std::string location =
4811 part.line_number());
4812 const std::string message =
4813 EscapeJson(location +
"\n" + part.message());
4814 *stream << kIndent <<
" {\n"
4815 << kIndent <<
" \"message\": \"" << message <<
"\"\n"
4820 if (skipped > 0) *stream <<
"\n" << kIndent <<
"]";
4823 *stream <<
"\n" << Indent(8) <<
"}";
4827 void JsonUnitTestResultPrinter::PrintJsonTestSuite(
4828 std::ostream* stream,
const TestSuite& test_suite) {
4829 const std::string kTestsuite =
"testsuite";
4830 const std::string kIndent = Indent(6);
4832 *stream << Indent(4) <<
"{\n";
4833 OutputJsonKey(stream, kTestsuite,
"name", test_suite.name(), kIndent);
4834 OutputJsonKey(stream, kTestsuite,
"tests", test_suite.reportable_test_count(),
4837 OutputJsonKey(stream, kTestsuite,
"failures",
4838 test_suite.failed_test_count(), kIndent);
4839 OutputJsonKey(stream, kTestsuite,
"disabled",
4840 test_suite.reportable_disabled_test_count(), kIndent);
4841 OutputJsonKey(stream, kTestsuite,
"errors", 0, kIndent);
4843 stream, kTestsuite,
"timestamp",
4844 FormatEpochTimeInMillisAsRFC3339(test_suite.start_timestamp()),
4846 OutputJsonKey(stream, kTestsuite,
"time",
4847 FormatTimeInMillisAsDuration(test_suite.elapsed_time()),
4849 *stream << TestPropertiesAsJson(test_suite.ad_hoc_test_result(), kIndent)
4853 *stream << kIndent <<
"\"" << kTestsuite <<
"\": [\n";
4856 for (
int i = 0;
i < test_suite.total_test_count(); ++
i) {
4857 if (test_suite.GetTestInfo(
i)->is_reportable()) {
4863 OutputJsonTestInfo(stream, test_suite.name(), *test_suite.GetTestInfo(
i));
4869 if (test_suite.ad_hoc_test_result().Failed()) {
4873 OutputJsonTestCaseForTestResult(stream, test_suite.ad_hoc_test_result());
4876 *stream <<
"\n" << kIndent <<
"]\n" << Indent(4) <<
"}";
4880 void JsonUnitTestResultPrinter::PrintJsonUnitTest(std::ostream* stream,
4881 const UnitTest& unit_test) {
4882 const std::string kTestsuites =
"testsuites";
4883 const std::string kIndent = Indent(2);
4886 OutputJsonKey(stream, kTestsuites,
"tests", unit_test.reportable_test_count(),
4888 OutputJsonKey(stream, kTestsuites,
"failures", unit_test.failed_test_count(),
4890 OutputJsonKey(stream, kTestsuites,
"disabled",
4891 unit_test.reportable_disabled_test_count(), kIndent);
4892 OutputJsonKey(stream, kTestsuites,
"errors", 0, kIndent);
4894 OutputJsonKey(stream, kTestsuites,
"random_seed", unit_test.random_seed(),
4897 OutputJsonKey(stream, kTestsuites,
"timestamp",
4898 FormatEpochTimeInMillisAsRFC3339(unit_test.start_timestamp()),
4900 OutputJsonKey(stream, kTestsuites,
"time",
4901 FormatTimeInMillisAsDuration(unit_test.elapsed_time()), kIndent,
4904 *stream << TestPropertiesAsJson(unit_test.ad_hoc_test_result(), kIndent)
4907 OutputJsonKey(stream, kTestsuites,
"name",
"AllTests", kIndent);
4908 *stream << kIndent <<
"\"" << kTestsuites <<
"\": [\n";
4911 for (
int i = 0;
i < unit_test.total_test_suite_count(); ++
i) {
4912 if (unit_test.GetTestSuite(
i)->reportable_test_count() > 0) {
4918 PrintJsonTestSuite(stream, *unit_test.GetTestSuite(
i));
4924 if (unit_test.ad_hoc_test_result().Failed()) {
4928 OutputJsonTestSuiteForTestResult(stream, unit_test.ad_hoc_test_result());
4936 void JsonUnitTestResultPrinter::PrintJsonTestList(
4937 std::ostream* stream,
const std::vector<TestSuite*>& test_suites) {
4938 const std::string kTestsuites =
"testsuites";
4939 const std::string kIndent = Indent(2);
4941 int total_tests = 0;
4942 for (
auto test_suite : test_suites) {
4943 total_tests += test_suite->total_test_count();
4945 OutputJsonKey(stream, kTestsuites,
"tests", total_tests, kIndent);
4947 OutputJsonKey(stream, kTestsuites,
"name",
"AllTests", kIndent);
4948 *stream << kIndent <<
"\"" << kTestsuites <<
"\": [\n";
4950 for (
size_t i = 0;
i < test_suites.size(); ++
i) {
4954 PrintJsonTestSuite(stream, *test_suites[
i]);
4963 std::string JsonUnitTestResultPrinter::TestPropertiesAsJson(
4964 const TestResult& result,
const std::string& indent) {
4966 for (
int i = 0;
i < result.test_property_count(); ++
i) {
4967 const TestProperty&
property = result.GetTestProperty(
i);
4969 << indent <<
"\"" <<
property.key() <<
"\": " <<
"\""
4970 << EscapeJson(property.value()) <<
"\"";
4972 return attributes.GetString();
4976 #endif // GTEST_HAS_FILE_SYSTEM
4978 #if GTEST_CAN_STREAM_RESULTS_
4985 std::string StreamingListener::UrlEncode(
const char* str) {
4987 result.reserve(strlen(str) + 1);
4988 for (
char ch = *str; ch !=
'\0'; ch = *++str) {
4994 result.push_back(
'%');
4998 result.push_back(ch);
5005 void StreamingListener::SocketWriter::MakeConnection() {
5007 <<
"MakeConnection() can't be called when there is already a connection.";
5010 memset(&hints, 0,
sizeof(hints));
5011 hints.ai_family = AF_UNSPEC;
5012 hints.ai_socktype = SOCK_STREAM;
5013 addrinfo* servinfo =
nullptr;
5017 const int error_num =
5018 getaddrinfo(host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
5019 if (error_num != 0) {
5020 GTEST_LOG_(WARNING) <<
"stream_result_to: getaddrinfo() failed: "
5021 << gai_strerror(error_num);
5025 for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr !=
nullptr;
5026 cur_addr = cur_addr->ai_next) {
5027 sockfd_ = socket(cur_addr->ai_family, cur_addr->ai_socktype,
5028 cur_addr->ai_protocol);
5029 if (sockfd_ != -1) {
5031 if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
5038 freeaddrinfo(servinfo);
5040 if (sockfd_ == -1) {
5041 GTEST_LOG_(WARNING) <<
"stream_result_to: failed to connect to "
5042 << host_name_ <<
":" << port_num_;
5047 #endif // GTEST_CAN_STREAM_RESULTS__
5056 #ifdef GTEST_HAS_ABSL
5059 if (max_depth <= 0) {
5065 std::vector<void*> raw_stack(max_depth);
5067 const int raw_stack_size =
5068 absl::GetStackTrace(&raw_stack[0], max_depth, skip_count + 1);
5070 void* caller_frame =
nullptr;
5073 caller_frame = caller_frame_;
5076 for (
int i = 0;
i < raw_stack_size; ++
i) {
5077 if (raw_stack[
i] == caller_frame &&
5080 absl::StrAppend(&result, kElidedFramesMarker,
"\n");
5085 const char* symbol =
"(unknown)";
5086 if (absl::Symbolize(raw_stack[
i], tmp,
sizeof(tmp))) {
5091 snprintf(line,
sizeof(line),
" %p: %s\n", raw_stack[i], symbol);
5097 #else // !GTEST_HAS_ABSL
5098 static_cast<void>(max_depth);
5099 static_cast<void>(skip_count);
5101 #endif // GTEST_HAS_ABSL
5105 #ifdef GTEST_HAS_ABSL
5106 void* caller_frame =
nullptr;
5107 if (absl::GetStackTrace(&caller_frame, 1, 3) <= 0) {
5108 caller_frame =
nullptr;
5112 caller_frame_ = caller_frame;
5113 #endif // GTEST_HAS_ABSL
5116 #ifdef GTEST_HAS_DEATH_TEST
5119 class ScopedPrematureExitFile {
5121 explicit ScopedPrematureExitFile(
const char* premature_exit_filepath)
5122 : premature_exit_filepath_(
5123 premature_exit_filepath ? premature_exit_filepath :
"") {
5125 if (!premature_exit_filepath_.empty()) {
5129 FILE* pfile =
posix::FOpen(premature_exit_filepath_.c_str(),
"w");
5130 fwrite(
"0", 1, 1, pfile);
5135 ~ScopedPrematureExitFile() {
5136 #ifndef GTEST_OS_ESP8266
5137 if (!premature_exit_filepath_.empty()) {
5138 int retval =
remove(premature_exit_filepath_.c_str());
5140 GTEST_LOG_(ERROR) <<
"Failed to remove premature exit filepath \""
5141 << premature_exit_filepath_ <<
"\" with error "
5149 const std::string premature_exit_filepath_;
5151 ScopedPrematureExitFile(
const ScopedPrematureExitFile&) =
delete;
5152 ScopedPrematureExitFile& operator=(
const ScopedPrematureExitFile&) =
delete;
5154 #endif // GTEST_HAS_DEATH_TEST
5161 : repeater_(new internal::TestEventRepeater()),
5162 default_result_printer_(nullptr),
5163 default_xml_generator_(nullptr) {}
5201 if (listener !=
nullptr)
Append(listener);
5216 if (listener !=
nullptr)
Append(listener);
5244 #if defined(__BORLANDC__)
5250 #endif // defined(__BORLANDC__)
5275 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5288 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5350 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5354 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5399 if (env ==
nullptr) {
5412 const char* file_name,
int line_number,
5413 const std::string& message,
5414 const std::string& os_stack_trace)
5420 if (!impl_->gtest_trace_stack().empty()) {
5423 for (
size_t i = impl_->gtest_trace_stack().size();
i > 0; --
i) {
5431 if (os_stack_trace.c_str() !=
nullptr && !os_stack_trace.empty()) {
5437 const TestPartResult result = TestPartResult(
5438 result_type, file_name, line_number, msg.
GetString().c_str());
5439 impl_->GetTestPartResultReporterForCurrentThread()->ReportTestPartResult(
5442 if (result_type != TestPartResult::kSuccess &&
5443 result_type != TestPartResult::kSkip) {
5450 #if defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_PHONE) && \
5451 !defined(GTEST_OS_WINDOWS_RT)
5456 #elif (!defined(__native_client__)) && \
5457 ((defined(__clang__) || defined(__GNUC__)) && \
5458 (defined(__x86_64__) || defined(__i386__)))
5461 #elif GTEST_HAS_BUILTIN(__builtin_trap)
5463 #elif defined(SIGTRAP)
5469 *
static_cast<volatile int*
>(
nullptr) = 1;
5470 #endif // GTEST_OS_WINDOWS
5472 #if GTEST_HAS_EXCEPTIONS
5473 throw internal::GoogleTestFailureException(result);
5489 const std::string& value) {
5499 #ifdef GTEST_HAS_DEATH_TEST
5500 const bool in_death_test_child_process =
5524 const internal::ScopedPrematureExitFile premature_exit_file(
5525 in_death_test_child_process
5529 const bool in_death_test_child_process =
false;
5530 #endif // GTEST_HAS_DEATH_TEST
5536 #ifdef GTEST_OS_WINDOWS
5541 if (
impl()->catch_exceptions() || in_death_test_child_process) {
5542 #if !defined(GTEST_OS_WINDOWS_MOBILE) && !defined(GTEST_OS_WINDOWS_PHONE) && \
5543 !defined(GTEST_OS_WINDOWS_RT) && !defined(GTEST_OS_WINDOWS_GAMES)
5545 SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
5546 SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
5547 #endif // !GTEST_OS_WINDOWS_MOBILE
5549 #if (defined(_MSC_VER) || defined(GTEST_OS_WINDOWS_MINGW)) && \
5550 !defined(GTEST_OS_WINDOWS_MOBILE)
5554 _set_error_mode(_OUT_TO_STDERR);
5557 #if defined(_MSC_VER) && !defined(GTEST_OS_WINDOWS_MOBILE)
5564 _set_abort_behavior(
5566 _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
5572 if (!IsDebuggerPresent()) {
5573 (
void)_CrtSetReportMode(_CRT_ASSERT,
5574 _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
5575 (
void)_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
5580 (
void)in_death_test_child_process;
5581 #endif // GTEST_OS_WINDOWS
5585 "auxiliary test code (environments or event listeners)")
5590 #if GTEST_HAS_FILE_SYSTEM
5594 return impl_->original_working_dir_.c_str();
5596 #endif // GTEST_HAS_FILE_SYSTEM
5607 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5644 impl_->gtest_trace_stack().push_back(trace);
5653 namespace internal {
5658 default_global_test_part_result_reporter_(this),
5659 default_per_thread_test_part_result_reporter_(this),
5661 &default_global_test_part_result_reporter_),
5662 per_thread_test_part_result_reporter_(
5663 &default_per_thread_test_part_result_reporter_),
5664 parameterized_test_registry_(),
5665 parameterized_tests_registered_(
false),
5666 last_death_test_suite_(-1),
5667 current_test_suite_(nullptr),
5668 current_test_info_(nullptr),
5669 ad_hoc_test_result_(),
5670 os_stack_trace_getter_(nullptr),
5671 post_flag_parse_init_performed_(
false),
5674 start_timestamp_(0),
5676 #ifdef GTEST_HAS_DEATH_TEST
5677 death_test_factory_(new DefaultDeathTestFactory),
5680 catch_exceptions_(
false) {
5700 std::string xml_element;
5704 xml_element =
"testcase";
5707 xml_element =
"testsuite";
5710 xml_element =
"testsuites";
5716 #ifdef GTEST_HAS_DEATH_TEST
5719 void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
5720 if (internal_run_death_test_flag_ !=
nullptr)
5723 #endif // GTEST_HAS_DEATH_TEST
5729 #if GTEST_HAS_FILE_SYSTEM
5730 if (output_format ==
"xml") {
5733 }
else if (output_format ==
"json") {
5736 }
else if (!output_format.empty()) {
5737 GTEST_LOG_(WARNING) <<
"WARNING: unrecognized output format \""
5738 << output_format <<
"\" ignored.";
5741 if (!output_format.empty()) {
5742 GTEST_LOG_(ERROR) <<
"ERROR: alternative output formats require "
5743 <<
"GTEST_HAS_FILE_SYSTEM to be enabled";
5745 #endif // GTEST_HAS_FILE_SYSTEM
5748 #if GTEST_CAN_STREAM_RESULTS_
5751 void UnitTestImpl::ConfigureStreamingOutput() {
5753 if (!target.empty()) {
5754 const size_t pos = target.find(
':');
5755 if (pos != std::string::npos) {
5757 new StreamingListener(target.substr(0, pos), target.substr(pos + 1)));
5759 GTEST_LOG_(WARNING) <<
"unrecognized streaming target \"" << target
5764 #endif // GTEST_CAN_STREAM_RESULTS_
5776 #if defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
5779 #endif // defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
5781 #ifdef GTEST_HAS_DEATH_TEST
5782 InitDeathTestSubprocessControlInfo();
5783 SuppressTestEventsIfInSubprocess();
5784 #endif // GTEST_HAS_DEATH_TEST
5799 #if GTEST_CAN_STREAM_RESULTS_
5801 ConfigureStreamingOutput();
5802 #endif // GTEST_CAN_STREAM_RESULTS_
5804 #ifdef GTEST_HAS_ABSL
5806 absl::FailureSignalHandlerOptions options;
5807 absl::InstallFailureSignalHandler(options);
5809 #endif // GTEST_HAS_ABSL
5826 const std::string& test_suite_name,
const char* type_param,
5840 return item_it->second;
5844 auto*
const new_test_suite =
5845 new TestSuite(test_suite_name, type_param, set_up_tc, tear_down_tc);
5850 if (death_test_suite_filter.MatchesName(test_suite_name)) {
5864 return new_test_suite;
5893 #if GTEST_HAS_FILE_SYSTEM
5898 #endif // GTEST_HAS_FILE_SYSTEM
5902 bool in_subprocess_for_death_test =
false;
5904 #ifdef GTEST_HAS_DEATH_TEST
5905 in_subprocess_for_death_test = (internal_run_death_test_flag_ !=
nullptr);
5906 #if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
5907 if (in_subprocess_for_death_test) {
5908 GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_();
5910 #endif // defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
5911 #endif // GTEST_HAS_DEATH_TEST
5914 in_subprocess_for_death_test);
5918 const bool has_tests_to_run =
5932 bool failed =
false;
5941 const int repeat = in_subprocess_for_death_test ? 1 :
GTEST_FLAG_GET(repeat);
5944 const bool gtest_repeat_forever = repeat < 0;
5952 const bool recreate_environments_when_repeating =
5954 gtest_repeat_forever;
5956 for (
int i = 0; gtest_repeat_forever ||
i != repeat;
i++) {
5976 if (has_tests_to_run) {
5979 if (
i == 0 || recreate_environments_when_repeating) {
5993 const TestPartResult& test_part_result =
5995 if (test_part_result.type() == TestPartResult::kSkip) {
5996 const std::string& result = test_part_result.message();
5997 printf(
"%s\n", result.c_str());
6026 if (
i == repeat - 1 || recreate_environments_when_repeating) {
6060 bool delete_environment_on_teardown =
true;
6061 if (delete_environment_on_teardown) {
6066 if (!gtest_is_initialized_before_run_all_tests) {
6069 "\nIMPORTANT NOTICE - DO NOT IGNORE:\n"
6071 "() before calling RUN_ALL_TESTS(). This is INVALID. Soon " GTEST_NAME_
6072 " will start to enforce the valid usage. "
6073 "Please fix it ASAP, or IT WILL START TO FAIL.\n");
6079 #if GTEST_HAS_FILE_SYSTEM
6086 if (test_shard_file !=
nullptr) {
6088 if (file ==
nullptr) {
6090 "Could not write to the test shard status file \"%s\" "
6091 "specified by the %s environment variable.\n",
6099 #endif // GTEST_HAS_FILE_SYSTEM
6107 bool ShouldShard(
const char* total_shards_env,
const char* shard_index_env,
6108 bool in_subprocess_for_death_test) {
6109 if (in_subprocess_for_death_test) {
6116 if (total_shards == -1 && shard_index == -1) {
6118 }
else if (total_shards == -1 && shard_index != -1) {
6119 const Message msg =
Message() <<
"Invalid environment variables: you have "
6126 }
else if (total_shards != -1 && shard_index == -1) {
6128 <<
"Invalid environment variables: you have "
6134 }
else if (shard_index < 0 || shard_index >= total_shards) {
6136 Message() <<
"Invalid environment variables: we require 0 <= "
6145 return total_shards > 1;
6153 if (str_val ==
nullptr) {
6159 str_val, &result)) {
6170 return (test_id % total_shards) == shard_index;
6188 const PositiveAndNegativeUnitTestFilter gtest_flag_filter(
6195 int num_runnable_tests = 0;
6196 int num_selected_tests = 0;
6198 const std::string& test_suite_name = test_suite->name_;
6199 test_suite->set_should_run(
false);
6201 for (
TestInfo* test_info : test_suite->test_info_list()) {
6202 const std::string& test_name = test_info->name_;
6205 const bool is_disabled =
6206 disable_test_filter.MatchesName(test_suite_name) ||
6207 disable_test_filter.MatchesName(test_name);
6208 test_info->is_disabled_ = is_disabled;
6210 const bool matches_filter =
6211 gtest_flag_filter.MatchesTest(test_suite_name, test_name);
6212 test_info->matches_filter_ = matches_filter;
6214 const bool is_runnable =
6218 const bool is_in_another_shard =
6221 test_info->is_in_another_shard_ = is_in_another_shard;
6222 const bool is_selected = is_runnable && !is_in_another_shard;
6224 num_runnable_tests += is_runnable;
6225 num_selected_tests += is_selected;
6227 test_info->should_run_ = is_selected;
6228 test_suite->set_should_run(test_suite->should_run() || is_selected);
6231 return num_selected_tests;
6239 if (str !=
nullptr) {
6240 for (
int i = 0; *str !=
'\0'; ++str) {
6241 if (
i >= max_length) {
6259 const int kMaxParamLength = 250;
6262 bool printed_test_suite_name =
false;
6264 for (
size_t j = 0; j < test_suite->test_info_list().size(); j++) {
6265 const TestInfo*
const test_info = test_suite->test_info_list()[j];
6267 if (!printed_test_suite_name) {
6268 printed_test_suite_name =
true;
6269 printf(
"%s.", test_suite->name());
6270 if (test_suite->type_param() !=
nullptr) {
6278 printf(
" %s", test_info->
name());
6290 #if GTEST_HAS_FILE_SYSTEM
6292 if (output_format ==
"xml" || output_format ==
"json") {
6295 std::stringstream stream;
6296 if (output_format ==
"xml") {
6297 XmlUnitTestResultPrinter(
6299 .PrintXmlTestsList(&stream, test_suites_);
6300 }
else if (output_format ==
"json") {
6301 JsonUnitTestResultPrinter(
6303 .PrintJsonTestList(&stream, test_suites_);
6308 #endif // GTEST_HAS_FILE_SYSTEM
6329 #ifdef GTEST_OS_STACK_TRACE_GETTER_
6333 #endif // GTEST_OS_STACK_TRACE_GETTER_
6362 test_suite->ShuffleTests(
random());
6396 class ClassUniqueToAlwaysTrue {};
6399 bool IsTrue(
bool condition) {
return condition; }
6402 #if GTEST_HAS_EXCEPTIONS
6405 if (
IsTrue(
false))
throw ClassUniqueToAlwaysTrue();
6406 #endif // GTEST_HAS_EXCEPTIONS
6414 const size_t prefix_len = strlen(prefix);
6415 if (strncmp(*pstr, prefix, prefix_len) == 0) {
6416 *pstr += prefix_len;
6428 bool def_optional) {
6430 if (str ==
nullptr || flag_name ==
nullptr)
return nullptr;
6433 const std::string flag_str =
6435 const size_t flag_len = flag_str.length();
6436 if (strncmp(str, flag_str.c_str(), flag_len) != 0)
return nullptr;
6439 const char* flag_end = str + flag_len;
6442 if (def_optional && (flag_end[0] ==
'\0')) {
6449 if (flag_end[0] !=
'=')
return nullptr;
6452 return flag_end + 1;
6465 static bool ParseFlag(
const char* str,
const char* flag_name,
bool* value) {
6467 const char*
const value_str =
ParseFlagValue(str, flag_name,
true);
6470 if (value_str ==
nullptr)
return false;
6473 *value = !(*value_str ==
'0' || *value_str ==
'f' || *value_str ==
'F');
6481 bool ParseFlag(
const char* str,
const char* flag_name, int32_t* value) {
6483 const char*
const value_str =
ParseFlagValue(str, flag_name,
false);
6486 if (value_str ==
nullptr)
return false;
6497 template <
typename String>
6500 const char*
const value_str =
ParseFlagValue(str, flag_name,
false);
6503 if (value_str ==
nullptr)
return false;
6534 GTestColor color = GTestColor::kDefault;
6541 const char*
p = strchr(str,
'@');
6549 const char ch = p[1];
6553 }
else if (ch ==
'D') {
6554 color = GTestColor::kDefault;
6555 }
else if (ch ==
'R') {
6556 color = GTestColor::kRed;
6557 }
else if (ch ==
'G') {
6558 color = GTestColor::kGreen;
6559 }
else if (ch ==
'Y') {
6560 color = GTestColor::kYellow;
6568 "This program contains tests written using " GTEST_NAME_
6569 ". You can use the\n"
6570 "following command line flags to control its behavior:\n"
6575 " List the names of all tests instead of running them. The name of\n"
6576 " TEST(Foo, Bar) is \"Foo.Bar\".\n"
6578 "filter=@YPOSITIVE_PATTERNS"
6579 "[@G-@YNEGATIVE_PATTERNS]@D\n"
6580 " Run only the tests whose name matches one of the positive patterns "
6582 " none of the negative patterns. '?' matches any single character; "
6584 " matches any substring; ':' separates two patterns.\n"
6586 "also_run_disabled_tests@D\n"
6587 " Run all disabled tests too.\n"
6591 "repeat=@Y[COUNT]@D\n"
6592 " Run the tests repeatedly; use a negative count to repeat forever.\n"
6595 " Randomize tests' orders on every iteration.\n"
6597 "random_seed=@Y[NUMBER]@D\n"
6598 " Random number seed to use for shuffling test orders (between 1 and\n"
6599 " 99999, or 0 to use a seed based on the current time).\n"
6601 "recreate_environments_when_repeating@D\n"
6602 " Sets up and tears down the global test environment on each repeat\n"
6607 "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
6608 " Enable/disable colored output. The default is @Gauto@D.\n"
6611 " Only print test failures.\n"
6614 " Don't print the elapsed time of each test.\n"
6617 "@Y|@G:@YFILE_PATH]@D\n"
6618 " Generate a JSON or XML report in the given directory or with the "
6620 " file name. @YFILE_PATH@D defaults to @Gtest_detail.xml@D.\n"
6621 #if GTEST_CAN_STREAM_RESULTS_
6623 "stream_result_to=@YHOST@G:@YPORT@D\n"
6624 " Stream test results to the given server.\n"
6625 #endif // GTEST_CAN_STREAM_RESULTS_
6627 "Assertion Behavior:\n"
6628 #if defined(GTEST_HAS_DEATH_TEST) && !defined(GTEST_OS_WINDOWS)
6630 "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
6631 " Set the default death test style.\n"
6632 #endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
6634 "break_on_failure@D\n"
6635 " Turn assertion failures into debugger break-points.\n"
6637 "throw_on_failure@D\n"
6638 " Turn assertion failures into C++ exceptions for use by an external\n"
6639 " test framework.\n"
6641 "catch_exceptions=0@D\n"
6642 " Do not report exceptions as test failures. Instead, allow them\n"
6643 " to crash the program or throw a pop-up (on Windows).\n"
6646 "list_tests@D, you can alternatively set "
6647 "the corresponding\n"
6648 "environment variable of a flag (all letters in upper-case). For example, "
6650 "disable colored text output, you can either specify "
6652 "color=no@D or set\n"
6654 "COLOR@D environment variable to @Gno@D.\n"
6656 "For more information, please read the " GTEST_NAME_
6657 " documentation at\n"
6660 "(not one in your own code or tests), please report it to\n"
6664 #define GTEST_INTERNAL_PARSE_FLAG(flag_name) \
6666 auto value = GTEST_FLAG_GET(flag_name); \
6667 if (ParseFlag(arg, #flag_name, &value)) { \
6668 GTEST_FLAG_SET(flag_name, value); \
6697 #if GTEST_USE_OWN_FLAGFILE_FLAG_ && GTEST_HAS_FILE_SYSTEM
6698 static void LoadFlagsFromFile(
const std::string& path) {
6706 std::vector<std::string> lines;
6708 for (
size_t i = 0;
i < lines.size(); ++
i) {
6709 if (lines[
i].empty())
continue;
6713 #endif // GTEST_USE_OWN_FLAGFILE_FLAG_ && GTEST_HAS_FILE_SYSTEM
6718 template <
typename CharType>
6720 std::string flagfile_value;
6721 for (
int i = 1;
i < *argc;
i++) {
6723 const char*
const arg = arg_string.c_str();
6727 bool remove_flag =
false;
6730 #if GTEST_USE_OWN_FLAGFILE_FLAG_ && GTEST_HAS_FILE_SYSTEM
6731 }
else if (
ParseFlag(arg,
"flagfile", &flagfile_value)) {
6733 LoadFlagsFromFile(flagfile_value);
6735 #endif // GTEST_USE_OWN_FLAGFILE_FLAG_ && GTEST_HAS_FILE_SYSTEM
6744 for (
int j = i + 1; j < *argc; ++j) {
6745 argv[j - 1] = argv[j];
6752 argv[*argc] =
nullptr;
6775 #ifdef GTEST_HAS_ABSL_FLAGS
6776 if (*argc <= 0)
return;
6778 std::vector<char*> positional_args;
6779 std::vector<absl::UnrecognizedFlag> unrecognized_flags;
6780 absl::ParseAbseilFlagsOnly(*argc, argv, positional_args, unrecognized_flags);
6781 absl::flat_hash_set<absl::string_view> unrecognized;
6782 for (
const auto& flag : unrecognized_flags) {
6783 unrecognized.insert(flag.flag_name);
6785 absl::flat_hash_set<char*> positional;
6786 for (
const auto& arg : positional_args) {
6787 positional.insert(arg);
6792 for (; in_pos < *argc; ++in_pos) {
6793 char* arg = argv[in_pos];
6794 absl::string_view arg_str(arg);
6795 if (absl::ConsumePrefix(&arg_str,
"--")) {
6798 if (unrecognized.contains(arg_str)) {
6799 argv[out_pos++] = argv[in_pos];
6804 if (arg_str.empty()) {
6811 if (positional.contains(arg)) {
6812 argv[out_pos++] = arg;
6817 while (in_pos < *argc) {
6818 argv[out_pos++] = argv[in_pos++];
6822 argv[out_pos] =
nullptr;
6831 #ifndef GTEST_OS_IOS
6832 if (*_NSGetArgv() == argv) {
6833 *_NSGetArgc() = *argc;
6846 template <
typename CharType>
6851 if (*argc <= 0)
return;
6854 for (
int i = 0;
i != *argc;
i++) {
6858 #ifdef GTEST_HAS_ABSL
6859 absl::InitializeSymbolizer(
g_argvs[0].c_str());
6861 #ifdef GTEST_HAS_ABSL_FLAGS
6864 absl::SetProgramUsageMessage(absl::StrReplaceAll(
6866 {{
"@D",
""}, {
"@R",
""}, {
"@G",
""}, {
"@Y",
""}, {
"@@",
"@"}}));
6867 #endif // GTEST_HAS_ABSL_FLAGS
6868 #endif // GTEST_HAS_ABSL
6886 #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6887 GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
6888 #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6890 #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6896 #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6897 GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
6898 #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6900 #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6908 const auto arg0 =
"dummy";
6909 char* argv0 =
const_cast<char*
>(arg0);
6910 char** argv = &argv0;
6912 #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6913 GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(&argc, argv);
6914 #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6916 #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6919 #if !defined(GTEST_CUSTOM_TEMPDIR_FUNCTION_) || \
6920 !defined(GTEST_CUSTOM_SRCDIR_FUNCTION_)
6926 std::initializer_list<const char*> environment_variables,
6927 const char* fallback,
char separator) {
6928 for (
const char* variable_name : environment_variables) {
6930 if (value !=
nullptr && value[0] !=
'\0') {
6931 if (value[strlen(value) - 1] != separator) {
6932 return std::string(value).append(1, separator);
6942 #if defined(GTEST_CUSTOM_TEMPDIR_FUNCTION_)
6943 return GTEST_CUSTOM_TEMPDIR_FUNCTION_();
6944 #elif defined(GTEST_OS_WINDOWS) || defined(GTEST_OS_WINDOWS_MOBILE)
6945 return GetDirFromEnv({
"TEST_TMPDIR",
"TEMP"},
"\\temp\\",
'\\');
6946 #elif defined(GTEST_OS_LINUX_ANDROID)
6947 return GetDirFromEnv({
"TEST_TMPDIR",
"TMPDIR"},
"/data/local/tmp/",
'/');
6949 return GetDirFromEnv({
"TEST_TMPDIR",
"TMPDIR"},
"/tmp/",
'/');
6953 #if GTEST_HAS_FILE_SYSTEM && !defined(GTEST_CUSTOM_SRCDIR_FUNCTION_)
6956 static std::string GetCurrentExecutableDirectory() {
6958 return argv_0.RemoveFileName().string();
6962 #if GTEST_HAS_FILE_SYSTEM
6964 #if defined(GTEST_CUSTOM_SRCDIR_FUNCTION_)
6965 return GTEST_CUSTOM_SRCDIR_FUNCTION_();
6966 #elif defined(GTEST_OS_WINDOWS) || defined(GTEST_OS_WINDOWS_MOBILE)
6967 return GetDirFromEnv({
"TEST_SRCDIR"}, GetCurrentExecutableDirectory().c_str(),
6969 #elif defined(GTEST_OS_LINUX_ANDROID)
6970 return GetDirFromEnv({
"TEST_SRCDIR"}, GetCurrentExecutableDirectory().c_str(),
6973 return GetDirFromEnv({
"TEST_SRCDIR"}, GetCurrentExecutableDirectory().c_str(),
const char * file() const
GTEST_API_ bool g_help_flag
int failed_test_count() const
void SetDefaultResultPrinter(TestEventListener *listener)
TestPartResultReporterInterface * GetTestPartResultReporterForCurrentThread()
class UnitTestImpl * GetUnitTestImpl()
void AddTestInfo(internal::SetUpTestSuiteFunc set_up_tc, internal::TearDownTestSuiteFunc tear_down_tc, TestInfo *test_info)
std::vector< Environment * > & environments()
GTEST_API_ bool IsTrue(bool condition)
void RecordProperty(const std::string &xml_element, const TestProperty &test_property)
static std::string FormatTestSuiteCount(int test_suite_count)
GTEST_API_ int32_t Int32FromGTestEnv(const char *flag, int32_t default_val)
#define GTEST_REPEATER_METHOD_(Name, Type)
TestSuite(const std::string &name, const char *a_type_param, internal::SetUpTestSuiteFunc set_up_tc, internal::TearDownTestSuiteFunc tear_down_tc)
void ReportFailureInUnknownLocation(TestPartResult::Type result_type, const std::string &message)
int disabled_test_count() const
void set_current_test_info(TestInfo *a_current_test_info) GTEST_LOCK_EXCLUDED_(mutex_)
Result HandleExceptionsInMethodIfSupported(T *object, Result(T::*method)(), const char *location)
static bool HasFatalFailure()
std::vector< int > test_suite_indices_
int successful_test_count() const
void OnEnvironmentsSetUpStart(const UnitTest &unit_test) override
void UponLeavingGTest() override
void OnTestProgramEnd(const UnitTest ¶meter) override
const TestSuite * GetTestSuite(int i) const
int reportable_disabled_test_count() const
const TestInfo * GetTestInfo(int i) const
UnitTestFilter negative_filter_
TimeInMillis elapsed_time() const
static bool HasGoogleTestFlagPrefix(const char *str)
void OnEnvironmentsSetUpStart(const UnitTest &) override
void RegisterInstantiation(const char *test_suite_name)
const TestResult * ad_hoc_test_result() const
void OnEnvironmentsSetUpEnd(const UnitTest &) override
static const char kDisableTestFilter[]
E GetElementOr(const std::vector< E > &v, int i, E default_value)
static AssertionResult HasOneFailure(const char *, const char *, const char *, const TestPartResultArray &results, TestPartResult::Type type, const std::string &substr)
int failed_test_count() const
std::vector< TestSuite * > test_suites_
constexpr uint32_t kMaxCodePoint4
virtual void OnTestCaseStart(const TestCase &)
AssertionResult AssertionFailure()
int total_test_count() const
TimeInMillis elapsed_time_
virtual void OnEnvironmentsTearDownStart(const UnitTest &unit_test)=0
static const char * TestPartResultTypeToString(TestPartResult::Type type)
GTEST_API_ std::vector< EditType > CalculateOptimalEdits(const std::vector< size_t > &left, const std::vector< size_t > &right)
void OnTestDisabled(const TestInfo &) override
std::vector< Environment * > environments_
GTEST_API_ int32_t Int32FromEnvOrDie(const char *env_var, int32_t default_val)
int reportable_test_count() const
GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms)
MarkAsIgnored(const char *test_suite)
int successful_test_suite_count() const
internal::ParameterizedTestSuiteRegistry & parameterized_test_registry()
void set_current_test_info(TestInfo *a_current_test_info)
TestPartResultReporterInterface * GetGlobalTestPartResultReporter()
#define EXPECT_PRED_FORMAT3(pred_format, v1, v2, v3)
std::vector< TestInfo * > test_info_list_
internal::TestEventRepeater * repeater_
void RegisterParameterizedTests()
::std::string PrintToString(const T &value)
GTEST_API_ AssertionResult CmpHelperSTRCASEEQ(const char *s1_expression, const char *s2_expression, const char *s1, const char *s2)
int GetNextRandomSeed(int seed)
static void ClearTestResult(TestInfo *test_info)
GTEST_API_ AssertionResult CmpHelperSTREQ(const char *s1_expression, const char *s2_expression, const char *s1, const char *s2)
virtual Test * CreateTest()=0
#define GTEST_FLAG_PREFIX_DASH_
const char * StringFromGTestEnv(const char *flag, const char *default_val)
void OnEnvironmentsTearDownStart(const UnitTest &unit_test) override
TestSuite * GetMutableTestSuite(int i)
#define GTEST_LOG_(severity)
static bool TestSuitePassed(const TestSuite *test_suite)
static bool EndsWithCaseInsensitive(const std::string &str, const std::string &suffix)
GTEST_API_ bool ShouldUseColor(bool stdout_is_tty)
GTEST_API_ AssertionResult CmpHelperSTRCASENE(const char *s1_expression, const char *s2_expression, const char *s1, const char *s2)
static bool ParseGoogleTestFlag(const char *const arg)
TestEventListener * Release(TestEventListener *listener)
GTEST_API_ bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id)
void ListTestsMatchingFilter()
#define GTEST_DEFINE_int32_(name, default_val, doc)
static const char * GetDefaultFilter()
void OnTestIterationStart(const UnitTest &unit_test, int iteration) override
static bool TestPartNonfatallyFailed(const TestPartResult &result)
TestEventListener * repeater()
void OnTestEnd(const TestInfo &test_info) override
TimeInMillis start_timestamp() const
void OnEnvironmentsSetUpEnd(const UnitTest ¶meter) override
std::list< std::pair< char, const char * > > hunk_adds_
TestPartResult::Type const type
virtual void OnTestIterationStart(const UnitTest &unit_test, int iteration)=0
TestSuite * GetMutableSuiteCase(int i)
uint32_t Generate(uint32_t range)
internal::Mutex global_test_part_result_reporter_mutex_
void SetGlobalTestPartResultReporter(TestPartResultReporterInterface *reporter)
void RecordProperty(const std::string &key, const std::string &value)
GTEST_API_ void RegisterTypeParameterizedTestSuiteInstantiation(const char *case_name)
static bool TestPassed(const TestInfo *test_info)
virtual std::string CurrentStackTrace(int max_depth, int skip_count)=0
int test_to_run_count() const
Result HandleSehExceptionsInMethodIfSupported(T *object, Result(T::*method)(), const char *location)
static const char *const kReservedTestSuiteAttributes[]
virtual void OnEnvironmentsSetUpStart(const UnitTest &unit_test)=0
void OnTestIterationStart(const UnitTest &, int) override
#define GTEST_PROJECT_URL_
TestEventRepeater & operator=(const TestEventRepeater &)=delete
static const char kDeathTestSuiteFilter[]
void OnTestSuiteEnd(const TestSuite ¶meter) override
void set_elapsed_time(TimeInMillis elapsed)
GTEST_API_ AssertionResult DoubleNearPredFormat(const char *expr1, const char *expr2, const char *abs_error_expr, double val1, double val2, double abs_error)
Message & operator<<(const T &val)
GTEST_API_ bool SkipPrefix(const char *prefix, const char **pstr)
void OnTestProgramStart(const UnitTest ¶meter) override
#define GTEST_DEFINE_bool_(name, default_val, doc)
virtual void OnTestStart(const TestInfo &test_info)=0
void OnTestIterationEnd(const UnitTest &unit_test, int iteration) override
void OnEnvironmentsTearDownEnd(const UnitTest &) override
static bool ValidateTestProperty(const std::string &xml_element, const TestProperty &test_property)
void operator=(const Message &message) const
int reportable_disabled_test_count() const
const TestPartResult & GetTestPartResult(int i) const
const TestProperty & GetTestProperty(int i) const
const char * GetEnv(const char *name)
const char * name() const
static void PrintSkippedTests(const UnitTest &unit_test)
bool IsUtf16SurrogatePair(wchar_t first, wchar_t second)
GTEST_API_ std::string SrcDir()
void Append(TestEventListener *listener)
GTEST_API_ bool ShouldShard(const char *total_shards_str, const char *shard_index_str, bool in_subprocess_for_death_test)
static void SetUpEnvironment(Environment *env)
UnitTestImpl *const unit_test_
static const char kTestTotalShards[]
std::string CurrentStackTrace(int max_depth, int skip_count) override
void SuppressEventForwarding(bool)
static std::string GetAbsolutePathToOutputFile()
TestResult ad_hoc_test_result_
static std::string FormatByte(unsigned char value)
int reportable_test_count() const
std::string CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_ GTEST_NO_TAIL_CALL_
int failed_test_count() const
#define GTEST_LOCK_EXCLUDED_(locks)
void OnTestProgramEnd(const UnitTest &) override
void OnTestCaseStart(const TestSuite ¶meter) override
void OnTestStart(const TestInfo &) override
const TestSuite * GetTestSuite(int i) const
static const char *const kElidedFramesMarker
static std::vector< std::string > GetReservedAttributesForElement(const std::string &xml_element)
void(*)( TearDownTestSuiteFunc)
AssertHelperData *const data_
void PushGTestTrace(const internal::TraceInfo &trace) GTEST_LOCK_EXCLUDED_(mutex_)
GTEST_API_ std::vector< std::string > GetArgvs()
static std::string FormatHexInt(int value)
OsStackTraceGetterInterface * os_stack_trace_getter_
static const char * ParseFlagValue(const char *str, const char *flag_name, bool def_optional)
GTEST_API_ void ReportInvalidTestSuiteType(const char *test_suite_name, const CodeLocation &code_location)
TimeInMillis start_timestamp() const
int total_test_count() const
std::string StreamableToString(const T &streamable)
std::list< std::pair< char, const char * > > hunk_
static const char kTestShardStatusFile[]
static const char * GetAnsiColorCode(GTestColor color)
GTEST_API_ std::string ReadEntireFile(FILE *file)
GTEST_API_ std::string CodePointToUtf8(uint32_t code_point)
void RunTearDownTestSuite()
bool HasNonfatalFailure() const
int failed_test_suite_count() const
GTEST_API_ bool ParseInt32(const Message &src_text, const char *str, int32_t *value)
int reportable_test_count() const
GTEST_API_::std::string FormatFileLocation(const char *file, int line)
internal::TestFactoryBase *const factory_
void SplitString(const ::std::string &str, char delimiter,::std::vector<::std::string > *dest)
void OnEnvironmentsTearDownEnd(const UnitTest ¶meter) override
void PostFlagParsingInit()
int successful_test_suite_count() const
GTEST_API_ std::string GetCurrentOsStackTraceExceptTop(int skip_count)
const internal::TypeId fixture_class_id_
int last_death_test_suite_
#define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check)
std::set< std::string > * GetIgnoredParameterizedTestSuites()
void set_os_stack_trace_getter(OsStackTraceGetterInterface *getter)
internal::TypeParameterizedTestSuiteRegistry type_parameterized_test_registry_
const std::string error_message_
GTEST_API_ TypeId GetTestTypeId()
#define GTEST_NO_TAIL_CALL_
TimeInMillis start_timestamp_
static std::string FormatCountableNoun(int count, const char *singular_form, const char *plural_form)
std::list< std::pair< char, const char * > > hunk_removes_
UnitTestFilter positive_filter_
const char * name() const
CacheTaylor< T > diff(const CacheTaylor< T > &x, int n=1)
Compute Taylor series of n-th derivative of x.
int test_case_to_run_count() const
#define GTEST_FLAG_PREFIX_UPPER_
expr expr1 expr1 expr1 c expr2 expr1 expr2 expr1 expr2 expr1 expr1 expr1 expr1 c expr2 expr1 expr2 expr1 expr2 expr1 expr1 expr1 expr1 c *expr2 expr1 expr2 expr1 expr2 expr1 expr1 expr1 expr1 c expr2 expr1 expr2 expr1 expr2 expr1 expr1 expr1 expr2 expr1 expr2 expr1 expr1 expr1 expr2 expr1 expr2 expr1 expr1 expr1 c
virtual void OnTestIterationEnd(const UnitTest &unit_test, int iteration)=0
std::vector< TestEventListener * > listeners_
void OnTestStart(const TestInfo &test_info) override
int test_to_run_count() const
TestInfo * GetMutableTestInfo(int i)
virtual void OnTestProgramEnd(const UnitTest &unit_test)=0
OsStackTraceGetterInterface * os_stack_trace_getter()
void ReportTestPartResult(const TestPartResult &result) override
void OnTestDisabled(const TestInfo &test_info) override
AssertionResult AssertionSuccess()
void OnTestPartResult(const TestPartResult &result) override
int test_suite_to_run_count() const
#define GTEST_REVERSE_REPEATER_METHOD_(Name, Type)
void set_forwarding_enabled(bool enable)
TestResult ad_hoc_test_result_
static bool CaseInsensitiveWideCStringEquals(const wchar_t *lhs, const wchar_t *rhs)
#define GTEST_CHECK_(condition)
std::string const message
static std::string FormatHexUInt32(uint32_t value)
static std::string GetOutputFormat()
TestEventListeners & listeners()
SimpleFad< ValueT > min(const SimpleFad< ValueT > &a, const SimpleFad< ValueT > &b)
bool parameterized_tests_registered_
void SetDefaultXmlGenerator(TestEventListener *listener)
bool forwarding_enabled() const
const int kMaxStackTraceDepth
std::vector< TestPartResult > test_part_results_
std::vector< TestProperty > test_properties_
static const char kValueParamLabel[]
static bool CStringEquals(const char *lhs, const char *rhs)
void RecordProperty(const TestProperty &test_property)
void SetTestPartResultReporterForCurrentThread(TestPartResultReporterInterface *reporter)
static const char *const kReservedTestSuitesAttributes[]
AssertHelper(TestPartResult::Type type, const char *file, int line, const char *message)
void OnTestCaseEnd(const TestCase &test_case) override
int successful_test_count() const
void OnTestProgramStart(const UnitTest &) override
static bool WideCStringEquals(const wchar_t *lhs, const wchar_t *rhs)
GTEST_API_ const TypeId kTestTypeIdInGoogleTest
internal::UnitTestImpl * impl_
static bool GTestIsInitialized()
void OnTestPartResult(const TestPartResult ¶meter) override
int total_test_suite_count() const
std::vector< int > test_indices_
const TestCase * GetTestCase(int i) const
GTEST_API_ bool AlwaysTrue()
int total_test_suite_count() const
const char * type_param() const
static bool CaseInsensitiveCStringEquals(const char *lhs, const char *rhs)
static void PrintColorEncoded(const char *str)
virtual void OnTestDisabled(const TestInfo &)
AssertionResult FloatingPointLE(const char *expr1, const char *expr2, RawType val1, RawType val2)
void AddTestPartResult(const TestPartResult &test_part_result)
void ShuffleTests(internal::Random *random)
int successful_test_count() const
virtual void OnTestSuiteEnd(const TestSuite &)
GTEST_DISABLE_MSC_WARNINGS_POP_() inline const char *SkipComma(const char *str)
void OnEnvironmentsTearDownEnd(const UnitTest &) override
#define GTEST_FLAG_SET(name, value)
std::map< std::string, TypeParameterizedTestSuiteInfo > suites_
int StrCaseCmp(const char *s1, const char *s2)
static int SumOverTestSuiteList(const std::vector< TestSuite * > &case_list, int(TestSuite::*method)() const)
constexpr uint32_t kMaxCodePoint1
TestResult * current_test_result()
bool HasFatalFailure() const
int test_to_run_count() const
static const uint32_t kMaxRange
TimeInMillis start_timestamp_
void ClearNonAdHocTestResult()
UnitTestImpl *const unit_test_
static bool TestPartSkipped(const TestPartResult &result)
virtual void OnTestSuiteStart(const TestSuite &)
PrettyUnitTestResultPrinter()=default
const char * value_param() const
void OnTestProgramEnd(const UnitTest &) override
std::string GetString() const
void set_current_test_suite(TestSuite *a_current_test_suite) GTEST_LOCK_EXCLUDED_(mutex_)
static const char kUniversalFilter[]
GTEST_API_ AssertionResult IsSubstring(const char *needle_expr, const char *haystack_expr, const char *needle, const char *haystack)
static bool ShouldRunTest(const TestInfo *test_info)
GTEST_API_ TimeInMillis GetTimeInMillis()
void OnTestSuiteStart(const TestSuite ¶meter) override
std::chrono::steady_clock clock
int total_test_case_count() const
void ReportTestPartResult(const TestPartResult &result) override
#define GTEST_FLAG_GET(name)
static void PrintOnOneLine(const char *str, int max_length)
static std::string FormatTestCount(int test_count)
static std::string FormatIntWidthN(int value, int width)
static void PrintTestName(const char *test_suite, const char *test)
static bool TestPartFatallyFailed(const TestPartResult &result)
const TestCase * GetTestCase(int i) const
void OnTestPartResult(const TestPartResult &result) override
static::std::vector< std::string > g_argvs
void set_start_timestamp(TimeInMillis start)
const TestInfo * current_test_info() const GTEST_LOCK_EXCLUDED_(mutex_)
static const char *const kReservedTestCaseAttributes[]
GTEST_API_ bool ParseFlag(const char *str, const char *flag, int32_t *value)
virtual void OnEnvironmentsTearDownEnd(const UnitTest &unit_test)=0
GTEST_API_ std::string WideStringToUtf8(const wchar_t *str, int num_chars)
bool EventForwardingEnabled() const
static void PrintTestName(const char *test_suite, const char *test)
GTEST_DISABLE_MSC_WARNINGS_POP_() GTEST_API_ GTEST_API_::std::string FormatCompilerIndependentFileLocation(const char *file, int line)
int reportable_disabled_test_count() const
GTEST_API_ AssertionResult CmpHelperSTRNE(const char *s1_expression, const char *s2_expression, const char *s1, const char *s2)
GTEST_API_ const char kStackTraceMarker[]
void PrintTo(const T &value,::std::ostream *os)
static void PrintTestPartResult(const TestPartResult &test_part_result)
void PushTrace(const char *file, int line, std::string message)
int test_property_count() const
void ShuffleRange(internal::Random *random, int begin, int end, std::vector< E > *v)
#define GTEST_INIT_GOOGLE_TEST_NAME_
constexpr uint32_t kMaxCodePoint3
bool BoolFromGTestEnv(const char *flag, bool default_val)
FILE * FOpen(const char *path, const char *mode)
void PopGTestTrace() GTEST_LOCK_EXCLUDED_(mutex_)
GTEST_API_ std::string AppendUserMessage(const std::string >est_msg, const Message &user_msg)
static const char kDefaultOutputFile[]
GTEST_API_ void InsertSyntheticTestCase(const std::string &name, CodeLocation location, bool has_test_p)
GTEST_API_ TestInfo * MakeAndRegisterTestInfo(std::string 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)
Environment * AddEnvironment(Environment *env)
const char * test_suite_name() const
TestPartResultReporterInterface * global_test_part_result_reporter_
static bool ValidateTestPropertyName(const std::string &property_name, const std::vector< std::string > &reserved_names)
internal::ParameterizedTestSuiteRegistry parameterized_test_registry_
static bool TestDisabled(const TestInfo *test_info)
int skipped_test_count() const
static bool FilterMatchesTest(const std::string &test_suite_name, const std::string &test_name)
int CountIf(const Container &c, Predicate predicate)
std::unordered_set< std::string > exact_match_patterns_
void set_current_test_suite(TestSuite *a_current_test_suite)
int disabled_test_count() const
static const char *const kReservedOutputTestCaseAttributes[]
void AddTestPartResult(TestPartResult::Type result_type, const char *file_name, int line_number, const std::string &message, const std::string &os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_)
internal::UnitTestImpl * impl()
void OnTestIterationEnd(const UnitTest &unit_test, int iteration) override
void OnTestProgramStart(const UnitTest &) override
void InitGoogleTestImpl(int *argc, CharType **argv)
TimeInMillis elapsed_time_
const char * original_working_dir() const
int Run() GTEST_MUST_USE_RESULT_
void ParseGoogleTestFlagsOnlyImpl(int *argc, CharType **argv)
int FilterTests(ReactionToSharding shard_tests)
void OnTestCaseEnd(const TestCase &) override
BriefUnitTestResultPrinter()=default
GTEST_API_ AssertionResult EqFailure(const char *expected_expression, const char *actual_expression, const std::string &expected_value, const std::string &actual_value, bool ignoring_case)
TestEventListeners * listeners()
void OnTestCaseEnd(const TestCase ¶meter) override
TestEventListener * Release(TestEventListener *listener)
uint32_t ChopLowBits(uint32_t *bits, int n)
static const char kDefaultOutputFormat[]
static void PrintFullTestCommentIfPresent(const TestInfo &test_info)
static std::string FormatWordList(const std::vector< std::string > &words)
GTEST_API_ void ParseGoogleTestFlagsOnly(int *argc, char **argv)
TestEventListener * default_xml_generator_
static bool GetDefaultFailFast()
void RegisterTestSuite(const char *test_suite_name, CodeLocation code_location)
void ConfigureXmlOutput()
bool post_flag_parse_init_performed_
static bool HasSameFixtureClass()
void Shuffle(internal::Random *random, std::vector< E > *v)
GTEST_API_ std::string GetBoolAssertionFailureMessage(const AssertionResult &assertion_result, const char *expression_text, const char *actual_predicate_value, const char *expected_predicate_value)
GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms)
int total_test_count() const
void CheckForInstantiations()
GTEST_API_ std::string CreateUnifiedDiff(const std::vector< std::string > &left, const std::vector< std::string > &right, size_t context=2)
const TestSuite * current_test_suite() const
#define GTEST_INTERNAL_PARSE_FLAG(flag_name)
internal::Random * random()
static const char kTestShardIndex[]
void OnTestDisabled(const TestInfo ¶meter) override
virtual void OnTestPartResult(const TestPartResult &test_part_result)=0
std::vector< TraceInfo > & gtest_trace_stack()
static bool TestSkipped(const TestInfo *test_info)
TimeInMillis elapsed_time_
TestEventListener * default_result_printer_
GTEST_API_ void RegisterTypeParameterizedTestSuite(const char *test_suite_name, CodeLocation code_location)
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251) class GTEST_API_ TypedTestSuitePState
std::vector< std::string > glob_patterns_
virtual void OnEnvironmentsSetUpEnd(const UnitTest &unit_test)=0
std::vector< std::string > ArrayAsVector(const char *const (&array)[kSize])
TestSuite * current_test_suite_
GTEST_API_ std::string StringStreamToString(::std::stringstream *stream)
uint32_t CreateCodePointFromUtf16SurrogatePair(wchar_t first, wchar_t second)
static const char kColorEncodedHelpMessage[]
virtual void UponLeavingGTest()=0
std::vector< TestInfo * > & test_info_list()
int total_part_count() const
static void TearDownEnvironment(Environment *env)
virtual void OnTestCaseEnd(const TestCase &)
virtual void OnTestEnd(const TestInfo &test_info)=0
virtual void OnTestProgramStart(const UnitTest &unit_test)=0
static bool TestFailed(const TestInfo *test_info)
TestInfo * current_test_info_
GTEST_API_ AssertionResult DoubleLE(const char *expr1, const char *expr2, double val1, double val2)
GTEST_API_ void InitGoogleTest(int *argc, char **argv)
int failed_test_case_count() const
int successful_test_case_count() const
constexpr uint32_t kMaxCodePoint2
void OnEnvironmentsSetUpEnd(const UnitTest &) override
const TestResult * result() const
GTEST_API_ AssertionResult IsNotSubstring(const char *needle_expr, const char *haystack_expr, const char *needle, const char *haystack)
Factory TestInfo * RegisterTest(const char *test_suite_name, const char *test_name, const char *type_param, const char *value_param, const char *file, int line, Factory factory)
static UnitTest * GetInstance()
void OnTestIterationEnd(const UnitTest &unit_test, int iteration) override
void ClearTestPartResults()
int failed_test_suite_count() const
void Reseed(uint32_t seed)
void set_catch_exceptions(bool value)
void(*)( SetUpTestSuiteFunc)
static void ColoredPrintf(GTestColor color, const char *fmt,...)
void OnTestCaseStart(const TestCase &) override
const char * type_param() const
int GetRandomSeedFromFlag(int32_t random_seed_flag)
internal::Mutex test_properties_mutex_
static bool TestSuiteFailed(const TestSuite *test_suite)
const TestSuite * current_test_suite() const GTEST_LOCK_EXCLUDED_(mutex_)
internal::ThreadLocal< TestPartResultReporterInterface * > per_thread_test_part_result_reporter_
static void PrintFailedTestSuites(const UnitTest &unit_test)
void ForEach(const Container &c, Functor functor)
static void RecordProperty(const std::string &key, const std::string &value)
const TestResult & ad_hoc_test_result() const
void OnTestEnd(const TestInfo ¶meter) override
const char * value() const
void OnTestIterationStart(const UnitTest &unit_test, int iteration) override
TimeInMillis elapsed_time() const
int disabled_test_count() const
#define GTEST_FLAG_SAVER_
TimeInMillis elapsed_time() const
static std::string FormatIntWidth2(int value)
const TestResult & ad_hoc_test_result() const
void WriteToShardStatusFileIfNeeded()
static std::string GetDirFromEnv(std::initializer_list< const char * > environment_variables, const char *fallback, char separator)
static bool TestReportable(const TestInfo *test_info)
int test_suite_to_run_count() const
static bool TestReportableDisabled(const TestInfo *test_info)
void OnEnvironmentsSetUpStart(const UnitTest ¶meter) override
UnitTestImpl(UnitTest *parent)
static std::string ShowWideCString(const wchar_t *wide_c_str)
static void PrintFailedTests(const UnitTest &unit_test)
int skipped_test_count() const
static bool PatternMatchesString(const std::string &name_str, const char *pattern, const char *pattern_end)
std::string OutputFlagAlsoCheckEnvVar()
static bool MatchesFilter(const std::string &name, const char *filter)
DefaultPerThreadTestPartResultReporter(UnitTestImpl *unit_test)
const TestCase * current_test_case() const GTEST_LOCK_EXCLUDED_(mutex_)
#define GTEST_DEFINE_string_(name, default_val, doc)
void OnEnvironmentsTearDownStart(const UnitTest ¶meter) override
int skipped_test_count() const
TestInfo * current_test_info()
~TestEventRepeater() override
const std::unique_ptr< ::std::stringstream > ss_
std::unordered_map< std::string, TestSuite * > test_suites_by_name_
#define GTEST_FLAG_PREFIX_
internal::ParameterizedTestSuiteRegistry & parameterized_test_registry() GTEST_LOCK_EXCLUDED_(mutex_)
void OnTestStart(const TestInfo ¶meter) override
void Append(TestEventListener *listener)
void OnEnvironmentsTearDownStart(const UnitTest &) override
static std::string PrintTestPartResultToString(const TestPartResult &test_part_result)
void OnTestCaseStart(const TestCase &test_case) override
static bool ShouldRunTestSuite(const TestSuite *test_suite)
std::set< std::string > * ignored_parameterized_test_suites()
internal::TypeParameterizedTestSuiteRegistry & type_parameterized_test_registry()
void OnTestEnd(const TestInfo &test_info) override
GTEST_API_ AssertionResult FloatLE(const char *expr1, const char *expr2, float val1, float val2)
GTEST_API_ std::string TempDir()
TimeInMillis elapsed_time() const
void AddTestInfo(TestInfo *test_info)
static const char kTypeParamLabel[]
static ExpectedAnswer expected[4]