33 #include "gtest/gtest.h"
34 #include "gtest/internal/custom/gtest.h"
35 #include "gtest/gtest-spi.h"
64 # include <sys/mman.h>
65 # include <sys/time.h>
70 # include <sys/time.h>
75 #elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE.
80 #elif GTEST_OS_WINDOWS // We are on Windows proper.
90 # include <sys/timeb.h>
91 # include <sys/types.h>
92 # include <sys/stat.h>
94 # if GTEST_OS_WINDOWS_MINGW
95 # include <sys/time.h>
96 # endif // GTEST_OS_WINDOWS_MINGW
102 # include <sys/time.h>
105 #endif // GTEST_OS_LINUX
107 #if GTEST_HAS_EXCEPTIONS
108 # include <stdexcept>
111 #if GTEST_CAN_STREAM_RESULTS_
112 # include <arpa/inet.h>
114 # include <sys/socket.h>
115 # include <sys/types.h>
118 #include "src/gtest-internal-inl.h"
121 # define vsnprintf _vsnprintf
122 #endif // GTEST_OS_WINDOWS
126 #include <crt_externs.h>
131 #include "absl/debugging/failure_signal_handler.h"
132 #include "absl/debugging/stacktrace.h"
133 #include "absl/debugging/symbolize.h"
134 #include "absl/strings/str_cat.h"
135 #endif // GTEST_HAS_ABSL
182 FILE* fileout =
nullptr;
183 FilePath output_file_path(output_file);
186 if (
output_dir.CreateDirectoriesRecursively()) {
189 if (fileout ==
nullptr) {
200 const char*
const testbridge_test_only =
202 if (testbridge_test_only !=
nullptr) {
203 return testbridge_test_only;
211 const char*
const testbridge_test_runner_fail_fast =
213 if (testbridge_test_runner_fail_fast !=
nullptr) {
214 return strcmp(testbridge_test_runner_fail_fast,
"1") == 0;
221 "True if and only if a test failure should stop further test execution.");
224 also_run_disabled_tests,
226 "Run disabled tests too, in addition to the tests normally being run.");
230 "True if and only if a failed assertion should be a debugger "
236 " should catch exceptions and treat them as test failures.");
241 "Whether to use colors in the output. Valid values: yes, no, "
242 "and auto. 'auto' means to use colors if the output is "
243 "being sent to a terminal and the TERM environment variable "
244 "is set to a terminal type that supports colors.");
249 "A colon-separated list of glob (not regex) patterns "
250 "for filtering the tests to run, optionally followed by a "
251 "'-' and a : separated list of negative patterns (tests to "
252 "exclude). A test is run if it matches one of the positive "
253 "patterns and does not match any of the negative patterns.");
256 install_failure_signal_handler,
258 "If true and supported on the current platform, " GTEST_NAME_ " should "
259 "install a signal handler that dumps debugging information when fatal "
260 "signals are raised.");
263 "List all tests without running them.");
274 "A format (defaults to \"xml\" but can be specified to be \"json\"), "
275 "optionally followed by a colon and an output file name or directory. "
276 "A directory is indicated by a trailing pathname separator. "
277 "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
278 "If a directory is specified, output files will be created "
279 "within that directory, with file-names based on the test "
280 "executable's name and, if necessary, made unique by adding "
285 "True if only test failures should be displayed in text output.");
289 " should display elapsed time in text output.");
293 " prints UTF8 characters as text.");
298 "Random number seed to use when shuffling test orders. Must be in range "
299 "[1, 99999], or 0 to use a seed based on the current time.");
304 "How many times to repeat each test. Specify a negative number "
305 "for repeating forever. Useful for shaking out flaky tests.");
309 " should include internal stack frames when "
310 "printing test failure stack traces.");
314 " should randomize tests' order on every run.");
319 "The maximum number of stack frames to print when an "
320 "assertion fails. The valid range is 0 through 100, inclusive.");
325 "This flag specifies the host name and the port number on which to stream "
326 "test results. Example: \"localhost:555\". The flag is effective only on "
332 "When this flag is specified, a failed assertion will throw an exception "
333 "if exceptions are enabled or exit the program with a non-zero code "
334 "otherwise. For use with an external test framework.");
336 #if GTEST_USE_OWN_FLAGFILE_FLAG_
340 "This flag specifies the flagfile to read command-line flags from.");
341 #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
354 <<
"Cannot generate a number in the range [0, 0).";
356 <<
"Generation of a number in [0, " <<
range <<
") was requested, "
357 <<
"but this can only generate numbers in [0, " <<
kMaxRange <<
").";
376 for (
size_t i = 0;
i < case_list.size();
i++) {
406 AssertHelper::~AssertHelper() {
428 constexpr
bool kErrorOnUninstantiatedParameterizedTest =
true;
429 constexpr
bool kErrorOnUninstantiatedTypeParameterizedTest =
true;
432 class FailureTest :
public Test {
434 explicit FailureTest(
const CodeLocation&
loc,
std::string error_message,
440 void TestBody()
override {
472 if (ignored.find(
name) != ignored.end())
return;
474 const char kMissingInstantiation[] =
475 " is defined via TEST_P, but never instantiated. None of the test cases "
476 "will run. Either no INSTANTIATE_TEST_SUITE_P is provided or the only "
477 "ones provided expand to nothing."
479 "Ideally, TEST_P definitions should only ever be included as part of "
480 "binaries that intend to use them. (As opposed to, for example, being "
481 "placed in a library that may be linked in to get other utilities.)";
483 const char kMissingTestCase[] =
484 " is instantiated via INSTANTIATE_TEST_SUITE_P, but no tests are "
485 "defined via TEST_P . No test cases will run."
487 "Ideally, INSTANTIATE_TEST_SUITE_P should only ever be invoked from "
488 "code that always depend on code that provides TEST_P. Failing to do "
489 "so is often an indication of dead code, e.g. the last TEST_P was "
490 "removed but the rest got left behind.";
493 "Parameterized test suite " +
name +
494 (has_test_p ? kMissingInstantiation : kMissingTestCase) +
496 "To suppress this error for this test suite, insert the following line "
497 "(in a non-header) in the namespace it is defined in:"
499 "GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(" +
name +
");";
501 std::string full_name =
"UninstantiatedParameterizedTestSuite<" +
name +
">";
503 "GoogleTestVerification", full_name.c_str(),
507 return new FailureTest(location, message,
508 kErrorOnUninstantiatedParameterizedTest);
515 test_suite_name, code_location);
524 void TypeParameterizedTestSuiteRegistry::RegisterTestSuite(
525 const char* test_suite_name,
CodeLocation code_location) {
530 void TypeParameterizedTestSuiteRegistry::RegisterInstantiation(
531 const char* test_suite_name) {
533 if (
it != suites_.end()) {
534 it->second.instantiated =
true;
537 << test_suite_name <<
"'";
541 void TypeParameterizedTestSuiteRegistry::CheckForInstantiations() {
543 for (
const auto& testcase : suites_) {
544 if (testcase.second.instantiated)
continue;
545 if (ignored.find(testcase.first) != ignored.end())
continue;
548 "Type parameterized test suite " + testcase.first +
549 " is defined via REGISTER_TYPED_TEST_SUITE_P, but never instantiated "
550 "via INSTANTIATE_TYPED_TEST_SUITE_P. None of the test cases will run."
552 "Ideally, TYPED_TEST_P definitions should only ever be included as "
553 "part of binaries that intend to use them. (As opposed to, for "
554 "example, being placed in a library that may be linked in to get other "
557 "To suppress this error for this test suite, insert the following line "
558 "(in a non-header) in the namespace it is defined in:"
560 "GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(" +
561 testcase.first +
");";
564 "UninstantiatedTypeParameterizedTestSuite<" + testcase.first +
">";
566 "GoogleTestVerification", full_name.c_str(),
569 testcase.second.code_location.file.c_str(),
570 testcase.second.code_location.line, [
message, testcase] {
571 return new FailureTest(testcase.second.code_location, message,
572 kErrorOnUninstantiatedTypeParameterizedTest);
578 static ::std::vector<std::string>
g_argvs;
580 ::std::vector<std::string>
GetArgvs() {
581 #if defined(GTEST_CUSTOM_GET_ARGVS_)
584 const auto&
custom = GTEST_CUSTOM_GET_ARGVS_();
585 return ::std::vector<std::string>(
custom.begin(),
custom.end());
586 #else // defined(GTEST_CUSTOM_GET_ARGVS_)
588 #endif // defined(GTEST_CUSTOM_GET_ARGVS_)
596 #if GTEST_OS_WINDOWS || GTEST_OS_OS2
600 #endif // GTEST_OS_WINDOWS
602 return result.RemoveDirectoryName();
610 const char*
const colon = strchr(gtest_output_flag,
':');
611 return (colon ==
nullptr)
614 static_cast<size_t>(colon - gtest_output_flag));
619 std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
626 const char*
const colon = strchr(gtest_output_flag,
':');
627 if (colon ==
nullptr)
635 if (!output_name.IsAbsolutePath())
640 if (!output_name.IsDirectory())
641 return output_name.string();
645 GetOutputFormat().
c_str()));
671 bool UnitTestOptions::MatchesFilter(
673 const char *cur_pattern = filter;
680 cur_pattern = strchr(cur_pattern,
':');
683 if (cur_pattern ==
nullptr) {
694 bool UnitTestOptions::FilterMatchesTest(
const std::string& test_suite_name,
696 const std::string& full_name = test_suite_name +
"." + test_name.c_str();
701 const char*
const dash = strchr(p,
'-');
704 if (dash ==
nullptr) {
710 if (positive.empty()) {
718 return (MatchesFilter(full_name, positive.c_str()) &&
719 !MatchesFilter(full_name,
negative.c_str()));
726 int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
735 const DWORD kCxxExceptionCode = 0xe06d7363;
737 bool should_handle =
true;
740 should_handle =
false;
741 else if (exception_code == EXCEPTION_BREAKPOINT)
742 should_handle =
false;
743 else if (exception_code == kCxxExceptionCode)
744 should_handle =
false;
746 return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
748 #endif // GTEST_HAS_SEH
755 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
756 TestPartResultArray*
result)
757 : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
766 InterceptMode intercept_mode, TestPartResultArray*
result)
767 : intercept_mode_(intercept_mode),
774 if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
775 old_reporter_ = impl->GetGlobalTestPartResultReporter();
776 impl->SetGlobalTestPartResultReporter(
this);
778 old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
779 impl->SetTestPartResultReporterForCurrentThread(
this);
787 if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
788 impl->SetGlobalTestPartResultReporter(old_reporter_);
790 impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
797 const TestPartResult&
result) {
813 return GetTypeId<Test>();
831 "1 non-fatal failure");
834 msg <<
"Expected: " << expected <<
"\n"
835 <<
" Actual: " <<
results.size() <<
" failures";
843 if (
r.type() !=
type) {
849 if (strstr(
r.message(), substr.c_str()) ==
nullptr) {
871 SingleFailureChecker::~SingleFailureChecker() {
875 DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
876 UnitTestImpl* unit_test) : unit_test_(unit_test) {}
878 void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
879 const TestPartResult&
result) {
880 unit_test_->current_test_result()->AddTestPartResult(
result);
881 unit_test_->listeners()->repeater()->OnTestPartResult(
result);
884 DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
885 UnitTestImpl* unit_test) : unit_test_(unit_test) {}
887 void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
888 const TestPartResult&
result) {
889 unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(
result);
893 TestPartResultReporterInterface*
894 UnitTestImpl::GetGlobalTestPartResultReporter() {
896 return global_test_part_result_repoter_;
900 void UnitTestImpl::SetGlobalTestPartResultReporter(
901 TestPartResultReporterInterface* reporter) {
903 global_test_part_result_repoter_ = reporter;
907 TestPartResultReporterInterface*
908 UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
909 return per_thread_test_part_result_reporter_.get();
913 void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
914 TestPartResultReporterInterface* reporter) {
915 per_thread_test_part_result_reporter_.set(reporter);
919 int UnitTestImpl::successful_test_suite_count()
const {
924 int UnitTestImpl::failed_test_suite_count()
const {
929 int UnitTestImpl::total_test_suite_count()
const {
930 return static_cast<int>(test_suites_.size());
935 int UnitTestImpl::test_suite_to_run_count()
const {
940 int UnitTestImpl::successful_test_count()
const {
945 int UnitTestImpl::skipped_test_count()
const {
950 int UnitTestImpl::failed_test_count()
const {
955 int UnitTestImpl::reportable_disabled_test_count()
const {
961 int UnitTestImpl::disabled_test_count()
const {
966 int UnitTestImpl::reportable_test_count()
const {
971 int UnitTestImpl::total_test_count()
const {
976 int UnitTestImpl::test_to_run_count()
const {
990 std::string UnitTestImpl::CurrentOsStackTraceExceptTop(
int skip_count) {
991 return os_stack_trace_getter()->CurrentStackTrace(
992 static_cast<int>(
GTEST_FLAG(stack_trace_depth)),
1001 return std::chrono::duration_cast<std::chrono::milliseconds>(
1003 std::chrono::system_clock::from_time_t(0))
1011 #if GTEST_OS_WINDOWS_MOBILE
1016 LPCWSTR String::AnsiToUtf16(
const char* ansi) {
1017 if (!ansi)
return nullptr;
1018 const int length = strlen(ansi);
1019 const int unicode_length =
1020 MultiByteToWideChar(CP_ACP, 0, ansi,
length,
nullptr, 0);
1021 WCHAR*
unicode =
new WCHAR[unicode_length + 1];
1022 MultiByteToWideChar(CP_ACP, 0, ansi,
length,
1032 const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
1033 if (!utf16_str)
return nullptr;
1034 const int ansi_length = WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
nullptr,
1035 0,
nullptr,
nullptr);
1036 char* ansi =
new char[ansi_length + 1];
1037 WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, ansi, ansi_length,
nullptr,
1039 ansi[ansi_length] = 0;
1043 #endif // GTEST_OS_WINDOWS_MOBILE
1051 bool String::CStringEquals(
const char * lhs,
const char * rhs) {
1052 if (lhs ==
nullptr)
return rhs ==
nullptr;
1054 if (rhs ==
nullptr)
return false;
1056 return strcmp(lhs, rhs) == 0;
1059 #if GTEST_HAS_STD_WSTRING
1065 for (
size_t i = 0;
i !=
length; ) {
1066 if (wstr[i] != L
'\0') {
1067 *msg << WideStringToUtf8(wstr + i, static_cast<int>(
length - i));
1068 while (i !=
length && wstr[i] != L
'\0')
1077 #endif // GTEST_HAS_STD_WSTRING
1080 ::std::vector< ::std::string>*
dest) {
1081 ::std::vector< ::std::string> parsed;
1082 ::std::string::size_type
pos = 0;
1084 const ::std::string::size_type colon =
str.find(delimiter,
pos);
1085 if (colon == ::std::string::npos) {
1086 parsed.push_back(
str.substr(
pos));
1089 parsed.push_back(
str.substr(
pos, colon -
pos));
1106 *ss_ << std::setprecision(std::numeric_limits<double>::digits10 + 2);
1118 #if GTEST_HAS_STD_WSTRING
1125 #endif // GTEST_HAS_STD_WSTRING
1136 : success_(other.success_),
1137 message_(other.message_.
get() != nullptr
1139 : static_cast< ::
std::
string*>(nullptr)) {}
1157 return AssertionResult(
true);
1162 return AssertionResult(
false);
1173 namespace edit_distance {
1175 const std::vector<size_t>& right) {
1176 std::vector<std::vector<double> > costs(
1177 left.size() + 1, std::vector<double>(right.size() + 1));
1178 std::vector<std::vector<EditType> > best_move(
1179 left.size() + 1, std::vector<EditType>(right.size() + 1));
1182 for (
size_t l_i = 0; l_i < costs.size(); ++l_i) {
1183 costs[l_i][0] =
static_cast<double>(l_i);
1187 for (
size_t r_i = 1; r_i < costs[0].size(); ++r_i) {
1188 costs[0][r_i] =
static_cast<double>(r_i);
1189 best_move[0][r_i] =
kAdd;
1192 for (
size_t l_i = 0; l_i < left.size(); ++l_i) {
1193 for (
size_t r_i = 0; r_i < right.size(); ++r_i) {
1194 if (left[l_i] == right[r_i]) {
1196 costs[l_i + 1][r_i + 1] = costs[l_i][r_i];
1197 best_move[l_i + 1][r_i + 1] =
kMatch;
1201 const double add = costs[l_i + 1][r_i];
1202 const double remove = costs[l_i][r_i + 1];
1203 const double replace = costs[l_i][r_i];
1204 if (
add < remove &&
add < replace) {
1205 costs[l_i + 1][r_i + 1] =
add + 1;
1206 best_move[l_i + 1][r_i + 1] =
kAdd;
1207 }
else if (remove <
add && remove < replace) {
1208 costs[l_i + 1][r_i + 1] = remove + 1;
1209 best_move[l_i + 1][r_i + 1] =
kRemove;
1213 costs[l_i + 1][r_i + 1] = replace + 1.00001;
1214 best_move[l_i + 1][r_i + 1] =
kReplace;
1220 std::vector<EditType> best_path;
1221 for (
size_t l_i = left.size(), r_i = right.size(); l_i > 0 || r_i > 0;) {
1223 best_path.push_back(
move);
1234 class InternalStrings {
1238 if (
it !=
ids_.end())
return it->second;
1239 size_t id =
ids_.size();
1244 typedef std::map<std::string, size_t>
IdMap;
1251 const std::vector<std::string>& left,
1252 const std::vector<std::string>& right) {
1253 std::vector<size_t> left_ids, right_ids;
1255 InternalStrings intern_table;
1256 for (
size_t i = 0;
i < left.size(); ++
i) {
1257 left_ids.push_back(intern_table.GetId(left[
i]));
1259 for (
size_t i = 0;
i < right.size(); ++
i) {
1260 right_ids.push_back(intern_table.GetId(right[i]));
1274 Hunk(
size_t left_start,
size_t right_start)
1281 void PushLine(
char edit,
const char*
line) {
1286 hunk_.push_back(std::make_pair(
' ',
line));
1299 void PrintTo(std::ostream* os) {
1302 for (std::list<std::pair<char, const char*> >::const_iterator
it =
1305 *os <<
it->first <<
it->second <<
"\n";
1321 void PrintHeader(std::ostream* ss)
const {
1350 const std::vector<std::string>& right,
1354 size_t l_i = 0, r_i = 0, edit_i = 0;
1355 std::stringstream ss;
1356 while (edit_i < edits.size()) {
1358 while (edit_i < edits.size() && edits[edit_i] ==
kMatch) {
1366 Hunk hunk(l_i - prefix_context + 1, r_i - prefix_context + 1);
1367 for (
size_t i = prefix_context;
i > 0; --
i) {
1368 hunk.PushLine(
' ', left[l_i - i].
c_str());
1373 size_t n_suffix = 0;
1374 for (; edit_i < edits.size(); ++edit_i) {
1377 auto it = edits.begin() +
static_cast<int>(edit_i);
1379 if (
it == edits.end() ||
1380 static_cast<size_t>(
it - edits.begin()) - edit_i >=
context) {
1388 n_suffix = edit ==
kMatch ? n_suffix + 1 : 0;
1391 hunk.PushLine(edit ==
kMatch ?
' ' :
'-', left[l_i].
c_str());
1394 hunk.PushLine(
'+', right[r_i].
c_str());
1398 l_i += edit !=
kAdd;
1402 if (!hunk.has_edits()) {
1419 std::vector<std::string> SplitEscapedString(
const std::string&
str) {
1420 std::vector<std::string>
lines;
1426 bool escaped =
false;
1430 if (
str[i] ==
'n') {
1435 escaped =
str[
i] ==
'\\';
1459 AssertionResult
EqFailure(
const char* lhs_expression,
1460 const char* rhs_expression,
1463 bool ignoring_case) {
1465 msg <<
"Expected equality of these values:";
1466 msg <<
"\n " << lhs_expression;
1467 if (lhs_value != lhs_expression) {
1468 msg <<
"\n Which is: " << lhs_value;
1470 msg <<
"\n " << rhs_expression;
1471 if (rhs_value != rhs_expression) {
1472 msg <<
"\n Which is: " << rhs_value;
1475 if (ignoring_case) {
1476 msg <<
"\nIgnoring case";
1479 if (!lhs_value.empty() && !rhs_value.empty()) {
1480 const std::vector<std::string> lhs_lines =
1481 SplitEscapedString(lhs_value);
1482 const std::vector<std::string> rhs_lines =
1483 SplitEscapedString(rhs_value);
1484 if (lhs_lines.size() > 1 || rhs_lines.size() > 1) {
1485 msg <<
"\nWith diff:\n"
1495 const AssertionResult& assertion_result,
1496 const char* expression_text,
1497 const char* actual_predicate_value,
1498 const char* expected_predicate_value) {
1499 const char* actual_message = assertion_result.message();
1501 msg <<
"Value of: " << expression_text
1502 <<
"\n Actual: " << actual_predicate_value;
1503 if (actual_message[0] !=
'\0')
1504 msg <<
" (" << actual_message <<
")";
1505 msg <<
"\nExpected: " << expected_predicate_value;
1506 return msg.GetString();
1512 const char* abs_error_expr,
1522 const double epsilon =
1523 nextafter(min_abs, std::numeric_limits<double>::infinity()) - min_abs;
1531 abs_error < epsilon) {
1533 <<
"The difference between " << expr1 <<
" and " << expr2 <<
" is "
1534 <<
diff <<
", where\n"
1535 << expr1 <<
" evaluates to " <<
val1 <<
",\n"
1536 << expr2 <<
" evaluates to " <<
val2 <<
".\nThe abs_error parameter "
1537 << abs_error_expr <<
" evaluates to " << abs_error
1538 <<
" which is smaller than the minimum distance between doubles for "
1539 "numbers of this magnitude which is "
1541 <<
", thus making this EXPECT_NEAR check equivalent to "
1542 "EXPECT_EQUAL. Consider using EXPECT_DOUBLE_EQ instead.";
1545 <<
"The difference between " << expr1 <<
" and " << expr2
1546 <<
" is " <<
diff <<
", which exceeds " << abs_error_expr <<
", where\n"
1547 << expr1 <<
" evaluates to " <<
val1 <<
",\n"
1548 << expr2 <<
" evaluates to " <<
val2 <<
", and\n"
1549 << abs_error_expr <<
" evaluates to " << abs_error <<
".";
1554 template <
typename RawType>
1565 const FloatingPoint<RawType> lhs(
val1), rhs(
val2);
1566 if (lhs.AlmostEquals(rhs)) {
1574 ::std::stringstream val1_ss;
1575 val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
1578 ::std::stringstream val2_ss;
1579 val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
1583 <<
"Expected: (" << expr1 <<
") <= (" << expr2 <<
")\n"
1592 AssertionResult
FloatLE(
const char* expr1,
const char* expr2,
1594 return internal::FloatingPointLE<float>(expr1, expr2,
val1,
val2);
1599 AssertionResult
DoubleLE(
const char* expr1,
const char* expr2,
1601 return internal::FloatingPointLE<double>(expr1, expr2,
val1,
val2);
1608 AssertionResult
CmpHelperEQ(
const char* lhs_expression,
1609 const char* rhs_expression,
1626 #define GTEST_IMPL_CMP_HELPER_(op_name, op)\
1627 AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
1628 BiggestInt val1, BiggestInt val2) {\
1629 if (val1 op val2) {\
1630 return AssertionSuccess();\
1632 return AssertionFailure() \
1633 << "Expected: (" << expr1 << ") " #op " (" << expr2\
1634 << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
1635 << " vs " << FormatForComparisonFailureMessage(val2, val1);\
1655 #undef GTEST_IMPL_CMP_HELPER_
1659 const char* rhs_expression,
1675 const char* rhs_expression,
1691 const char* s2_expression,
1698 << s2_expression <<
"), actual: \""
1699 << s1 <<
"\" vs \"" << s2 <<
"\"";
1705 const char* s2_expression,
1712 <<
"Expected: (" << s1_expression <<
") != ("
1713 << s2_expression <<
") (ignoring case), actual: \""
1714 << s1 <<
"\" vs \"" << s2 <<
"\"";
1728 bool IsSubstringPred(
const char* needle,
const char* haystack) {
1729 if (needle ==
nullptr || haystack ==
nullptr)
return needle == haystack;
1731 return strstr(haystack, needle) !=
nullptr;
1734 bool IsSubstringPred(
const wchar_t* needle,
const wchar_t* haystack) {
1735 if (needle ==
nullptr || haystack ==
nullptr)
return needle == haystack;
1737 return wcsstr(haystack, needle) !=
nullptr;
1741 template <
typename StringType>
1742 bool IsSubstringPred(
const StringType& needle,
1744 return haystack.find(needle) != StringType::npos;
1751 template <
typename StringType>
1752 AssertionResult IsSubstringImpl(
1753 bool expected_to_be_substring,
1754 const char* needle_expr,
const char* haystack_expr,
1756 if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
1759 const bool is_wide_string =
sizeof(needle[0]) > 1;
1760 const char*
const begin_string_quote = is_wide_string ?
"L\"" :
"\"";
1762 <<
"Value of: " << needle_expr <<
"\n"
1763 <<
" Actual: " << begin_string_quote << needle <<
"\"\n"
1764 <<
"Expected: " << (expected_to_be_substring ?
"" :
"not ")
1765 <<
"a substring of " << haystack_expr <<
"\n"
1766 <<
"Which is: " << begin_string_quote << haystack <<
"\"";
1776 const char* needle_expr,
const char* haystack_expr,
1777 const char* needle,
const char* haystack) {
1778 return IsSubstringImpl(
true, needle_expr, haystack_expr, needle, haystack);
1782 const char* needle_expr,
const char* haystack_expr,
1783 const wchar_t* needle,
const wchar_t* haystack) {
1784 return IsSubstringImpl(
true, needle_expr, haystack_expr, needle, haystack);
1788 const char* needle_expr,
const char* haystack_expr,
1789 const char* needle,
const char* haystack) {
1790 return IsSubstringImpl(
false, needle_expr, haystack_expr, needle, haystack);
1794 const char* needle_expr,
const char* haystack_expr,
1795 const wchar_t* needle,
const wchar_t* haystack) {
1796 return IsSubstringImpl(
false, needle_expr, haystack_expr, needle, haystack);
1800 const char* needle_expr,
const char* haystack_expr,
1802 return IsSubstringImpl(
true, needle_expr, haystack_expr, needle, haystack);
1806 const char* needle_expr,
const char* haystack_expr,
1808 return IsSubstringImpl(
false, needle_expr, haystack_expr, needle, haystack);
1811 #if GTEST_HAS_STD_WSTRING
1813 const char* needle_expr,
const char* haystack_expr,
1815 return IsSubstringImpl(
true, needle_expr, haystack_expr, needle, haystack);
1819 const char* needle_expr,
const char* haystack_expr,
1821 return IsSubstringImpl(
false, needle_expr, haystack_expr, needle, haystack);
1823 #endif // GTEST_HAS_STD_WSTRING
1827 #if GTEST_OS_WINDOWS
1832 AssertionResult HRESULTFailureHelper(
const char* expr,
1833 const char* expected,
1835 # if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_TV_TITLE
1838 const char error_text[] =
"";
1845 const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
1846 FORMAT_MESSAGE_IGNORE_INSERTS;
1847 const DWORD kBufSize = 4096;
1849 char error_text[kBufSize] = {
'\0' };
1850 DWORD message_length = ::FormatMessageA(kFlags,
1852 static_cast<DWORD
>(hr),
1858 for (; message_length &&
IsSpace(error_text[message_length - 1]);
1860 error_text[message_length - 1] =
'\0';
1863 # endif // GTEST_OS_WINDOWS_MOBILE
1867 <<
"Expected: " << expr <<
" " << expected <<
".\n"
1868 <<
" Actual: " << error_hex <<
" " << error_text <<
"\n";
1873 AssertionResult IsHRESULTSuccess(
const char* expr,
long hr) {
1874 if (SUCCEEDED(hr)) {
1877 return HRESULTFailureHelper(expr,
"succeeds", hr);
1880 AssertionResult IsHRESULTFailure(
const char* expr,
long hr) {
1884 return HRESULTFailureHelper(expr,
"fails", hr);
1887 #endif // GTEST_OS_WINDOWS
1936 str[0] =
static_cast<char>(code_point);
1940 str[0] =
static_cast<char>(0xC0 | code_point);
1945 str[0] =
static_cast<char>(0xE0 | code_point);
1951 str[0] =
static_cast<char>(0xF0 | code_point);
1964 return sizeof(wchar_t) == 2 &&
1965 (
first & 0xFC00) == 0xD800 && (
second & 0xFC00) == 0xDC00;
1973 const uint32_t mask = (1 << 10) - 1;
1974 return (
sizeof(
wchar_t) == 2)
1975 ? (((first_u & mask) << 10) | (second_u & mask)) + 0x10000
1996 if (num_chars == -1)
1997 num_chars =
static_cast<int>(wcslen(
str));
1999 ::std::stringstream
stream;
2000 for (
int i = 0;
i < num_chars; ++
i) {
2003 if (
str[i] == L
'\0') {
2021 if (wide_c_str ==
nullptr)
return "(null)";
2033 if (lhs ==
nullptr)
return rhs ==
nullptr;
2035 if (rhs ==
nullptr)
return false;
2037 return wcscmp(lhs, rhs) == 0;
2042 const char* rhs_expression,
2044 const wchar_t* rhs) {
2058 const char* s2_expression,
2060 const wchar_t* s2) {
2066 << s2_expression <<
"), actual: "
2078 if (lhs ==
nullptr)
return rhs ==
nullptr;
2079 if (rhs ==
nullptr)
return false;
2096 const wchar_t* rhs) {
2097 if (lhs ==
nullptr)
return rhs ==
nullptr;
2099 if (rhs ==
nullptr)
return false;
2101 #if GTEST_OS_WINDOWS
2102 return _wcsicmp(lhs, rhs) == 0;
2103 #elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID
2104 return wcscasecmp(lhs, rhs) == 0;
2110 left = towlower(
static_cast<wint_t
>(*lhs++));
2111 right = towlower(
static_cast<wint_t
>(*rhs++));
2112 }
while (left && left == right);
2113 return left == right;
2114 #endif // OS selector
2121 const size_t str_len =
str.length();
2122 const size_t suffix_len =
suffix.length();
2123 return (str_len >= suffix_len) &&
2135 std::stringstream ss;
2136 ss << std::setfill(
'0') << std::setw(
width) <<
value;
2142 std::stringstream ss;
2143 ss << std::hex << std::uppercase <<
value;
2154 std::stringstream ss;
2155 ss << std::setfill(
'0') << std::setw(2) << std::hex << std::uppercase
2156 <<
static_cast<unsigned int>(
value);
2164 const char*
const start =
str.c_str();
2184 const std::string user_msg_string = user_msg.GetString();
2185 if (user_msg_string.empty()) {
2188 if (gtest_msg.empty()) {
2189 return user_msg_string;
2191 return gtest_msg +
"\n" + user_msg_string;
2200 : death_test_count_(0), start_timestamp_(0), elapsed_time_(0) {}
2210 if (i < 0 || i >= total_part_count())
2212 return test_part_results_.at(
static_cast<size_t>(i));
2219 if (i < 0 || i >= test_property_count())
2221 return test_properties_.at(
static_cast<size_t>(i));
2226 test_part_results_.clear();
2231 test_part_results_.push_back(test_part_result);
2238 const TestProperty& test_property) {
2239 if (!ValidateTestProperty(xml_element, test_property)) {
2244 std::find_if(test_properties_.begin(), test_properties_.end(),
2245 internal::TestPropertyKeyIs(test_property.key()));
2246 if (property_with_matching_key == test_properties_.end()) {
2247 test_properties_.push_back(test_property);
2250 property_with_matching_key->SetValue(test_property.value());
2269 "disabled",
"errors",
"failures",
"name",
2270 "tests",
"time",
"timestamp",
"skipped"};
2274 "classname",
"name",
"status",
"time",
"type_param",
2275 "value_param",
"file",
"line"};
2280 "classname",
"name",
"status",
"time",
"type_param",
2281 "value_param",
"file",
"line",
"result",
"timestamp"};
2283 template <
size_t kSize>
2285 return std::vector<std::string>(
array,
array + kSize);
2290 if (xml_element ==
"testsuites") {
2292 }
else if (xml_element ==
"testsuite") {
2294 }
else if (xml_element ==
"testcase") {
2297 GTEST_CHECK_(
false) <<
"Unrecognized xml_element provided: " << xml_element;
2300 return std::vector<std::string>();
2306 if (xml_element ==
"testsuites") {
2308 }
else if (xml_element ==
"testsuite") {
2310 }
else if (xml_element ==
"testcase") {
2313 GTEST_CHECK_(
false) <<
"Unrecognized xml_element provided: " << xml_element;
2316 return std::vector<std::string>();
2321 for (
size_t i = 0;
i <
words.size(); ++
i) {
2322 if (
i > 0 &&
words.size() > 2) {
2325 if (
i ==
words.size() - 1) {
2326 word_list <<
"and ";
2328 word_list <<
"'" <<
words[
i] <<
"'";
2338 ADD_FAILURE() <<
"Reserved key used in RecordProperty(): " << property_name
2349 const TestProperty& test_property) {
2356 test_part_results_.clear();
2357 test_properties_.clear();
2358 death_test_count_ = 0;
2374 for (
int i = 0;
i < total_part_count(); ++
i) {
2375 if (GetTestPartResult(i).failed())
2383 return result.fatally_failed();
2393 return result.nonfatally_failed();
2404 return static_cast<int>(test_part_results_.size());
2409 return static_cast<int>(test_properties_.size());
2430 void Test::SetUp() {
2436 void Test::TearDown() {
2441 UnitTest::GetInstance()->RecordProperty(
key,
value);
2447 value_message <<
value;
2448 RecordProperty(
key, value_message.GetString().c_str());
2457 UnitTest::GetInstance()->AddTestPartResult(
2472 bool Test::HasSameFixtureClass() {
2477 const TestInfo*
const first_test_info =
test_suite->test_info_list()[0];
2478 const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_;
2479 const char*
const first_test_name = first_test_info->name();
2482 const TestInfo*
const this_test_info = impl->current_test_info();
2483 const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_;
2484 const char*
const this_test_name = this_test_info->name();
2486 if (this_fixture_id != first_fixture_id) {
2492 if (first_is_TEST || this_is_TEST) {
2499 const char*
const TEST_name =
2500 first_is_TEST ? first_test_name : this_test_name;
2501 const char*
const TEST_F_name =
2502 first_is_TEST ? this_test_name : first_test_name;
2505 <<
"All tests in the same test suite must use the same test fixture\n"
2506 <<
"class, so mixing TEST_F and TEST in the same test suite is\n"
2507 <<
"illegal. In test suite " << this_test_info->test_suite_name()
2509 <<
"test " << TEST_F_name <<
" is defined using TEST_F but\n"
2510 <<
"test " << TEST_name <<
" is defined using TEST. You probably\n"
2511 <<
"want to change the TEST to TEST_F or move it to another test\n"
2517 <<
"All tests in the same test suite must use the same test fixture\n"
2518 <<
"class. However, in test suite "
2519 << this_test_info->test_suite_name() <<
",\n"
2520 <<
"you defined test " << first_test_name <<
" and test "
2521 << this_test_name <<
"\n"
2522 <<
"using two different test fixture classes. This can happen if\n"
2523 <<
"the two classes are from different namespaces or translation\n"
2524 <<
"units and have the same name. You should probably rename one\n"
2525 <<
"of the classes to put the tests into different test suites.";
2539 static std::string* FormatSehExceptionMessage(DWORD exception_code,
2540 const char* location) {
2542 message <<
"SEH exception with code 0x" << std::setbase(16) <<
2543 exception_code << std::setbase(10) <<
" thrown in " << location <<
".";
2548 #endif // GTEST_HAS_SEH
2552 #if GTEST_HAS_EXCEPTIONS
2556 const char* location) {
2561 message <<
"Unknown C++ exception";
2563 message <<
" thrown in " << location <<
".";
2569 const TestPartResult& test_part_result);
2571 GoogleTestFailureException::GoogleTestFailureException(
2572 const TestPartResult& failure)
2575 #endif // GTEST_HAS_EXCEPTIONS
2585 template <
class T,
typename Result>
2590 return (object->*
method)();
2591 } __except (internal::UnitTestOptions::GTestShouldProcessSEH(
2592 GetExceptionCode())) {
2596 std::string* exception_message = FormatSehExceptionMessage(
2597 GetExceptionCode(), location);
2599 *exception_message);
2600 delete exception_message;
2601 return static_cast<Result>(0);
2605 return (object->*
method)();
2606 #endif // GTEST_HAS_SEH
2612 template <
class T,
typename Result>
2639 #if GTEST_HAS_EXCEPTIONS
2642 }
catch (
const AssertionException&) {
2644 }
catch (
const internal::GoogleTestFailureException&) {
2649 }
catch (
const std::exception& e) {
2651 TestPartResult::kFatalFailure,
2652 FormatCxxExceptionMessage(
e.what(), location));
2655 TestPartResult::kFatalFailure,
2656 FormatCxxExceptionMessage(
nullptr, location));
2658 return static_cast<Result>(0);
2661 #endif // GTEST_HAS_EXCEPTIONS
2663 return (object->*
method)();
2671 if (!HasSameFixtureClass())
return;
2674 impl->os_stack_trace_getter()->UponLeavingGTest();
2678 if (!HasFatalFailure() && !IsSkipped()) {
2679 impl->os_stack_trace_getter()->UponLeavingGTest();
2681 this, &Test::TestBody,
"the test body");
2687 impl->os_stack_trace_getter()->UponLeavingGTest();
2689 this, &Test::TearDown,
"TearDown()");
2693 bool Test::HasFatalFailure() {
2698 bool Test::HasNonfatalFailure() {
2700 HasNonfatalFailure();
2704 bool Test::IsSkipped() {
2712 TestInfo::TestInfo(
const std::string& a_test_suite_name,
2713 const std::string& a_name,
const char* a_type_param,
2714 const char* a_value_param,
2715 internal::CodeLocation a_code_location,
2717 internal::TestFactoryBase* factory)
2718 : test_suite_name_(a_test_suite_name),
2720 type_param_(a_type_param ?
new std::
string(a_type_param) : nullptr),
2721 value_param_(a_value_param ?
new std::
string(a_value_param) : nullptr),
2722 location_(a_code_location),
2723 fixture_class_id_(fixture_class_id),
2725 is_disabled_(
false),
2726 matches_filter_(
false),
2727 is_in_another_shard_(
false),
2732 TestInfo::~TestInfo() {
delete factory_; }
2755 const char* test_suite_name,
const char*
name,
const char* type_param,
2756 const char* value_param, CodeLocation code_location,
2759 TestInfo*
const test_info =
2760 new TestInfo(test_suite_name,
name, type_param, value_param,
2761 code_location, fixture_class_id, factory);
2767 CodeLocation code_location) {
2770 <<
"Attempted redefinition of test suite " << test_suite_name <<
".\n"
2771 <<
"All tests in the same test suite must use the same test fixture\n"
2772 <<
"class. However, in test suite " << test_suite_name <<
", you tried\n"
2773 <<
"to define a test using a fixture class different from the one\n"
2774 <<
"used earlier. This can happen if the two fixture classes are\n"
2775 <<
"from different namespaces and have the same name. You should\n"
2776 <<
"probably rename one of the classes to put the tests into different\n"
2781 <<
" " <<
errors.GetString();
2800 explicit TestNameIs(
const char*
name)
2804 bool operator()(
const TestInfo * test_info)
const {
2805 return test_info && test_info->name() ==
name_;
2819 void UnitTestImpl::RegisterParameterizedTests() {
2820 if (!parameterized_tests_registered_) {
2821 parameterized_test_registry_.RegisterTests();
2822 type_parameterized_test_registry_.CheckForInstantiations();
2823 parameterized_tests_registered_ =
true;
2832 if (!should_run_)
return;
2836 impl->set_current_test_info(
this);
2838 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
2841 repeater->OnTestStart(*
this);
2845 impl->os_stack_trace_getter()->UponLeavingGTest();
2849 factory_, &internal::TestFactoryBase::CreateTest,
2850 "the test fixture's constructor");
2855 if (!Test::HasFatalFailure() && !Test::IsSkipped()) {
2861 if (
test !=
nullptr) {
2863 impl->os_stack_trace_getter()->UponLeavingGTest();
2865 test, &Test::DeleteSelf_,
"the test fixture's destructor");
2868 result_.set_start_timestamp(
start);
2872 repeater->OnTestEnd(*
this);
2876 impl->set_current_test_info(
nullptr);
2881 if (!should_run_)
return;
2904 int TestSuite::successful_test_count()
const {
2905 return CountIf(test_info_list_, TestPassed);
2909 int TestSuite::skipped_test_count()
const {
2910 return CountIf(test_info_list_, TestSkipped);
2914 int TestSuite::failed_test_count()
const {
2915 return CountIf(test_info_list_, TestFailed);
2919 int TestSuite::reportable_disabled_test_count()
const {
2920 return CountIf(test_info_list_, TestReportableDisabled);
2924 int TestSuite::disabled_test_count()
const {
2925 return CountIf(test_info_list_, TestDisabled);
2929 int TestSuite::reportable_test_count()
const {
2930 return CountIf(test_info_list_, TestReportable);
2934 int TestSuite::test_to_run_count()
const {
2935 return CountIf(test_info_list_, ShouldRunTest);
2939 int TestSuite::total_test_count()
const {
2940 return static_cast<int>(test_info_list_.size());
2952 TestSuite::TestSuite(
const char* a_name,
const char* a_type_param,
2956 type_param_(a_type_param ?
new std::
string(a_type_param) : nullptr),
2957 set_up_tc_(set_up_tc),
2958 tear_down_tc_(tear_down_tc),
2960 start_timestamp_(0),
2973 return index < 0 ? nullptr : test_info_list_[static_cast<size_t>(
index)];
2980 return index < 0 ? nullptr : test_info_list_[static_cast<size_t>(
index)];
2995 impl->set_current_test_suite(
this);
3002 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3003 repeater->OnTestCaseStart(*
this);
3004 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3006 impl->os_stack_trace_getter()->UponLeavingGTest();
3022 impl->os_stack_trace_getter()->UponLeavingGTest();
3027 repeater->OnTestSuiteEnd(*
this);
3029 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3030 repeater->OnTestCaseEnd(*
this);
3031 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3033 impl->set_current_test_suite(
nullptr);
3048 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3050 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3059 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3061 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3090 const char * singular_form,
3091 const char * plural_form) {
3093 (
count == 1 ? singular_form : plural_form);
3112 case TestPartResult::kSkip:
3125 return "Unknown result type";
3141 << test_part_result.
message()).GetString();
3154 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
3158 ::OutputDebugStringA(
result.c_str());
3159 ::OutputDebugStringA(
"\n");
3164 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \
3165 !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
3168 static WORD GetColorAttribute(
GTestColor color) {
3170 case GTestColor::kRed:
3171 return FOREGROUND_RED;
3172 case GTestColor::kGreen:
3173 return FOREGROUND_GREEN;
3174 case GTestColor::kYellow:
3175 return FOREGROUND_RED | FOREGROUND_GREEN;
3180 static int GetBitOffset(WORD color_mask) {
3181 if (color_mask == 0)
return 0;
3184 while ((color_mask & 1) == 0) {
3191 static WORD GetNewColor(
GTestColor color, WORD old_color_attrs) {
3193 static const WORD background_mask = BACKGROUND_BLUE | BACKGROUND_GREEN |
3194 BACKGROUND_RED | BACKGROUND_INTENSITY;
3195 static const WORD foreground_mask = FOREGROUND_BLUE | FOREGROUND_GREEN |
3196 FOREGROUND_RED | FOREGROUND_INTENSITY;
3197 const WORD existing_bg = old_color_attrs & background_mask;
3200 GetColorAttribute(color) | existing_bg | FOREGROUND_INTENSITY;
3201 static const int bg_bitOffset = GetBitOffset(background_mask);
3202 static const int fg_bitOffset = GetBitOffset(foreground_mask);
3204 if (((new_color & background_mask) >> bg_bitOffset) ==
3205 ((new_color & foreground_mask) >> fg_bitOffset)) {
3206 new_color ^= FOREGROUND_INTENSITY;
3217 case GTestColor::kRed:
3219 case GTestColor::kGreen:
3221 case GTestColor::kYellow:
3228 #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
3232 const char*
const gtest_color =
GTEST_FLAG(color).c_str();
3235 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
3238 return stdout_is_tty;
3242 const bool term_supports_color =
3254 return stdout_is_tty && term_supports_color;
3255 #endif // GTEST_OS_WINDOWS
3277 #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_ZOS || GTEST_OS_IOS || \
3278 GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT || defined(ESP_PLATFORM)
3281 static const bool in_color_mode =
3284 #endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_ZOS
3292 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \
3293 !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
3294 const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
3297 CONSOLE_SCREEN_BUFFER_INFO buffer_info;
3298 GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
3299 const WORD old_color_attrs = buffer_info.wAttributes;
3300 const WORD new_color = GetNewColor(color, old_color_attrs);
3306 SetConsoleTextAttribute(stdout_handle, new_color);
3312 SetConsoleTextAttribute(stdout_handle, old_color_attrs);
3317 #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
3327 const char*
const type_param = test_info.
type_param();
3328 const char*
const value_param = test_info.
value_param();
3330 if (type_param !=
nullptr || value_param !=
nullptr) {
3332 if (type_param !=
nullptr) {
3334 if (value_param !=
nullptr)
printf(
" and ");
3336 if (value_param !=
nullptr) {
3357 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3361 #endif // OnTestCaseStart
3367 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3371 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3386 const UnitTest& unit_test,
int iteration) {
3388 printf(
"\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
3390 const char*
const filter =
GTEST_FLAG(filter).c_str();
3401 ColoredPrintf(GTestColor::kYellow,
"Note: This is test shard %d of %s.\n",
3402 static_cast<int>(shard_index) + 1,
3408 "Note: Randomizing tests' orders with a seed of %d .\n",
3413 printf(
"Running %s from %s.\n",
3422 printf(
"Global test environment set-up.\n");
3426 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3431 printf(
"%s from %s", counts.c_str(), test_case.name());
3432 if (test_case.type_param() ==
nullptr) {
3453 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3457 PrintTestName(test_info.test_suite_name(), test_info.name());
3464 const TestPartResult&
result) {
3478 if (test_info.result()->Passed()) {
3480 }
else if (test_info.result()->Skipped()) {
3485 PrintTestName(test_info.test_suite_name(), test_info.name());
3486 if (test_info.result()->Failed())
3491 test_info.result()->elapsed_time()).c_str());
3498 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3505 printf(
"%s from %s (%s ms total)\n\n", counts.c_str(), test_case.name(),
3520 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3525 printf(
"Global test environment tear-down\n");
3531 const int failed_test_count = unit_test.failed_test_count();
3535 for (
int i = 0;
i < unit_test.total_test_suite_count(); ++
i) {
3540 for (
int j = 0;
j <
test_suite.total_test_count(); ++
j) {
3541 const TestInfo& test_info = *
test_suite.GetTestInfo(j);
3542 if (!test_info.should_run() || !test_info.result()->Failed()) {
3551 printf(
"\n%2d FAILED %s\n", failed_test_count,
3552 failed_test_count == 1 ?
"TEST" :
"TESTS");
3559 int suite_failure_count = 0;
3565 if (
test_suite.ad_hoc_test_result().Failed()) {
3568 ++suite_failure_count;
3571 if (suite_failure_count > 0) {
3572 printf(
"\n%2d FAILED TEST %s\n", suite_failure_count,
3573 suite_failure_count == 1 ?
"SUITE" :
"SUITES");
3580 if (skipped_test_count == 0) {
3589 for (
int j = 0; j <
test_suite.total_test_count(); ++j) {
3590 const TestInfo& test_info = *
test_suite.GetTestInfo(j);
3591 if (!test_info.should_run() || !test_info.result()->Skipped()) {
3604 printf(
"%s from %s ran.",
3615 const int skipped_test_count = unit_test.skipped_test_count();
3616 if (skipped_test_count > 0) {
3622 if (!unit_test.Passed()) {
3627 int num_disabled = unit_test.reportable_disabled_test_count();
3628 if (num_disabled && !
GTEST_FLAG(also_run_disabled_tests)) {
3629 if (unit_test.Passed()) {
3632 ColoredPrintf(GTestColor::kYellow,
" YOU HAVE %d DISABLED %s\n\n",
3633 num_disabled, num_disabled == 1 ?
"TEST" :
"TESTS");
3657 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3661 #endif // OnTestCaseStart
3667 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3671 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3714 printf(
"%s from %s ran.",
3726 if (skipped_test_count > 0) {
3732 if (num_disabled && !
GTEST_FLAG(also_run_disabled_tests)) {
3733 if (unit_test.
Passed()) {
3736 ColoredPrintf(GTestColor::kYellow,
" YOU HAVE %d DISABLED %s\n\n",
3737 num_disabled, num_disabled == 1 ?
"TEST" :
"TESTS");
3765 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3767 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3773 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3775 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3813 #define GTEST_REPEATER_METHOD_(Name, Type) \
3814 void TestEventRepeater::Name(const Type& parameter) { \
3815 if (forwarding_enabled_) { \
3816 for (size_t i = 0; i < listeners_.size(); i++) { \
3817 listeners_[i]->Name(parameter); \
3823 #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
3824 void TestEventRepeater::Name(const Type& parameter) { \
3825 if (forwarding_enabled_) { \
3826 for (size_t i = listeners_.size(); i != 0; i--) { \
3827 listeners_[i - 1]->Name(parameter); \
3835 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3837 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3846 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3848 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3852 #undef GTEST_REPEATER_METHOD_
3853 #undef GTEST_REVERSE_REPEATER_METHOD_
3859 listeners_[
i]->OnTestIterationStart(unit_test, iteration);
3867 for (
size_t i =
listeners_.size(); i > 0; i--) {
3868 listeners_[
i - 1]->OnTestIterationEnd(unit_test, iteration);
3876 class XmlUnitTestResultPrinter :
public EmptyTestEventListener {
3885 const std::vector<TestSuite*>& test_suites);
3891 return c == 0x9 || c == 0xA || c == 0xD;
3930 const char* test_suite_name,
3960 : output_file_(output_file) {
3970 std::stringstream
stream;
3977 const std::vector<TestSuite*>& test_suites) {
3979 std::stringstream
stream;
3999 for (
size_t i = 0;
i <
str.size(); ++
i) {
4035 return m.GetString();
4045 for (std::string::const_iterator
it =
str.begin();
it !=
str.end(); ++
it)
4071 ::std::stringstream ss;
4072 ss << (static_cast<double>(ms) * 1
e-3);
4077 #if defined(_MSC_VER)
4079 #elif defined(__MINGW32__) || defined(__MINGW64__)
4082 struct tm* tm_ptr = localtime(&
seconds);
4083 if (tm_ptr ==
nullptr)
return false;
4087 return localtime_r(&
seconds,
out) !=
nullptr;
4094 struct tm time_struct;
4110 const char* segment =
data;
4113 const char*
const next_segment = strstr(segment,
"]]>");
4114 if (next_segment !=
nullptr) {
4116 segment,
static_cast<std::streamsize
>(next_segment - segment));
4117 *
stream <<
"]]>]]><![CDATA[";
4118 segment = next_segment + strlen(
"]]>");
4132 const std::vector<std::string>& allowed_names =
4136 allowed_names.end())
4145 const char* test_suite_name,
4146 const TestInfo& test_info) {
4147 const TestResult&
result = *test_info.result();
4150 if (test_info.is_in_another_shard()) {
4157 if (test_info.value_param() !=
nullptr) {
4159 test_info.value_param());
4161 if (test_info.type_param() !=
nullptr) {
4163 test_info.type_param());
4174 test_info.should_run() ?
"run" :
"notrun");
4176 test_info.should_run()
4177 ? (
result.Skipped() ?
"skipped" :
"completed")
4182 stream, kTestsuite,
"timestamp",
4188 for (
int i = 0;
i <
result.total_part_count(); ++
i) {
4189 const TestPartResult& part =
result.GetTestPartResult(
i);
4190 if (part.failed()) {
4191 if (++
failures == 1 && skips == 0) {
4196 part.line_number());
4198 *
stream <<
" <failure message=\""
4203 *
stream <<
"</failure>\n";
4204 }
else if (part.skipped()) {
4205 if (++skips == 1 &&
failures == 0) {
4210 part.line_number());
4212 *
stream <<
" <skipped message=\""
4216 *
stream <<
"</skipped>\n";
4220 if (
failures == 0 && skips == 0 &&
result.test_property_count() == 0) {
4227 *
stream <<
" </testcase>\n";
4235 *
stream <<
" <" << kTestsuite;
4243 stream, kTestsuite,
"disabled",
4253 stream, kTestsuite,
"timestamp",
4262 *
stream <<
" </" << kTestsuite <<
">\n";
4267 const UnitTest& unit_test) {
4270 *
stream <<
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
4271 *
stream <<
"<" << kTestsuites;
4278 stream, kTestsuites,
"disabled",
4284 stream, kTestsuites,
"timestamp",
4296 for (
int i = 0;
i < unit_test.total_test_suite_count(); ++
i) {
4297 if (unit_test.GetTestSuite(
i)->reportable_test_count() > 0)
4300 *
stream <<
"</" << kTestsuites <<
">\n";
4304 std::ostream*
stream,
const std::vector<TestSuite*>& test_suites) {
4307 *
stream <<
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
4308 *
stream <<
"<" << kTestsuites;
4310 int total_tests = 0;
4312 total_tests +=
test_suite->total_test_count();
4322 *
stream <<
"</" << kTestsuites <<
">\n";
4328 const TestResult&
result) {
4330 for (
int i = 0;
i <
result.test_property_count(); ++
i) {
4331 const TestProperty&
property =
result.GetTestProperty(
i);
4332 attributes <<
" " <<
property.key() <<
"="
4335 return attributes.GetString();
4343 if (
result.test_property_count() <= 0) {
4347 *
stream <<
"<" << kProperties <<
">\n";
4348 for (
int i = 0;
i <
result.test_property_count(); ++
i) {
4349 const TestProperty&
property =
result.GetTestProperty(
i);
4350 *
stream <<
"<" << kProperty;
4355 *
stream <<
"</" << kProperties <<
">\n";
4361 class JsonUnitTestResultPrinter :
public EmptyTestEventListener {
4369 const std::vector<TestSuite*>& test_suites);
4392 const char* test_suite_name,
4393 const TestInfo& test_info);
4401 const UnitTest& unit_test);
4416 : output_file_(output_file) {
4417 if (output_file_.empty()) {
4422 void JsonUnitTestResultPrinter::OnTestIterationEnd(
const UnitTest& unit_test,
4425 std::stringstream
stream;
4426 PrintJsonUnitTest(&
stream, unit_test);
4435 for (
size_t i = 0;
i <
str.size(); ++
i) {
4460 m <<
"\\u00" << String::FormatByte(
static_cast<unsigned char>(
ch));
4468 return m.GetString();
4476 ::std::stringstream ss;
4477 ss << (static_cast<double>(ms) * 1e-3) <<
"s";
4484 struct tm time_struct;
4489 String::FormatIntWidth2(time_struct.tm_mon + 1) +
"-" +
4490 String::FormatIntWidth2(time_struct.tm_mday) +
"T" +
4491 String::FormatIntWidth2(time_struct.tm_hour) +
":" +
4492 String::FormatIntWidth2(time_struct.tm_min) +
":" +
4493 String::FormatIntWidth2(time_struct.tm_sec) +
"Z";
4500 void JsonUnitTestResultPrinter::OutputJsonKey(
4507 const std::vector<std::string>& allowed_names =
4511 allowed_names.end())
4520 void JsonUnitTestResultPrinter::OutputJsonKey(
4527 const std::vector<std::string>& allowed_names =
4531 allowed_names.end())
4541 void JsonUnitTestResultPrinter::OutputJsonTestInfo(::std::ostream*
stream,
4542 const char* test_suite_name,
4543 const TestInfo& test_info) {
4544 const TestResult&
result = *test_info.result();
4549 OutputJsonKey(
stream, kTestsuite,
"name", test_info.name(), kIndent);
4551 if (test_info.value_param() !=
nullptr) {
4552 OutputJsonKey(
stream, kTestsuite,
"value_param", test_info.value_param(),
4555 if (test_info.type_param() !=
nullptr) {
4556 OutputJsonKey(
stream, kTestsuite,
"type_param", test_info.type_param(),
4560 OutputJsonKey(
stream, kTestsuite,
"file", test_info.file(), kIndent);
4561 OutputJsonKey(
stream, kTestsuite,
"line", test_info.line(), kIndent,
false);
4566 OutputJsonKey(
stream, kTestsuite,
"status",
4567 test_info.should_run() ?
"RUN" :
"NOTRUN", kIndent);
4568 OutputJsonKey(
stream, kTestsuite,
"result",
4569 test_info.should_run()
4570 ? (
result.Skipped() ?
"SKIPPED" :
"COMPLETED")
4573 OutputJsonKey(
stream, kTestsuite,
"timestamp",
4576 OutputJsonKey(
stream, kTestsuite,
"time",
4578 OutputJsonKey(
stream, kTestsuite,
"classname", test_suite_name, kIndent,
4583 for (
int i = 0;
i <
result.total_part_count(); ++
i) {
4584 const TestPartResult& part =
result.GetTestPartResult(
i);
4585 if (part.failed()) {
4588 *
stream << kIndent <<
"\"" <<
"failures" <<
"\": [\n";
4592 part.line_number());
4594 *
stream << kIndent <<
" {\n"
4595 << kIndent <<
" \"failure\": \"" <<
message <<
"\",\n"
4596 << kIndent <<
" \"type\": \"\"\n"
4602 *
stream <<
"\n" << kIndent <<
"]";
4607 void JsonUnitTestResultPrinter::PrintJsonTestSuite(
4614 OutputJsonKey(
stream, kTestsuite,
"tests",
test_suite.reportable_test_count(),
4617 OutputJsonKey(
stream, kTestsuite,
"failures",
4619 OutputJsonKey(
stream, kTestsuite,
"disabled",
4620 test_suite.reportable_disabled_test_count(), kIndent);
4621 OutputJsonKey(
stream, kTestsuite,
"errors", 0, kIndent);
4623 stream, kTestsuite,
"timestamp",
4626 OutputJsonKey(
stream, kTestsuite,
"time",
4633 *
stream << kIndent <<
"\"" << kTestsuite <<
"\": [\n";
4646 *
stream <<
"\n" << kIndent <<
"]\n" <<
Indent(4) <<
"}";
4650 void JsonUnitTestResultPrinter::PrintJsonUnitTest(std::ostream*
stream,
4651 const UnitTest& unit_test) {
4656 OutputJsonKey(
stream, kTestsuites,
"tests", unit_test.reportable_test_count(),
4658 OutputJsonKey(
stream, kTestsuites,
"failures", unit_test.failed_test_count(),
4660 OutputJsonKey(
stream, kTestsuites,
"disabled",
4661 unit_test.reportable_disabled_test_count(), kIndent);
4662 OutputJsonKey(
stream, kTestsuites,
"errors", 0, kIndent);
4664 OutputJsonKey(
stream, kTestsuites,
"random_seed", unit_test.random_seed(),
4667 OutputJsonKey(
stream, kTestsuites,
"timestamp",
4670 OutputJsonKey(
stream, kTestsuites,
"time",
4674 *
stream << TestPropertiesAsJson(unit_test.ad_hoc_test_result(), kIndent)
4677 OutputJsonKey(
stream, kTestsuites,
"name",
"AllTests", kIndent);
4678 *
stream << kIndent <<
"\"" << kTestsuites <<
"\": [\n";
4681 for (
int i = 0;
i < unit_test.total_test_suite_count(); ++
i) {
4682 if (unit_test.GetTestSuite(
i)->reportable_test_count() > 0) {
4688 PrintJsonTestSuite(
stream, *unit_test.GetTestSuite(
i));
4692 *
stream <<
"\n" << kIndent <<
"]\n" <<
"}\n";
4695 void JsonUnitTestResultPrinter::PrintJsonTestList(
4696 std::ostream*
stream,
const std::vector<TestSuite*>& test_suites) {
4700 int total_tests = 0;
4702 total_tests +=
test_suite->total_test_count();
4704 OutputJsonKey(
stream, kTestsuites,
"tests", total_tests, kIndent);
4706 OutputJsonKey(
stream, kTestsuites,
"name",
"AllTests", kIndent);
4707 *
stream << kIndent <<
"\"" << kTestsuites <<
"\": [\n";
4709 for (
size_t i = 0;
i < test_suites.size(); ++
i) {
4713 PrintJsonTestSuite(
stream, *test_suites[
i]);
4722 std::string JsonUnitTestResultPrinter::TestPropertiesAsJson(
4725 for (
int i = 0;
i <
result.test_property_count(); ++
i) {
4726 const TestProperty&
property =
result.GetTestProperty(
i);
4727 attributes <<
",\n" <<
indent <<
"\"" <<
property.key() <<
"\": "
4728 <<
"\"" << EscapeJson(property.value()) <<
"\"";
4730 return attributes.GetString();
4735 #if GTEST_CAN_STREAM_RESULTS_
4751 result.append(
"%" + String::FormatByte(
static_cast<unsigned char>(
ch)));
4761 void StreamingListener::SocketWriter::MakeConnection() {
4763 <<
"MakeConnection() can't be called when there is already a connection.";
4766 memset(&hints, 0,
sizeof(hints));
4773 const int error_num = getaddrinfo(
4774 host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
4775 if (error_num != 0) {
4777 << gai_strerror(error_num);
4781 for (
addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr !=
nullptr;
4782 cur_addr = cur_addr->
ai_next) {
4784 cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol);
4785 if (sockfd_ != -1) {
4787 if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
4794 freeaddrinfo(servinfo);
4796 if (sockfd_ == -1) {
4798 << host_name_ <<
":" << port_num_;
4803 #endif // GTEST_CAN_STREAM_RESULTS__
4807 const char*
const OsStackTraceGetterInterface::kElidedFramesMarker =
4810 std::string OsStackTraceGetter::CurrentStackTrace(
int max_depth,
int skip_count)
4815 if (max_depth <= 0) {
4821 std::vector<void*> raw_stack(max_depth);
4823 const int raw_stack_size =
4826 void* caller_frame =
nullptr;
4829 caller_frame = caller_frame_;
4832 for (
int i = 0;
i < raw_stack_size; ++
i) {
4833 if (raw_stack[
i] == caller_frame &&
4841 const char* symbol =
"(unknown)";
4847 snprintf(
line,
sizeof(
line),
" %p: %s\n", raw_stack[
i], symbol);
4853 #else // !GTEST_HAS_ABSL
4854 static_cast<void>(max_depth);
4855 static_cast<void>(skip_count);
4857 #endif // GTEST_HAS_ABSL
4862 void* caller_frame =
nullptr;
4864 caller_frame =
nullptr;
4868 caller_frame_ = caller_frame;
4869 #endif // GTEST_HAS_ABSL
4874 class ScopedPrematureExitFile {
4877 : premature_exit_filepath_(premature_exit_filepath ?
4878 premature_exit_filepath :
"") {
4880 if (!premature_exit_filepath_.empty()) {
4885 fwrite(
"0", 1, 1, pfile);
4891 #if !defined GTEST_OS_ESP8266
4892 if (!premature_exit_filepath_.empty()) {
4893 int retval = remove(premature_exit_filepath_.c_str());
4896 << premature_exit_filepath_ <<
"\" with error "
4913 TestEventListeners::TestEventListeners()
4915 default_result_printer_(nullptr),
4916 default_xml_generator_(nullptr) {}
4925 repeater_->Append(listener);
4932 if (listener == default_result_printer_)
4933 default_result_printer_ =
nullptr;
4934 else if (listener == default_xml_generator_)
4935 default_xml_generator_ =
nullptr;
4936 return repeater_->Release(listener);
4949 if (default_result_printer_ != listener) {
4952 delete Release(default_result_printer_);
4953 default_result_printer_ = listener;
4954 if (listener !=
nullptr)
Append(listener);
4964 if (default_xml_generator_ != listener) {
4967 delete Release(default_xml_generator_);
4968 default_xml_generator_ = listener;
4969 if (listener !=
nullptr)
Append(listener);
4976 return repeater_->forwarding_enabled();
4980 repeater_->set_forwarding_enabled(
false);
4997 #if defined(__BORLANDC__)
4998 static UnitTest*
const instance =
new UnitTest;
5003 #endif // defined(__BORLANDC__)
5008 return impl()->successful_test_suite_count();
5013 return impl()->failed_test_suite_count();
5018 return impl()->total_test_suite_count();
5024 return impl()->test_suite_to_run_count();
5028 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5030 return impl()->successful_test_suite_count();
5033 return impl()->failed_test_suite_count();
5036 return impl()->total_test_suite_count();
5039 return impl()->test_suite_to_run_count();
5041 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5045 return impl()->successful_test_count();
5050 return impl()->skipped_test_count();
5058 return impl()->reportable_disabled_test_count();
5063 return impl()->disabled_test_count();
5068 return impl()->reportable_test_count();
5080 return impl()->start_timestamp();
5085 return impl()->elapsed_time();
5099 return impl()->GetTestSuite(i);
5103 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5105 return impl()->GetTestCase(i);
5107 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5112 return *impl()->ad_hoc_test_result();
5118 return impl()->GetMutableSuiteCase(i);
5124 return *impl()->listeners();
5138 if (
env ==
nullptr) {
5142 impl_->environments().push_back(
env);
5152 const char* file_name,
5160 if (
impl_->gtest_trace_stack().size() > 0) {
5163 for (
size_t i =
impl_->gtest_trace_stack().size(); i > 0; --i) {
5164 const internal::TraceInfo& trace =
impl_->gtest_trace_stack()[
i - 1];
5166 <<
" " << trace.message;
5170 if (os_stack_trace.c_str() !=
nullptr && !os_stack_trace.empty()) {
5174 const TestPartResult
result = TestPartResult(
5176 impl_->GetTestPartResultReporterForCurrentThread()->
5177 ReportTestPartResult(
result);
5187 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
5192 #elif (!defined(__native_client__)) && \
5193 ((defined(__clang__) || defined(__GNUC__)) && \
5194 (defined(__x86_64__) || defined(__i386__)))
5201 *
static_cast<volatile int*
>(
nullptr) = 1;
5202 #endif // GTEST_OS_WINDOWS
5204 #if GTEST_HAS_EXCEPTIONS
5205 throw internal::GoogleTestFailureException(
result);
5231 const bool in_death_test_child_process =
5255 const internal::ScopedPrematureExitFile premature_exit_file(
5256 in_death_test_child_process
5262 impl()->set_catch_exceptions(
GTEST_FLAG(catch_exceptions));
5264 #if GTEST_OS_WINDOWS
5269 if (impl()->catch_exceptions() || in_death_test_child_process) {
5270 # if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
5272 SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
5273 SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
5274 # endif // !GTEST_OS_WINDOWS_MOBILE
5276 # if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
5280 _set_error_mode(_OUT_TO_STDERR);
5283 # if defined(_MSC_VER) && !GTEST_OS_WINDOWS_MOBILE
5290 _set_abort_behavior(
5292 _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
5298 if (!IsDebuggerPresent()) {
5299 (void)_CrtSetReportMode(_CRT_ASSERT,
5300 _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
5301 (void)_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
5305 #endif // GTEST_OS_WINDOWS
5310 "auxiliary test code (environments or event listeners)") ? 0 : 1;
5316 return impl_->original_working_dir_.c_str();
5324 return impl_->current_test_suite();
5328 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5332 return impl_->current_test_suite();
5341 return impl_->current_test_info();
5349 internal::ParameterizedTestSuiteRegistry&
5351 return impl_->parameterized_test_registry();
5356 impl_ =
new internal::UnitTestImpl(
this);
5369 impl_->gtest_trace_stack().push_back(trace);
5376 impl_->gtest_trace_stack().pop_back();
5384 default_global_test_part_result_reporter_(this),
5385 default_per_thread_test_part_result_reporter_(this),
5387 &default_global_test_part_result_reporter_),
5388 per_thread_test_part_result_reporter_(
5389 &default_per_thread_test_part_result_reporter_),
5390 parameterized_test_registry_(),
5391 parameterized_tests_registered_(
false),
5392 last_death_test_suite_(-1),
5393 current_test_suite_(nullptr),
5394 current_test_info_(nullptr),
5395 ad_hoc_test_result_(),
5396 os_stack_trace_getter_(nullptr),
5397 post_flag_parse_init_performed_(
false),
5400 start_timestamp_(0),
5402 #
if GTEST_HAS_DEATH_TEST
5403 death_test_factory_(
new DefaultDeathTestFactory),
5406 catch_exceptions_(
false) {
5407 listeners()->SetDefaultResultPrinter(
new PrettyUnitTestResultPrinter);
5430 xml_element =
"testcase";
5433 xml_element =
"testsuite";
5436 xml_element =
"testsuites";
5439 test_result->RecordProperty(xml_element, test_property);
5442 #if GTEST_HAS_DEATH_TEST
5445 void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
5446 if (internal_run_death_test_flag_.get() !=
nullptr)
5449 #endif // GTEST_HAS_DEATH_TEST
5455 if (output_format ==
"xml") {
5458 }
else if (output_format ==
"json") {
5461 }
else if (output_format !=
"") {
5463 << output_format <<
"\" ignored.";
5467 #if GTEST_CAN_STREAM_RESULTS_
5470 void UnitTestImpl::ConfigureStreamingOutput() {
5474 if (
pos != std::string::npos) {
5483 #endif // GTEST_CAN_STREAM_RESULTS_
5495 #if defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
5498 #endif // defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
5500 #if GTEST_HAS_DEATH_TEST
5501 InitDeathTestSubprocessControlInfo();
5502 SuppressTestEventsIfInSubprocess();
5503 #endif // GTEST_HAS_DEATH_TEST
5518 #if GTEST_CAN_STREAM_RESULTS_
5520 ConfigureStreamingOutput();
5521 #endif // GTEST_CAN_STREAM_RESULTS_
5524 if (
GTEST_FLAG(install_failure_signal_handler)) {
5528 #endif // GTEST_HAS_ABSL
5540 class TestSuiteNameIs {
5568 const char* test_suite_name,
const char* type_param,
5574 TestSuiteNameIs(test_suite_name));
5579 auto*
const new_test_suite =
5580 new TestSuite(test_suite_name, type_param, set_up_tc, tear_down_tc);
5598 return new_test_suite;
5635 bool in_subprocess_for_death_test =
false;
5637 #if GTEST_HAS_DEATH_TEST
5638 in_subprocess_for_death_test =
5639 (internal_run_death_test_flag_.get() !=
nullptr);
5640 # if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
5641 if (in_subprocess_for_death_test) {
5642 GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_();
5644 # endif // defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
5645 #endif // GTEST_HAS_DEATH_TEST
5648 in_subprocess_for_death_test);
5652 const bool has_tests_to_run =
FilterTests(should_shard
5667 bool failed =
false;
5672 repeater->OnTestProgramStart(*
parent_);
5676 const int repeat = in_subprocess_for_death_test ? 1 :
GTEST_FLAG(repeat);
5678 const bool gtest_repeat_forever = repeat < 0;
5679 for (
int i = 0; gtest_repeat_forever ||
i != repeat;
i++) {
5687 if (has_tests_to_run &&
GTEST_FLAG(shuffle)) {
5696 repeater->OnTestIterationStart(*
parent_, i);
5699 if (has_tests_to_run) {
5701 repeater->OnEnvironmentsSetUpStart(*
parent_);
5703 repeater->OnEnvironmentsSetUpEnd(*
parent_);
5713 const TestPartResult& test_part_result =
5715 if (test_part_result.type() == TestPartResult::kSkip) {
5736 repeater->OnEnvironmentsTearDownStart(*
parent_);
5739 repeater->OnEnvironmentsTearDownEnd(*
parent_);
5745 repeater->OnTestIterationEnd(*
parent_, i);
5766 repeater->OnTestProgramEnd(*
parent_);
5768 if (!gtest_is_initialized_before_run_all_tests) {
5771 "\nIMPORTANT NOTICE - DO NOT IGNORE:\n"
5773 "() before calling RUN_ALL_TESTS(). This is INVALID. Soon " GTEST_NAME_
5774 " will start to enforce the valid usage. "
5775 "Please fix it ASAP, or IT WILL START TO FAIL.\n");
5776 #if GTEST_FOR_GOOGLE_
5778 "For more details, see http://wiki/Main/ValidGUnitMain.\n");
5779 #endif // GTEST_FOR_GOOGLE_
5791 if (test_shard_file !=
nullptr) {
5793 if (
file ==
nullptr) {
5795 "Could not write to the test shard status file \"%s\" "
5796 "specified by the %s environment variable.\n",
5812 const char* shard_index_env,
5813 bool in_subprocess_for_death_test) {
5814 if (in_subprocess_for_death_test) {
5821 if (total_shards == -1 && shard_index == -1) {
5823 }
else if (total_shards == -1 && shard_index != -1) {
5825 <<
"Invalid environment variables: you have "
5831 }
else if (total_shards != -1 && shard_index == -1) {
5833 <<
"Invalid environment variables: you have "
5839 }
else if (shard_index < 0 || shard_index >= total_shards) {
5841 <<
"Invalid environment variables: we require 0 <= "
5850 return total_shards > 1;
5858 if (str_val ==
nullptr) {
5875 return (test_id % total_shards) == shard_index;
5895 int num_runnable_tests = 0;
5896 int num_selected_tests = 0;
5901 for (
size_t j = 0; j <
test_suite->test_info_list().
size(); j++) {
5902 TestInfo*
const test_info =
test_suite->test_info_list()[j];
5910 test_info->is_disabled_ = is_disabled;
5913 test_suite_name, test_name);
5914 test_info->matches_filter_ = matches_filter;
5916 const bool is_runnable =
5917 (
GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
5920 const bool is_in_another_shard =
5923 test_info->is_in_another_shard_ = is_in_another_shard;
5924 const bool is_selected = is_runnable && !is_in_another_shard;
5926 num_runnable_tests += is_runnable;
5927 num_selected_tests += is_selected;
5929 test_info->should_run_ = is_selected;
5933 return num_selected_tests;
5941 if (
str !=
nullptr) {
5942 for (
int i = 0; *
str !=
'\0'; ++
str) {
5943 if (
i >= max_length) {
5961 const int kMaxParamLength = 250;
5964 bool printed_test_suite_name =
false;
5966 for (
size_t j = 0; j <
test_suite->test_info_list().
size(); j++) {
5969 if (!printed_test_suite_name) {
5970 printed_test_suite_name =
true;
5993 if (output_format ==
"xml" || output_format ==
"json") {
5996 std::stringstream
stream;
5997 if (output_format ==
"xml") {
5998 XmlUnitTestResultPrinter(
6001 }
else if (output_format ==
"json") {
6002 JsonUnitTestResultPrinter(
6017 OsStackTraceGetterInterface* getter) {
6029 #ifdef GTEST_OS_STACK_TRACE_GETTER_
6033 #endif // GTEST_OS_STACK_TRACE_GETTER_
6096 class ClassUniqueToAlwaysTrue {};
6099 bool IsTrue(
bool condition) {
return condition; }
6102 #if GTEST_HAS_EXCEPTIONS
6106 throw ClassUniqueToAlwaysTrue();
6107 #endif // GTEST_HAS_EXCEPTIONS
6115 const size_t prefix_len = strlen(
prefix);
6116 if (strncmp(*pstr,
prefix, prefix_len) == 0) {
6117 *pstr += prefix_len;
6129 bool def_optional) {
6131 if (
str ==
nullptr ||
flag ==
nullptr)
return nullptr;
6135 const size_t flag_len = flag_str.length();
6136 if (strncmp(
str, flag_str.c_str(), flag_len) != 0)
return nullptr;
6139 const char* flag_end =
str + flag_len;
6142 if (def_optional && (flag_end[0] ==
'\0')) {
6149 if (flag_end[0] !=
'=')
return nullptr;
6152 return flag_end + 1;
6170 if (value_str ==
nullptr)
return false;
6173 *
value = !(*value_str ==
'0' || *value_str ==
'f' || *value_str ==
'F');
6186 if (value_str ==
nullptr)
return false;
6197 template <
typename String>
6203 if (value_str ==
nullptr)
return false;
6242 const char* p = strchr(
str,
'@');
6250 const char ch = p[1];
6254 }
else if (
ch ==
'D') {
6256 }
else if (
ch ==
'R') {
6257 color = GTestColor::kRed;
6258 }
else if (
ch ==
'G') {
6259 color = GTestColor::kGreen;
6260 }
else if (
ch ==
'Y') {
6261 color = GTestColor::kYellow;
6269 "This program contains tests written using " GTEST_NAME_
6270 ". You can use the\n"
6271 "following command line flags to control its behavior:\n"
6276 " List the names of all tests instead of running them. The name of\n"
6277 " TEST(Foo, Bar) is \"Foo.Bar\".\n"
6279 "filter=@YPOSITIVE_PATTERNS"
6280 "[@G-@YNEGATIVE_PATTERNS]@D\n"
6281 " Run only the tests whose name matches one of the positive patterns "
6283 " none of the negative patterns. '?' matches any single character; "
6285 " matches any substring; ':' separates two patterns.\n"
6287 "also_run_disabled_tests@D\n"
6288 " Run all disabled tests too.\n"
6292 "repeat=@Y[COUNT]@D\n"
6293 " Run the tests repeatedly; use a negative count to repeat forever.\n"
6296 " Randomize tests' orders on every iteration.\n"
6298 "random_seed=@Y[NUMBER]@D\n"
6299 " Random number seed to use for shuffling test orders (between 1 and\n"
6300 " 99999, or 0 to use a seed based on the current time).\n"
6304 "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
6305 " Enable/disable colored output. The default is @Gauto@D.\n"
6308 " Only print test failures.\n"
6311 " Don't print the elapsed time of each test.\n"
6314 "@Y|@G:@YFILE_PATH]@D\n"
6315 " Generate a JSON or XML report in the given directory or with the "
6317 " file name. @YFILE_PATH@D defaults to @Gtest_detail.xml@D.\n"
6318 # if GTEST_CAN_STREAM_RESULTS_
6320 "stream_result_to=@YHOST@G:@YPORT@D\n"
6321 " Stream test results to the given server.\n"
6322 # endif // GTEST_CAN_STREAM_RESULTS_
6324 "Assertion Behavior:\n"
6325 # if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
6327 "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
6328 " Set the default death test style.\n"
6329 # endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
6331 "break_on_failure@D\n"
6332 " Turn assertion failures into debugger break-points.\n"
6334 "throw_on_failure@D\n"
6335 " Turn assertion failures into C++ exceptions for use by an external\n"
6336 " test framework.\n"
6338 "catch_exceptions=0@D\n"
6339 " Do not report exceptions as test failures. Instead, allow them\n"
6340 " to crash the program or throw a pop-up (on Windows).\n"
6343 "list_tests@D, you can alternatively set "
6344 "the corresponding\n"
6345 "environment variable of a flag (all letters in upper-case). For example, "
6347 "disable colored text output, you can either specify "
6349 "color=no@D or set\n"
6351 "COLOR@D environment variable to @Gno@D.\n"
6353 "For more information, please read the " GTEST_NAME_
6354 " documentation at\n"
6357 "(not one in your own code or tests), please report it to\n"
6391 #if GTEST_USE_OWN_FLAGFILE_FLAG_
6400 std::vector<std::string>
lines;
6402 for (
size_t i = 0;
i <
lines.size(); ++
i) {
6409 #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
6414 template <
typename CharType>
6416 for (
int i = 1;
i < *argc;
i++) {
6418 const char*
const arg = arg_string.c_str();
6424 bool remove_flag =
false;
6427 #if GTEST_USE_OWN_FLAGFILE_FLAG_
6431 #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
6432 }
else if (arg_string ==
"--help" || arg_string ==
"-h" ||
6433 arg_string ==
"-?" || arg_string ==
"/?" ||
6445 for (
int j = i;
j != *argc;
j++) {
6446 argv[
j] = argv[
j + 1];
6475 #ifndef GTEST_OS_IOS
6476 if (*_NSGetArgv() == argv) {
6477 *_NSGetArgc() = *argc;
6490 template <
typename CharType>
6495 if (*argc <= 0)
return;
6498 for (
int i = 0;
i != *argc;
i++) {
6504 #endif // GTEST_HAS_ABSL
6522 #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6523 GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
6524 #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6526 #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6532 #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6533 GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
6534 #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6536 #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6544 const auto arg0 =
"dummy";
6545 char* argv0 =
const_cast<char*
>(arg0);
6546 char** argv = &argv0;
6548 #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6549 GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(&argc, argv);
6550 #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6552 #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6556 #if defined(GTEST_CUSTOM_TEMPDIR_FUNCTION_)
6557 return GTEST_CUSTOM_TEMPDIR_FUNCTION_();
6558 #elif GTEST_OS_WINDOWS_MOBILE
6560 #elif GTEST_OS_WINDOWS
6562 if (temp_dir ==
nullptr || temp_dir[0] ==
'\0') {
6564 }
else if (temp_dir[strlen(temp_dir) - 1] ==
'\\') {
6569 #elif GTEST_OS_LINUX_ANDROID
6571 if (temp_dir ==
nullptr || temp_dir[0] ==
'\0') {
6572 return "/data/local/tmp/";
6576 #elif GTEST_OS_LINUX
6578 if (temp_dir ==
nullptr || temp_dir[0] ==
'\0') {
6585 #endif // GTEST_OS_WINDOWS_MOBILE
6593 internal::TraceInfo trace;