34 #include "gtest/gtest.h" 35 #include "gtest/internal/custom/gtest.h" 36 #include "gtest/gtest-spi.h" 60 # define GTEST_HAS_GETTIMEOFDAY_ 1 67 # include <sys/mman.h> 68 # include <sys/time.h> 72 #elif GTEST_OS_SYMBIAN 73 # define GTEST_HAS_GETTIMEOFDAY_ 1 74 # include <sys/time.h> 77 # define GTEST_HAS_GETTIMEOFDAY_ 1 78 # include <sys/time.h> 83 #elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE. 88 #elif GTEST_OS_WINDOWS // We are on Windows proper. 91 # include <sys/timeb.h> 92 # include <sys/types.h> 93 # include <sys/stat.h> 95 # if GTEST_OS_WINDOWS_MINGW 102 # define GTEST_HAS_GETTIMEOFDAY_ 1 103 # include <sys/time.h> 104 # endif // GTEST_OS_WINDOWS_MINGW 108 # include <windows.h> 116 # define GTEST_HAS_GETTIMEOFDAY_ 1 120 # include <sys/time.h> 123 #endif // GTEST_OS_LINUX 125 #if GTEST_HAS_EXCEPTIONS 126 # include <stdexcept> 129 #if GTEST_CAN_STREAM_RESULTS_ 130 # include <arpa/inet.h> 132 # include <sys/socket.h> 133 # include <sys/types.h> 141 #define GTEST_IMPLEMENTATION_ 1 142 #include "src/gtest-internal-inl.h" 143 #undef GTEST_IMPLEMENTATION_ 146 # define vsnprintf _vsnprintf 147 #endif // GTEST_OS_WINDOWS 193 #ifdef GTEST_TEST_FILTER_ENV_VAR_ 194 const char*
const testbridge_test_only = getenv(GTEST_TEST_FILTER_ENV_VAR_);
195 if (testbridge_test_only != NULL) {
196 return testbridge_test_only;
198 #endif // GTEST_TEST_FILTER_ENV_VAR_ 203 also_run_disabled_tests,
205 "Run disabled tests too, in addition to the tests normally being run.");
210 "True iff a failed assertion should be a debugger break-point.");
216 " should catch exceptions and treat them as test failures.");
221 "Whether to use colors in the output. Valid values: yes, no, " 222 "and auto. 'auto' means to use colors if the output is " 223 "being sent to a terminal and the TERM environment variable " 224 "is set to a terminal type that supports colors.");
229 "A colon-separated list of glob (not regex) patterns " 230 "for filtering the tests to run, optionally followed by a " 231 "'-' and a : separated list of negative patterns (tests to " 232 "exclude). A test is run if it matches one of the positive " 233 "patterns and does not match any of the negative patterns.");
236 "List all tests without running them.");
241 "A format (currently must be \"xml\"), optionally followed " 242 "by a colon and an output file name or directory. A directory " 243 "is indicated by a trailing pathname separator. " 244 "Examples: \"xml:filename.xml\", \"xml::directoryname/\". " 245 "If a directory is specified, output files will be created " 246 "within that directory, with file-names based on the test " 247 "executable's name and, if necessary, made unique by adding " 254 " should display elapsed time in text output.");
259 "Random number seed to use when shuffling test orders. Must be in range " 260 "[1, 99999], or 0 to use a seed based on the current time.");
265 "How many times to repeat each test. Specify a negative number " 266 "for repeating forever. Useful for shaking out flaky tests.");
269 show_internal_stack_frames,
false,
270 "True iff " GTEST_NAME_ " should include internal stack frames when " 271 "printing test failure stack traces.");
277 " should randomize tests' order on every run.");
282 "The maximum number of stack frames to print when an " 283 "assertion fails. The valid range is 0 through 100, inclusive.");
288 "This flag specifies the host name and the port number on which to stream " 289 "test results. Example: \"localhost:555\". The flag is effective only on " 295 "When this flag is specified, a failed assertion will throw an exception " 296 "if exceptions are enabled or exit the program with a non-zero code " 299 #if GTEST_USE_OWN_FLAGFILE_FLAG_ 303 "This flag specifies the flagfile to read command-line flags from.");
304 #endif // GTEST_USE_OWN_FLAGFILE_FLAG_ 313 state_ = (1103515245U*state_ + 12345U) % kMaxRange;
316 <<
"Cannot generate a number in the range [0, 0).";
318 <<
"Generation of a number in [0, " << range <<
") was requested, " 319 <<
"but this can only generate numbers in [0, " << kMaxRange <<
").";
324 return state_ %
range;
338 for (
size_t i = 0;
i < case_list.size();
i++) {
339 sum += (case_list[
i]->*method)();
365 :
data_(
new AssertHelperData(type, file, line, message)) {
387 ::std::vector<testing::internal::string>
g_argvs;
389 const ::std::vector<testing::internal::string>&
GetArgvs() {
390 #if defined(GTEST_CUSTOM_GET_ARGVS_) 391 return GTEST_CUSTOM_GET_ARGVS_();
392 #else // defined(GTEST_CUSTOM_GET_ARGVS_) 394 #endif // defined(GTEST_CUSTOM_GET_ARGVS_) 406 #endif // GTEST_OS_WINDOWS 416 if (gtest_output_flag == NULL)
return std::string(
"");
418 const char*
const colon = strchr(gtest_output_flag,
':');
419 return (colon == NULL) ?
421 std::string(gtest_output_flag, colon - gtest_output_flag);
428 if (gtest_output_flag == NULL)
431 const char*
const colon = strchr(gtest_output_flag,
':');
449 return output_name.
string();
453 GetOutputFormat().c_str()));
469 return *str !=
'\0' && PatternMatchesString(pattern + 1, str + 1);
471 return (*str !=
'\0' && PatternMatchesString(pattern, str + 1)) ||
472 PatternMatchesString(pattern + 1, str);
474 return *pattern == *str &&
475 PatternMatchesString(pattern + 1, str + 1);
481 const char *cur_pattern =
filter;
483 if (PatternMatchesString(cur_pattern, name.c_str())) {
488 cur_pattern = strchr(cur_pattern,
':');
491 if (cur_pattern == NULL) {
504 const std::string& full_name = test_case_name +
"." + test_name.c_str();
508 const char*
const p =
GTEST_FLAG(filter).c_str();
509 const char*
const dash = strchr(p,
'-');
518 if (positive.empty()) {
526 return (MatchesFilter(full_name, positive.c_str()) &&
527 !MatchesFilter(full_name, negative.c_str()));
534 int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
543 const DWORD kCxxExceptionCode = 0xe06d7363;
545 bool should_handle =
true;
548 should_handle =
false;
549 else if (exception_code == EXCEPTION_BREAKPOINT)
550 should_handle =
false;
551 else if (exception_code == kCxxExceptionCode)
552 should_handle =
false;
554 return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
556 #endif // GTEST_HAS_SEH 565 : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
575 : intercept_mode_(intercept_mode),
582 if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
595 if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
606 result_->Append(result);
621 return GetTypeId<Test>();
636 const string& substr) {
639 "1 non-fatal failure");
641 if (results.
size() != 1) {
642 msg <<
"Expected: " << expected <<
"\n" 643 <<
" Actual: " << results.
size() <<
" failures";
644 for (
int i = 0;
i < results.
size();
i++) {
657 if (strstr(r.
message(), substr.c_str()) == NULL) {
673 const string& substr)
691 unit_test_->current_test_result()->AddTestPartResult(result);
692 unit_test_->listeners()->repeater()->OnTestPartResult(result);
700 unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
707 return global_test_part_result_repoter_;
714 global_test_part_result_repoter_ = reporter;
720 return per_thread_test_part_result_reporter_.get();
726 per_thread_test_part_result_reporter_.set(reporter);
741 return static_cast<int>(test_cases_.size());
797 return os_stack_trace_getter()->CurrentStackTrace(
798 static_cast<int>(
GTEST_FLAG(stack_trace_depth)),
807 #if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__) 812 const DWORD kTenthMicrosInMilliSecond = 10000;
814 SYSTEMTIME now_systime;
815 FILETIME now_filetime;
816 ULARGE_INTEGER now_int64;
819 GetSystemTime(&now_systime);
820 if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
821 now_int64.LowPart = now_filetime.dwLowDateTime;
822 now_int64.HighPart = now_filetime.dwHighDateTime;
823 now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
824 kJavaEpochToWinFileTimeDelta;
825 return now_int64.QuadPart;
828 #elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_ 839 return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
842 gettimeofday(&now, NULL);
843 return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
845 #
error "Don't know how to get the current time on your system." 853 #if GTEST_OS_WINDOWS_MOBILE 858 LPCWSTR String::AnsiToUtf16(
const char* ansi) {
859 if (!ansi)
return NULL;
860 const int length = strlen(ansi);
861 const int unicode_length =
862 MultiByteToWideChar(CP_ACP, 0, ansi, length,
864 WCHAR* unicode =
new WCHAR[unicode_length + 1];
865 MultiByteToWideChar(CP_ACP, 0, ansi, length,
866 unicode, unicode_length);
867 unicode[unicode_length] = 0;
875 const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
876 if (!utf16_str)
return NULL;
877 const int ansi_length =
878 WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
879 NULL, 0, NULL, NULL);
880 char* ansi =
new char[ansi_length + 1];
881 WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
882 ansi, ansi_length, NULL, NULL);
883 ansi[ansi_length] = 0;
887 #endif // GTEST_OS_WINDOWS_MOBILE 895 if ( lhs == NULL )
return rhs == NULL;
897 if ( rhs == NULL )
return false;
899 return strcmp(lhs, rhs) == 0;
902 #if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING 906 static void StreamWideCharsToMessage(
const wchar_t* wstr,
size_t length,
908 for (
size_t i = 0;
i != length; ) {
909 if (wstr[
i] != L
'\0') {
910 *msg << WideStringToUtf8(wstr + i, static_cast<int>(length -
i));
911 while (
i != length && wstr[
i] != L
'\0')
920 #endif // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING 923 ::std::vector< ::std::string>*
dest) {
924 ::std::vector< ::std::string> parsed;
925 ::std::string::size_type pos = 0;
927 const ::std::string::size_type colon = str.find(delimiter, pos);
928 if (colon == ::std::string::npos) {
929 parsed.push_back(str.substr(pos));
932 parsed.push_back(str.substr(pos, colon - pos));
961 #if GTEST_HAS_STD_WSTRING 965 internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(),
this);
968 #endif // GTEST_HAS_STD_WSTRING 970 #if GTEST_HAS_GLOBAL_WSTRING 974 internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(),
this);
977 #endif // GTEST_HAS_GLOBAL_WSTRING 1004 if (message_.get() != NULL)
1005 negation << *message_;
1025 namespace internal {
1027 namespace edit_distance {
1029 const std::vector<size_t>& right) {
1030 std::vector<std::vector<double> > costs(
1031 left.size() + 1, std::vector<double>(right.size() + 1));
1032 std::vector<std::vector<EditType> > best_move(
1033 left.size() + 1, std::vector<EditType>(right.size() + 1));
1036 for (
size_t l_i = 0; l_i < costs.size(); ++l_i) {
1037 costs[l_i][0] =
static_cast<double>(l_i);
1041 for (
size_t r_i = 1; r_i < costs[0].size(); ++r_i) {
1042 costs[0][r_i] =
static_cast<double>(r_i);
1043 best_move[0][r_i] =
kAdd;
1046 for (
size_t l_i = 0; l_i < left.size(); ++l_i) {
1047 for (
size_t r_i = 0; r_i < right.size(); ++r_i) {
1048 if (left[l_i] == right[r_i]) {
1050 costs[l_i + 1][r_i + 1] = costs[l_i][r_i];
1051 best_move[l_i + 1][r_i + 1] =
kMatch;
1055 const double add = costs[l_i + 1][r_i];
1056 const double remove = costs[l_i][r_i + 1];
1057 const double replace = costs[l_i][r_i];
1058 if (add <
remove && add < replace) {
1059 costs[l_i + 1][r_i + 1] = add + 1;
1060 best_move[l_i + 1][r_i + 1] =
kAdd;
1061 }
else if (
remove < add &&
remove < replace) {
1062 costs[l_i + 1][r_i + 1] =
remove + 1;
1063 best_move[l_i + 1][r_i + 1] =
kRemove;
1067 costs[l_i + 1][r_i + 1] = replace + 1.00001;
1068 best_move[l_i + 1][r_i + 1] =
kReplace;
1074 std::vector<EditType> best_path;
1075 for (
size_t l_i = left.size(), r_i = right.size(); l_i > 0 || r_i > 0;) {
1077 best_path.push_back(move);
1078 l_i -= move !=
kAdd;
1081 std::reverse(best_path.begin(), best_path.end());
1088 class InternalStrings {
1091 IdMap::iterator it =
ids_.find(str);
1092 if (it !=
ids_.end())
return it->second;
1093 size_t id =
ids_.size();
1094 return ids_[str] = id;
1098 typedef std::map<std::string, size_t> IdMap;
1105 const std::vector<std::string>& left,
1106 const std::vector<std::string>& right) {
1107 std::vector<size_t> left_ids, right_ids;
1109 InternalStrings intern_table;
1110 for (
size_t i = 0;
i < left.size(); ++
i) {
1111 left_ids.push_back(intern_table.GetId(left[
i]));
1113 for (
size_t i = 0;
i < right.size(); ++
i) {
1114 right_ids.push_back(intern_table.GetId(right[
i]));
1128 Hunk(
size_t left_start,
size_t right_start)
1135 void PushLine(
char edit,
const char* line) {
1140 hunk_.push_back(std::make_pair(
' ', line));
1148 hunk_adds_.push_back(std::make_pair(
'+', line));
1153 void PrintTo(std::ostream* os) {
1156 for (
std::list<std::pair<char, const char*> >::const_iterator it =
1158 it !=
hunk_.end(); ++it) {
1159 *os << it->first << it->second <<
"\n";
1175 void PrintHeader(std::ostream* ss)
const {
1204 const std::vector<std::string>& right,
1208 size_t l_i = 0, r_i = 0, edit_i = 0;
1209 std::stringstream ss;
1210 while (edit_i < edits.size()) {
1212 while (edit_i < edits.size() && edits[edit_i] ==
kMatch) {
1219 const size_t prefix_context =
std::min(l_i, context);
1220 Hunk hunk(l_i - prefix_context + 1, r_i - prefix_context + 1);
1221 for (
size_t i = prefix_context;
i > 0; --
i) {
1222 hunk.PushLine(
' ', left[l_i -
i].c_str());
1227 size_t n_suffix = 0;
1228 for (; edit_i < edits.size(); ++edit_i) {
1229 if (n_suffix >= context) {
1231 std::vector<EditType>::const_iterator it = edits.begin() + edit_i;
1232 while (it != edits.end() && *it ==
kMatch) ++it;
1233 if (it == edits.end() || (it - edits.begin()) - edit_i >= context) {
1241 n_suffix = edit ==
kMatch ? n_suffix + 1 : 0;
1244 hunk.PushLine(edit ==
kMatch ?
' ' :
'-', left[l_i].c_str());
1247 hunk.PushLine(
'+', right[r_i].c_str());
1251 l_i += edit !=
kAdd;
1255 if (!hunk.has_edits()) {
1272 std::vector<std::string> SplitEscapedString(
const std::string& str) {
1273 std::vector<std::string>
lines;
1274 size_t start = 0,
end = str.size();
1275 if (
end > 2 && str[0] ==
'"' && str[
end - 1] ==
'"') {
1279 bool escaped =
false;
1280 for (
size_t i = start;
i + 1 <
end; ++
i) {
1283 if (str[
i] ==
'n') {
1284 lines.push_back(str.substr(start,
i - start - 1));
1288 escaped = str[
i] ==
'\\';
1291 lines.push_back(str.substr(start, end - start));
1312 AssertionResult
EqFailure(
const char* lhs_expression,
1313 const char* rhs_expression,
1316 bool ignoring_case) {
1318 msg <<
" Expected: " << lhs_expression;
1319 if (lhs_value != lhs_expression) {
1320 msg <<
"\n Which is: " << lhs_value;
1322 msg <<
"\nTo be equal to: " << rhs_expression;
1323 if (rhs_value != rhs_expression) {
1324 msg <<
"\n Which is: " << rhs_value;
1327 if (ignoring_case) {
1328 msg <<
"\nIgnoring case";
1331 if (!lhs_value.empty() && !rhs_value.empty()) {
1332 const std::vector<std::string> lhs_lines =
1333 SplitEscapedString(lhs_value);
1334 const std::vector<std::string> rhs_lines =
1335 SplitEscapedString(rhs_value);
1336 if (lhs_lines.size() > 1 || rhs_lines.size() > 1) {
1337 msg <<
"\nWith diff:\n" 1347 const AssertionResult& assertion_result,
1348 const char* expression_text,
1349 const char* actual_predicate_value,
1350 const char* expected_predicate_value) {
1351 const char* actual_message = assertion_result.message();
1353 msg <<
"Value of: " << expression_text
1354 <<
"\n Actual: " << actual_predicate_value;
1355 if (actual_message[0] !=
'\0')
1356 msg <<
" (" << actual_message <<
")";
1357 msg <<
"\nExpected: " << expected_predicate_value;
1358 return msg.GetString();
1364 const char* abs_error_expr,
1368 const double diff = fabs(val1 - val2);
1374 <<
"The difference between " << expr1 <<
" and " << expr2
1375 <<
" is " << diff <<
", which exceeds " << abs_error_expr <<
", where\n" 1376 << expr1 <<
" evaluates to " << val1 <<
",\n" 1377 << expr2 <<
" evaluates to " << val2 <<
", and\n" 1378 << abs_error_expr <<
" evaluates to " << abs_error <<
".";
1383 template <
typename RawType>
1394 const FloatingPoint<RawType> lhs(val1),
rhs(val2);
1395 if (lhs.AlmostEquals(rhs)) {
1403 ::std::stringstream val1_ss;
1407 ::std::stringstream val2_ss;
1412 <<
"Expected: (" << expr1 <<
") <= (" << expr2 <<
")\n" 1421 AssertionResult
FloatLE(
const char* expr1,
const char* expr2,
1422 float val1,
float val2) {
1423 return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
1428 AssertionResult
DoubleLE(
const char* expr1,
const char* expr2,
1429 double val1,
double val2) {
1430 return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
1433 namespace internal {
1437 AssertionResult
CmpHelperEQ(
const char* lhs_expression,
1438 const char* rhs_expression,
1455 #define GTEST_IMPL_CMP_HELPER_(op_name, op)\ 1456 AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \ 1457 BiggestInt val1, BiggestInt val2) {\ 1458 if (val1 op val2) {\ 1459 return AssertionSuccess();\ 1461 return AssertionFailure() \ 1462 << "Expected: (" << expr1 << ") " #op " (" << expr2\ 1463 << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\ 1464 << " vs " << FormatForComparisonFailureMessage(val2, val1);\ 1484 #undef GTEST_IMPL_CMP_HELPER_ 1488 const char* rhs_expression,
1504 const char* rhs_expression,
1520 const char* s2_expression,
1527 << s2_expression <<
"), actual: \"" 1528 << s1 <<
"\" vs \"" << s2 <<
"\"";
1534 const char* s2_expression,
1541 <<
"Expected: (" << s1_expression <<
") != (" 1542 << s2_expression <<
") (ignoring case), actual: \"" 1543 << s1 <<
"\" vs \"" << s2 <<
"\"";
1557 bool IsSubstringPred(
const char*
needle,
const char* haystack) {
1558 if (needle == NULL || haystack == NULL)
1559 return needle == haystack;
1561 return strstr(haystack, needle) != NULL;
1564 bool IsSubstringPred(
const wchar_t* needle,
const wchar_t* haystack) {
1565 if (needle == NULL || haystack == NULL)
1566 return needle == haystack;
1568 return wcsstr(haystack, needle) != NULL;
1572 template <
typename StringType>
1573 bool IsSubstringPred(
const StringType& needle,
1574 const StringType& haystack) {
1575 return haystack.find(needle) != StringType::npos;
1582 template <
typename StringType>
1583 AssertionResult IsSubstringImpl(
1584 bool expected_to_be_substring,
1585 const char* needle_expr,
const char* haystack_expr,
1586 const StringType& needle,
const StringType& haystack) {
1587 if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
1590 const bool is_wide_string =
sizeof(needle[0]) > 1;
1591 const char*
const begin_string_quote = is_wide_string ?
"L\"" :
"\"";
1593 <<
"Value of: " << needle_expr <<
"\n" 1594 <<
" Actual: " << begin_string_quote << needle <<
"\"\n" 1595 <<
"Expected: " << (expected_to_be_substring ?
"" :
"not ")
1596 <<
"a substring of " << haystack_expr <<
"\n" 1597 <<
"Which is: " << begin_string_quote << haystack <<
"\"";
1607 const char* needle_expr,
const char* haystack_expr,
1608 const char*
needle,
const char* haystack) {
1609 return IsSubstringImpl(
true, needle_expr, haystack_expr, needle, haystack);
1613 const char* needle_expr,
const char* haystack_expr,
1614 const wchar_t* needle,
const wchar_t* haystack) {
1615 return IsSubstringImpl(
true, needle_expr, haystack_expr, needle, haystack);
1619 const char* needle_expr,
const char* haystack_expr,
1620 const char* needle,
const char* haystack) {
1621 return IsSubstringImpl(
false, needle_expr, haystack_expr, needle, haystack);
1625 const char* needle_expr,
const char* haystack_expr,
1626 const wchar_t* needle,
const wchar_t* haystack) {
1627 return IsSubstringImpl(
false, needle_expr, haystack_expr, needle, haystack);
1631 const char* needle_expr,
const char* haystack_expr,
1633 return IsSubstringImpl(
true, needle_expr, haystack_expr, needle, haystack);
1637 const char* needle_expr,
const char* haystack_expr,
1639 return IsSubstringImpl(
false, needle_expr, haystack_expr, needle, haystack);
1642 #if GTEST_HAS_STD_WSTRING 1644 const char* needle_expr,
const char* haystack_expr,
1646 return IsSubstringImpl(
true, needle_expr, haystack_expr, needle, haystack);
1650 const char* needle_expr,
const char* haystack_expr,
1652 return IsSubstringImpl(
false, needle_expr, haystack_expr, needle, haystack);
1654 #endif // GTEST_HAS_STD_WSTRING 1656 namespace internal {
1658 #if GTEST_OS_WINDOWS 1663 AssertionResult HRESULTFailureHelper(
const char* expr,
1664 const char* expected,
1666 # if GTEST_OS_WINDOWS_MOBILE 1669 const char error_text[] =
"";
1676 const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
1677 FORMAT_MESSAGE_IGNORE_INSERTS;
1678 const DWORD kBufSize = 4096;
1680 char error_text[kBufSize] = {
'\0' };
1681 DWORD message_length = ::FormatMessageA(kFlags,
1689 for (; message_length &&
IsSpace(error_text[message_length - 1]);
1691 error_text[message_length - 1] =
'\0';
1694 # endif // GTEST_OS_WINDOWS_MOBILE 1698 <<
"Expected: " << expr <<
" " << expected <<
".\n" 1699 <<
" Actual: " << error_hex <<
" " << error_text <<
"\n";
1704 AssertionResult IsHRESULTSuccess(
const char* expr,
long hr) {
1705 if (SUCCEEDED(hr)) {
1708 return HRESULTFailureHelper(expr,
"succeeds", hr);
1711 AssertionResult IsHRESULTFailure(
const char* expr,
long hr) {
1715 return HRESULTFailureHelper(expr,
"fails", hr);
1718 #endif // GTEST_OS_WINDOWS 1748 const UInt32 low_bits = *bits & ((
static_cast<UInt32>(1) << n) - 1);
1760 if (code_point > kMaxCodePoint4) {
1765 if (code_point <= kMaxCodePoint1) {
1767 str[0] =
static_cast<char>(code_point);
1768 }
else if (code_point <= kMaxCodePoint2) {
1770 str[1] =
static_cast<char>(0x80 |
ChopLowBits(&code_point, 6));
1771 str[0] =
static_cast<char>(0xC0 | code_point);
1772 }
else if (code_point <= kMaxCodePoint3) {
1774 str[2] =
static_cast<char>(0x80 |
ChopLowBits(&code_point, 6));
1775 str[1] =
static_cast<char>(0x80 |
ChopLowBits(&code_point, 6));
1776 str[0] =
static_cast<char>(0xE0 | code_point);
1779 str[3] =
static_cast<char>(0x80 |
ChopLowBits(&code_point, 6));
1780 str[2] =
static_cast<char>(0x80 |
ChopLowBits(&code_point, 6));
1781 str[1] =
static_cast<char>(0x80 |
ChopLowBits(&code_point, 6));
1782 str[0] =
static_cast<char>(0xF0 | code_point);
1795 return sizeof(wchar_t) == 2 &&
1796 (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;
1802 const UInt32 mask = (1 << 10) - 1;
1803 return (
sizeof(
wchar_t) == 2) ?
1804 (((first & mask) << 10) | (second & mask)) + 0x10000 :
1824 if (num_chars == -1)
1825 num_chars =
static_cast<int>(wcslen(str));
1827 ::std::stringstream
stream;
1828 for (
int i = 0;
i < num_chars; ++
i) {
1829 UInt32 unicode_code_point;
1831 if (str[
i] == L
'\0') {
1838 unicode_code_point =
static_cast<UInt32>(str[
i]);
1849 if (wide_c_str == NULL)
return "(null)";
1861 if (lhs == NULL)
return rhs == NULL;
1863 if (rhs == NULL)
return false;
1865 return wcscmp(lhs, rhs) == 0;
1870 const char* rhs_expression,
1872 const wchar_t* rhs) {
1886 const char* s2_expression,
1888 const wchar_t* s2) {
1894 << s2_expression <<
"), actual: " 1926 const wchar_t* rhs) {
1927 if (lhs == NULL)
return rhs == NULL;
1929 if (rhs == NULL)
return false;
1931 #if GTEST_OS_WINDOWS 1932 return _wcsicmp(lhs, rhs) == 0;
1933 #elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID 1934 return wcscasecmp(lhs, rhs) == 0;
1940 left = towlower(*lhs++);
1941 right = towlower(*rhs++);
1942 }
while (left && left == right);
1943 return left == right;
1944 #endif // OS selector 1951 const size_t str_len = str.length();
1952 const size_t suffix_len = suffix.length();
1953 return (str_len >= suffix_len) &&
1960 std::stringstream ss;
1961 ss << std::setfill(
'0') << std::setw(2) <<
value;
1967 std::stringstream ss;
1968 ss << std::hex << std::uppercase <<
value;
1974 std::stringstream ss;
1975 ss << std::setfill(
'0') << std::setw(2) << std::hex << std::uppercase
1976 <<
static_cast<unsigned int>(
value);
1984 const char*
const start = str.c_str();
1985 const char*
const end = start + str.length();
1988 result.reserve(2 * (end - start));
1989 for (
const char*
ch = start;
ch !=
end; ++
ch) {
2002 const Message& user_msg) {
2004 const std::string user_msg_string = user_msg.GetString();
2005 if (user_msg_string.empty()) {
2009 return gtest_msg +
"\n" + user_msg_string;
2018 : death_test_count_(0),
2030 if (i < 0 || i >= total_part_count())
2032 return test_part_results_.at(i);
2039 if (i < 0 || i >= test_property_count())
2041 return test_properties_.at(i);
2046 test_part_results_.clear();
2051 test_part_results_.push_back(test_part_result);
2058 const TestProperty& test_property) {
2059 if (!ValidateTestProperty(xml_element, test_property)) {
2063 const std::vector<TestProperty>::iterator property_with_matching_key =
2064 std::find_if(test_properties_.begin(), test_properties_.end(),
2065 internal::TestPropertyKeyIs(test_property.key()));
2066 if (property_with_matching_key == test_properties_.end()) {
2067 test_properties_.push_back(test_property);
2070 property_with_matching_key->SetValue(test_property.value());
2107 template <
int kSize>
2108 std::vector<std::string>
ArrayAsVector(
const char*
const (&array)[kSize]) {
2109 return std::vector<std::string>(array, array + kSize);
2114 if (xml_element ==
"testsuites") {
2116 }
else if (xml_element ==
"testsuite") {
2118 }
else if (xml_element ==
"testcase") {
2121 GTEST_CHECK_(
false) <<
"Unrecognized xml_element provided: " << xml_element;
2124 return std::vector<std::string>();
2129 for (
size_t i = 0; i < words.size(); ++
i) {
2130 if (i > 0 && words.size() > 2) {
2133 if (i == words.size() - 1) {
2134 word_list <<
"and ";
2136 word_list <<
"'" << words[
i] <<
"'";
2142 const std::vector<std::string>& reserved_names) {
2143 if (std::find(reserved_names.begin(), reserved_names.end(), property_name) !=
2144 reserved_names.end()) {
2145 ADD_FAILURE() <<
"Reserved key used in RecordProperty(): " << property_name
2163 test_part_results_.clear();
2164 test_properties_.clear();
2165 death_test_count_ = 0;
2171 for (
int i = 0; i < total_part_count(); ++
i) {
2172 if (GetTestPartResult(i).failed())
2201 return static_cast<int>(test_part_results_.size());
2206 return static_cast<int>(test_properties_.size());
2244 value_message <<
value;
2245 RecordProperty(key, value_message.
GetString().c_str());
2248 namespace internal {
2276 const char*
const first_test_name = first_test_info->
name();
2281 const char*
const this_test_name = this_test_info->
name();
2283 if (this_fixture_id != first_fixture_id) {
2289 if (first_is_TEST || this_is_TEST) {
2296 const char*
const TEST_name =
2297 first_is_TEST ? first_test_name : this_test_name;
2298 const char*
const TEST_F_name =
2299 first_is_TEST ? this_test_name : first_test_name;
2302 <<
"All tests in the same test case must use the same test fixture\n" 2303 <<
"class, so mixing TEST_F and TEST in the same test case is\n" 2306 <<
"test " << TEST_F_name <<
" is defined using TEST_F but\n" 2307 <<
"test " << TEST_name <<
" is defined using TEST. You probably\n" 2308 <<
"want to change the TEST to TEST_F or move it to another test\n" 2314 <<
"All tests in the same test case must use the same test fixture\n" 2315 <<
"class. However, in test case " 2317 <<
"you defined test " << first_test_name
2318 <<
" and test " << this_test_name <<
"\n" 2319 <<
"using two different test fixture classes. This can happen if\n" 2320 <<
"the two classes are from different namespaces or translation\n" 2321 <<
"units and have the same name. You should probably rename one\n" 2322 <<
"of the classes to put the tests into different test cases.";
2336 static std::string* FormatSehExceptionMessage(DWORD exception_code,
2337 const char* location) {
2339 message <<
"SEH exception with code 0x" << std::setbase(16) <<
2340 exception_code << std::setbase(10) <<
" thrown in " << location <<
".";
2345 #endif // GTEST_HAS_SEH 2347 namespace internal {
2349 #if GTEST_HAS_EXCEPTIONS 2353 const char* location) {
2355 if (description != NULL) {
2356 message <<
"C++ exception with description \"" << description <<
"\"";
2358 message <<
"Unknown C++ exception";
2360 message <<
" thrown in " << location <<
".";
2368 GoogleTestFailureException::GoogleTestFailureException(
2372 #endif // GTEST_HAS_EXCEPTIONS 2382 template <
class T,
typename Result>
2384 T*
object, Result (
T::*method)(),
const char* location) {
2387 return (object->*method)();
2388 } __except (internal::UnitTestOptions::GTestShouldProcessSEH(
2389 GetExceptionCode())) {
2393 std::string* exception_message = FormatSehExceptionMessage(
2394 GetExceptionCode(), location);
2396 *exception_message);
2397 delete exception_message;
2398 return static_cast<Result
>(0);
2402 return (object->*method)();
2403 #endif // GTEST_HAS_SEH 2409 template <
class T,
typename Result>
2411 T*
object, Result (
T::*method)(),
const char* location) {
2436 #if GTEST_HAS_EXCEPTIONS 2439 }
catch (
const internal::GoogleTestFailureException&) {
2444 }
catch (
const std::exception& e) {
2447 FormatCxxExceptionMessage(e.what(), location));
2451 FormatCxxExceptionMessage(NULL, location));
2453 return static_cast<Result
>(0);
2456 #endif // GTEST_HAS_EXCEPTIONS 2458 return (object->*method)();
2466 if (!HasSameFixtureClass())
return;
2472 if (!HasFatalFailure()) {
2494 HasNonfatalFailure();
2503 const char* a_type_param,
2504 const char* a_value_param,
2508 : test_case_name_(a_test_case_name),
2510 type_param_(a_type_param ?
new std::string(a_type_param) : NULL),
2511 value_param_(a_value_param ?
new std::string(a_value_param) : NULL),
2512 location_(a_code_location),
2513 fixture_class_id_(fixture_class_id),
2515 is_disabled_(
false),
2516 matches_filter_(
false),
2523 namespace internal {
2544 const char* test_case_name,
2546 const char* type_param,
2547 const char* value_param,
2548 CodeLocation code_location,
2552 TestFactoryBase* factory) {
2554 new TestInfo(test_case_name, name, type_param, value_param,
2555 code_location, fixture_class_id, factory);
2560 #if GTEST_HAS_PARAM_TEST 2561 void ReportInvalidTestCaseType(
const char* test_case_name,
2562 CodeLocation code_location) {
2565 <<
"Attempted redefinition of test case " << test_case_name <<
".\n" 2566 <<
"All tests in the same test case must use the same test fixture\n" 2567 <<
"class. However, in test case " << test_case_name <<
", you tried\n" 2568 <<
"to define a test using a fixture class different from the one\n" 2569 <<
"used earlier. This can happen if the two fixture classes are\n" 2570 <<
"from different namespaces and have the same name. You should\n" 2571 <<
"probably rename one of the classes to put the tests into different\n" 2574 fprintf(stderr,
"%s %s",
2576 code_location.line).c_str(),
2579 #endif // GTEST_HAS_PARAM_TEST 2598 explicit TestNameIs(
const char*
name)
2602 bool operator()(
const TestInfo * test_info)
const {
2603 return test_info && test_info->
name() ==
name_;
2612 namespace internal {
2618 #if GTEST_HAS_PARAM_TEST 2619 if (!parameterized_tests_registered_) {
2620 parameterized_test_registry_.RegisterTests();
2621 parameterized_tests_registered_ =
true;
2631 if (!should_run_)
return;
2635 impl->set_current_test_info(
this);
2644 impl->os_stack_trace_getter()->UponLeavingGTest();
2649 "the test fixture's constructor");
2660 impl->os_stack_trace_getter()->UponLeavingGTest();
2667 repeater->OnTestEnd(*
this);
2671 impl->set_current_test_info(NULL);
2678 return CountIf(test_info_list_, TestPassed);
2683 return CountIf(test_info_list_, TestFailed);
2688 return CountIf(test_info_list_, TestReportableDisabled);
2693 return CountIf(test_info_list_, TestDisabled);
2698 return CountIf(test_info_list_, TestReportable);
2703 return CountIf(test_info_list_, ShouldRunTest);
2708 return static_cast<int>(test_info_list_.size());
2724 type_param_(a_type_param ?
new std::string(a_type_param) : NULL),
2725 set_up_tc_(set_up_tc),
2726 tear_down_tc_(tear_down_tc),
2734 ForEach(test_info_list_, internal::Delete<TestInfo>);
2741 return index < 0 ? NULL : test_info_list_[index];
2748 return index < 0 ? NULL : test_info_list_[index];
2754 test_info_list_.push_back(test_info);
2755 test_indices_.push_back(static_cast<int>(test_indices_.size()));
2760 if (!should_run_)
return;
2763 impl->set_current_test_case(
this);
2768 impl->os_stack_trace_getter()->UponLeavingGTest();
2773 for (
int i = 0; i < total_test_count(); i++) {
2774 GetMutableTestInfo(i)->Run();
2778 impl->os_stack_trace_getter()->UponLeavingGTest();
2782 repeater->OnTestCaseEnd(*
this);
2783 impl->set_current_test_case(NULL);
2788 ad_hoc_test_result_.Clear();
2794 Shuffle(random, &test_indices_);
2799 for (
size_t i = 0; i < test_indices_.size(); i++) {
2800 test_indices_[
i] =
static_cast<int>(
i);
2810 const char * singular_form,
2811 const char * plural_form) {
2813 (count == 1 ? singular_form : plural_form);
2843 return "Unknown result type";
2847 namespace internal {
2856 << test_part_result.
message()).GetString();
2863 printf(
"%s\n", result.c_str());
2869 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE 2873 ::OutputDebugStringA(result.c_str());
2874 ::OutputDebugStringA(
"\n");
2887 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \ 2888 !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT 2895 case COLOR_YELLOW:
return FOREGROUND_RED | FOREGROUND_GREEN;
2908 case COLOR_YELLOW:
return "3";
2909 default:
return NULL;
2913 #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE 2917 const char*
const gtest_color =
GTEST_FLAG(color).c_str();
2920 #if GTEST_OS_WINDOWS 2923 return stdout_is_tty;
2927 const bool term_supports_color =
2939 return stdout_is_tty && term_supports_color;
2940 #endif // GTEST_OS_WINDOWS 2958 va_start(args, fmt);
2960 #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS || \ 2961 GTEST_OS_IOS || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT 2964 static const bool in_color_mode =
2966 const bool use_color = in_color_mode && (color !=
COLOR_DEFAULT);
2967 #endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS 2976 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \ 2977 !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT 2978 const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
2981 CONSOLE_SCREEN_BUFFER_INFO buffer_info;
2982 GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
2983 const WORD old_color_attrs = buffer_info.wAttributes;
2989 SetConsoleTextAttribute(stdout_handle,
2990 GetColorAttribute(color) | FOREGROUND_INTENSITY);
2995 SetConsoleTextAttribute(stdout_handle, old_color_attrs);
3000 #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE 3010 const char*
const type_param = test_info.
type_param();
3011 const char*
const value_param = test_info.
value_param();
3013 if (type_param != NULL || value_param != NULL) {
3015 if (type_param != NULL) {
3016 printf(
"%s = %s", kTypeParamLabel, type_param);
3017 if (value_param != NULL)
3020 if (value_param != NULL) {
3021 printf(
"%s = %s", kValueParamLabel, value_param);
3033 printf(
"%s.%s", test_case, test);
3038 virtual void OnTestIterationStart(
const UnitTest& unit_test,
int iteration);
3039 virtual void OnEnvironmentsSetUpStart(
const UnitTest& unit_test);
3041 virtual void OnTestCaseStart(
const TestCase& test_case);
3042 virtual void OnTestStart(
const TestInfo& test_info);
3044 virtual void OnTestEnd(
const TestInfo& test_info);
3045 virtual void OnTestCaseEnd(
const TestCase& test_case);
3046 virtual void OnEnvironmentsTearDownStart(
const UnitTest& unit_test);
3048 virtual void OnTestIterationEnd(
const UnitTest& unit_test,
int iteration);
3052 static void PrintFailedTests(
const UnitTest& unit_test);
3057 const UnitTest& unit_test,
int iteration) {
3059 printf(
"\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
3073 "Note: This is test shard %d of %s.\n",
3074 static_cast<int>(shard_index) + 1,
3080 "Note: Randomizing tests' orders with a seed of %d .\n",
3085 printf(
"Running %s from %s.\n",
3094 printf(
"Global test environment set-up.\n");
3102 printf(
"%s from %s", counts.c_str(), test_case.
name());
3106 printf(
", where %s = %s\n", kTypeParamLabel, test_case.
type_param());
3155 printf(
"%s from %s (%s ms total)\n\n",
3156 counts.c_str(), test_case.
name(),
3164 printf(
"Global test environment tear-down\n");
3171 if (failed_test_count == 0) {
3186 printf(
"%s.%s", test_case.
name(), test_info.
name());
3196 printf(
"%s from %s ran.",
3200 printf(
" (%s ms total)",
3208 if (!unit_test.
Passed()) {
3211 printf(
"%s, listed below:\n",
FormatTestCount(failed_test_count).c_str());
3212 PrintFailedTests(unit_test);
3213 printf(
"\n%2d FAILED %s\n", num_failures,
3214 num_failures == 1 ?
"TEST" :
"TESTS");
3218 if (num_disabled && !
GTEST_FLAG(also_run_disabled_tests)) {
3219 if (!num_failures) {
3223 " YOU HAVE %d DISABLED %s\n\n",
3225 num_disabled == 1 ?
"TEST" :
"TESTS");
3248 virtual void OnTestProgramStart(
const UnitTest& unit_test);
3249 virtual void OnTestIterationStart(
const UnitTest& unit_test,
int iteration);
3250 virtual void OnEnvironmentsSetUpStart(
const UnitTest& unit_test);
3251 virtual void OnEnvironmentsSetUpEnd(
const UnitTest& unit_test);
3252 virtual void OnTestCaseStart(
const TestCase& test_case);
3253 virtual void OnTestStart(
const TestInfo& test_info);
3255 virtual void OnTestEnd(
const TestInfo& test_info);
3256 virtual void OnTestCaseEnd(
const TestCase& test_case);
3257 virtual void OnEnvironmentsTearDownStart(
const UnitTest& unit_test);
3258 virtual void OnEnvironmentsTearDownEnd(
const UnitTest& unit_test);
3259 virtual void OnTestIterationEnd(
const UnitTest& unit_test,
int iteration);
3260 virtual void OnTestProgramEnd(
const UnitTest& unit_test);
3265 bool forwarding_enabled_;
3267 std::vector<TestEventListener*> listeners_;
3277 listeners_.push_back(listener);
3282 for (
size_t i = 0; i < listeners_.size(); ++
i) {
3283 if (listeners_[i] == listener) {
3284 listeners_.erase(listeners_.begin() +
i);
3294 #define GTEST_REPEATER_METHOD_(Name, Type) \ 3295 void TestEventRepeater::Name(const Type& parameter) { \ 3296 if (forwarding_enabled_) { \ 3297 for (size_t i = 0; i < listeners_.size(); i++) { \ 3298 listeners_[i]->Name(parameter); \ 3304 #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \ 3305 void TestEventRepeater::Name(const Type& parameter) { \ 3306 if (forwarding_enabled_) { \ 3307 for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \ 3308 listeners_[i]->Name(parameter); \ 3325 #undef GTEST_REPEATER_METHOD_ 3326 #undef GTEST_REVERSE_REPEATER_METHOD_ 3330 if (forwarding_enabled_) {
3331 for (
size_t i = 0; i < listeners_.size(); i++) {
3332 listeners_[
i]->OnTestIterationStart(unit_test, iteration);
3339 if (forwarding_enabled_) {
3340 for (
int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) {
3341 listeners_[
i]->OnTestIterationEnd(unit_test, iteration);
3349 class XmlUnitTestResultPrinter :
public EmptyTestEventListener {
3351 explicit XmlUnitTestResultPrinter(
const char* output_file);
3353 virtual void OnTestIterationEnd(
const UnitTest& unit_test,
int iteration);
3359 return c == 0x9 || c == 0xA || c == 0xD;
3364 return IsNormalizableWhitespace(c) || c >= 0x20;
3378 return EscapeXml(str,
true);
3383 return EscapeXml(str,
false);
3388 static void OutputXmlAttribute(std::ostream*
stream,
3394 static void OutputXmlCDataSection(::std::ostream* stream,
const char*
data);
3397 static void OutputXmlTestInfo(::std::ostream* stream,
3398 const char* test_case_name,
3402 static void PrintXmlTestCase(::std::ostream* stream,
3406 static void PrintXmlUnitTest(::std::ostream* stream,
3423 : output_file_(output_file) {
3424 if (output_file_.c_str() == NULL || output_file_.empty()) {
3425 fprintf(stderr,
"XML output file may not be null\n");
3434 FILE* xmlout = NULL;
3435 FilePath output_file(output_file_);
3438 if (
output_dir.CreateDirectoriesRecursively()) {
3441 if (xmlout == NULL) {
3453 "Unable to open file \"%s\"\n",
3454 output_file_.c_str());
3458 std::stringstream
stream;
3459 PrintXmlUnitTest(&stream, unit_test);
3480 for (
size_t i = 0; i < str.size(); ++
i) {
3481 const char ch = str[
i];
3505 if (IsValidXmlCharacter(ch)) {
3506 if (is_attribute && IsNormalizableWhitespace(ch))
3525 output.reserve(str.size());
3526 for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
3527 if (IsValidXmlCharacter(*it))
3528 output.push_back(*it);
3551 ::std::stringstream ss;
3552 ss << (static_cast<double>(ms) * 1e-3);
3557 #if defined(_MSC_VER) 3558 return localtime_s(out, &seconds) == 0;
3559 #elif defined(__MINGW32__) || defined(__MINGW64__) 3562 struct tm* tm_ptr = localtime(&seconds);
3568 return localtime_r(&seconds, out) != NULL;
3575 struct tm time_struct;
3590 const char* segment =
data;
3591 *stream <<
"<![CDATA[";
3593 const char*
const next_segment = strstr(segment,
"]]>");
3594 if (next_segment != NULL) {
3596 segment, static_cast<std::streamsize>(next_segment - segment));
3597 *stream <<
"]]>]]><![CDATA[";
3598 segment = next_segment + strlen(
"]]>");
3608 std::ostream* stream,
3612 const std::vector<std::string>& allowed_names =
3615 GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(),
name) !=
3616 allowed_names.end())
3617 <<
"Attribute " << name <<
" is not allowed for element <" << element_name
3620 *stream <<
" " << name <<
"=\"" << EscapeXmlAttribute(value) <<
"\"";
3626 const char* test_case_name,
3631 *stream <<
" <testcase";
3632 OutputXmlAttribute(stream, kTestcase,
"name", test_info.
name());
3635 OutputXmlAttribute(stream, kTestcase,
"value_param",
3639 OutputXmlAttribute(stream, kTestcase,
"type_param", test_info.
type_param());
3642 OutputXmlAttribute(stream, kTestcase,
"status",
3644 OutputXmlAttribute(stream, kTestcase,
"time",
3646 OutputXmlAttribute(stream, kTestcase,
"classname", test_case_name);
3647 *stream << TestPropertiesAsXmlAttributes(result);
3653 if (++failures == 1) {
3658 const string summary = location +
"\n" + part.
summary();
3659 *stream <<
" <failure message=\"" 3660 << EscapeXmlAttribute(summary.c_str())
3663 OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
3664 *stream <<
"</failure>\n";
3671 *stream <<
" </testcase>\n";
3678 *stream <<
" <" << kTestsuite;
3679 OutputXmlAttribute(stream, kTestsuite,
"name", test_case.
name());
3680 OutputXmlAttribute(stream, kTestsuite,
"tests",
3682 OutputXmlAttribute(stream, kTestsuite,
"failures",
3685 stream, kTestsuite,
"disabled",
3687 OutputXmlAttribute(stream, kTestsuite,
"errors",
"0");
3688 OutputXmlAttribute(stream, kTestsuite,
"time",
3695 OutputXmlTestInfo(stream, test_case.
name(), *test_case.
GetTestInfo(i));
3697 *stream <<
" </" << kTestsuite <<
">\n";
3705 *stream <<
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
3706 *stream <<
"<" << kTestsuites;
3708 OutputXmlAttribute(stream, kTestsuites,
"tests",
3710 OutputXmlAttribute(stream, kTestsuites,
"failures",
3713 stream, kTestsuites,
"disabled",
3715 OutputXmlAttribute(stream, kTestsuites,
"errors",
"0");
3717 stream, kTestsuites,
"timestamp",
3719 OutputXmlAttribute(stream, kTestsuites,
"time",
3723 OutputXmlAttribute(stream, kTestsuites,
"random_seed",
3729 OutputXmlAttribute(stream, kTestsuites,
"name",
"AllTests");
3734 PrintXmlTestCase(stream, *unit_test.
GetTestCase(i));
3736 *stream <<
"</" << kTestsuites <<
">\n";
3746 attributes <<
" " <<
property.key() <<
"=" 3747 <<
"\"" << EscapeXmlAttribute(property.value()) <<
"\"";
3754 #if GTEST_CAN_STREAM_RESULTS_ 3761 string StreamingListener::UrlEncode(
const char* str) {
3763 result.reserve(strlen(str) + 1);
3764 for (
char ch = *str;
ch !=
'\0';
ch = *++str) {
3773 result.push_back(
ch);
3780 void StreamingListener::SocketWriter::MakeConnection() {
3782 <<
"MakeConnection() can't be called when there is already a connection.";
3785 memset(&hints, 0,
sizeof(hints));
3786 hints.ai_family = AF_UNSPEC;
3787 hints.ai_socktype = SOCK_STREAM;
3788 addrinfo* servinfo = NULL;
3792 const int error_num = getaddrinfo(
3793 host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
3794 if (error_num != 0) {
3795 GTEST_LOG_(WARNING) <<
"stream_result_to: getaddrinfo() failed: " 3796 << gai_strerror(error_num);
3800 for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != NULL;
3801 cur_addr = cur_addr->ai_next) {
3803 cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol);
3804 if (sockfd_ != -1) {
3806 if (
connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
3813 freeaddrinfo(servinfo);
3815 if (sockfd_ == -1) {
3816 GTEST_LOG_(WARNING) <<
"stream_result_to: failed to connect to " 3817 << host_name_ <<
":" << port_num_;
3822 #endif // GTEST_CAN_STREAM_RESULTS__ 3862 : premature_exit_filepath_(premature_exit_filepath) {
3864 if (premature_exit_filepath != NULL && *premature_exit_filepath !=
'\0') {
3869 fwrite(
"0", 1, 1, pfile);
3875 if (premature_exit_filepath_ != NULL && *premature_exit_filepath_ !=
'\0') {
3876 remove(premature_exit_filepath_);
3881 const char*
const premature_exit_filepath_;
3892 default_result_printer_(NULL),
3893 default_xml_generator_(NULL) {
3903 repeater_->Append(listener);
3910 if (listener == default_result_printer_)
3911 default_result_printer_ = NULL;
3912 else if (listener == default_xml_generator_)
3913 default_xml_generator_ = NULL;
3914 return repeater_->Release(listener);
3927 if (default_result_printer_ != listener) {
3930 delete Release(default_result_printer_);
3931 default_result_printer_ = listener;
3932 if (listener != NULL)
3943 if (default_xml_generator_ != listener) {
3946 delete Release(default_xml_generator_);
3947 default_xml_generator_ = listener;
3948 if (listener != NULL)
3956 return repeater_->forwarding_enabled();
3960 repeater_->set_forwarding_enabled(
false);
3984 #if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__) 3990 #endif // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__) 3995 return impl()->successful_test_case_count();
4000 return impl()->failed_test_case_count();
4005 return impl()->total_test_case_count();
4011 return impl()->test_case_to_run_count();
4016 return impl()->successful_test_count();
4024 return impl()->reportable_disabled_test_count();
4029 return impl()->disabled_test_count();
4034 return impl()->reportable_test_count();
4046 return impl()->start_timestamp();
4051 return impl()->elapsed_time();
4064 return impl()->GetTestCase(i);
4070 return *impl()->ad_hoc_test_result();
4076 return impl()->GetMutableTestCase(i);
4082 return *impl()->listeners();
4100 impl_->environments().push_back(env);
4110 const char* file_name,
4118 if (impl_->gtest_trace_stack().size() > 0) {
4121 for (
int i = static_cast<int>(impl_->gtest_trace_stack().size());
4129 if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) {
4136 impl_->GetTestPartResultReporterForCurrentThread()->
4137 ReportTestPartResult(result);
4146 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT 4156 *
static_cast<volatile int*
>(NULL) = 1;
4157 #endif // GTEST_OS_WINDOWS 4159 #if GTEST_HAS_EXCEPTIONS 4160 throw internal::GoogleTestFailureException(result);
4186 const bool in_death_test_child_process =
4211 in_death_test_child_process ?
4216 impl()->set_catch_exceptions(
GTEST_FLAG(catch_exceptions));
4223 if (impl()->catch_exceptions() || in_death_test_child_process) {
4224 # if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT 4226 SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
4227 SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
4228 # endif // !GTEST_OS_WINDOWS_MOBILE 4230 # if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE 4234 _set_error_mode(_OUT_TO_STDERR);
4237 # if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE 4250 _set_abort_behavior(
4252 _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
4255 #endif // GTEST_HAS_SEH 4260 "auxiliary test code (environments or event listeners)") ? 0 : 1;
4266 return impl_->original_working_dir_.c_str();
4274 return impl_->current_test_case();
4282 return impl_->current_test_info();
4288 #if GTEST_HAS_PARAM_TEST 4291 internal::ParameterizedTestCaseRegistry&
4292 UnitTest::parameterized_test_registry()
4294 return impl_->parameterized_test_registry();
4296 #endif // GTEST_HAS_PARAM_TEST 4313 impl_->gtest_trace_stack().push_back(trace);
4320 impl_->gtest_trace_stack().pop_back();
4323 namespace internal {
4328 default_global_test_part_result_reporter_(
this),
4329 default_per_thread_test_part_result_reporter_(
this),
4331 global_test_part_result_repoter_(
4332 &default_global_test_part_result_reporter_),
4333 per_thread_test_part_result_reporter_(
4334 &default_per_thread_test_part_result_reporter_),
4335 #if GTEST_HAS_PARAM_TEST 4336 parameterized_test_registry_(),
4337 parameterized_tests_registered_(
false),
4338 #endif // GTEST_HAS_PARAM_TEST 4339 last_death_test_case_(-1),
4340 current_test_case_(NULL),
4341 current_test_info_(NULL),
4342 ad_hoc_test_result_(),
4343 os_stack_trace_getter_(NULL),
4344 post_flag_parse_init_performed_(
false),
4347 start_timestamp_(0),
4349 #if GTEST_HAS_DEATH_TEST 4350 death_test_factory_(
new DefaultDeathTestFactory),
4353 catch_exceptions_(
false) {
4359 ForEach(test_cases_, internal::Delete<TestCase>);
4362 ForEach(environments_, internal::Delete<Environment>);
4364 delete os_stack_trace_getter_;
4376 if (current_test_info_ != NULL) {
4377 xml_element =
"testcase";
4378 test_result = &(current_test_info_->result_);
4379 }
else if (current_test_case_ != NULL) {
4380 xml_element =
"testsuite";
4381 test_result = &(current_test_case_->ad_hoc_test_result_);
4383 xml_element =
"testsuites";
4384 test_result = &ad_hoc_test_result_;
4389 #if GTEST_HAS_DEATH_TEST 4392 void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
4393 if (internal_run_death_test_flag_.get() != NULL)
4394 listeners()->SuppressEventForwarding();
4396 #endif // GTEST_HAS_DEATH_TEST 4402 if (output_format ==
"xml") {
4405 }
else if (output_format !=
"") {
4406 printf(
"WARNING: unrecognized output format \"%s\" ignored.\n",
4407 output_format.c_str());
4412 #if GTEST_CAN_STREAM_RESULTS_ 4415 void UnitTestImpl::ConfigureStreamingOutput() {
4417 if (!target.empty()) {
4418 const size_t pos = target.find(
':');
4419 if (pos != std::string::npos) {
4420 listeners()->Append(
new StreamingListener(target.substr(0, pos),
4421 target.substr(pos+1)));
4423 printf(
"WARNING: unrecognized streaming target \"%s\" ignored.\n",
4429 #endif // GTEST_CAN_STREAM_RESULTS_ 4438 if (!post_flag_parse_init_performed_) {
4439 post_flag_parse_init_performed_ =
true;
4441 #if defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_) 4443 listeners()->Append(
new GTEST_CUSTOM_TEST_EVENT_LISTENER_());
4444 #endif // defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_) 4446 #if GTEST_HAS_DEATH_TEST 4447 InitDeathTestSubprocessControlInfo();
4448 SuppressTestEventsIfInSubprocess();
4449 #endif // GTEST_HAS_DEATH_TEST 4454 RegisterParameterizedTests();
4458 ConfigureXmlOutput();
4460 #if GTEST_CAN_STREAM_RESULTS_ 4462 ConfigureStreamingOutput();
4463 #endif // GTEST_CAN_STREAM_RESULTS_ 4483 return test_case != NULL && strcmp(test_case->
name(),
name_.c_str()) == 0;
4503 const char* type_param,
4507 const std::vector<TestCase*>::const_iterator test_case =
4508 std::find_if(test_cases_.begin(), test_cases_.end(),
4511 if (test_case != test_cases_.end())
4516 new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc);
4520 kDeathTestCaseFilter)) {
4525 ++last_death_test_case_;
4526 test_cases_.insert(test_cases_.begin() + last_death_test_case_,
4530 test_cases_.push_back(new_test_case);
4533 test_case_indices_.push_back(static_cast<int>(test_case_indices_.size()));
4534 return new_test_case;
4555 "\nThis test program did NOT call ::testing::InitGoogleTest " 4556 "before calling RUN_ALL_TESTS(). Please fix it.\n");
4566 PostFlagParsingInit();
4575 bool in_subprocess_for_death_test =
false;
4577 #if GTEST_HAS_DEATH_TEST 4578 in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL);
4579 # if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_) 4580 if (in_subprocess_for_death_test) {
4581 GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_();
4583 # endif // defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_) 4584 #endif // GTEST_HAS_DEATH_TEST 4586 const bool should_shard =
ShouldShard(kTestTotalShards, kTestShardIndex,
4587 in_subprocess_for_death_test);
4591 const bool has_tests_to_run = FilterTests(should_shard
4592 ? HONOR_SHARDING_PROTOCOL
4593 : IGNORE_SHARDING_PROTOCOL) > 0;
4598 ListTestsMatchingFilter();
4617 const bool forever = repeat < 0;
4618 for (
int i = 0; forever || i !=
repeat; i++) {
4621 ClearNonAdHocTestResult();
4626 if (has_tests_to_run &&
GTEST_FLAG(shuffle)) {
4627 random()->Reseed(random_seed_);
4638 if (has_tests_to_run) {
4647 for (
int test_index = 0; test_index < total_test_case_count();
4649 GetMutableTestCase(test_index)->Run();
4694 const char*
const test_shard_file =
posix::GetEnv(kTestShardStatusFile);
4695 if (test_shard_file != NULL) {
4699 "Could not write to the test shard status file \"%s\" " 4700 "specified by the %s environment variable.\n",
4701 test_shard_file, kTestShardStatusFile);
4716 const char* shard_index_env,
4717 bool in_subprocess_for_death_test) {
4718 if (in_subprocess_for_death_test) {
4725 if (total_shards == -1 && shard_index == -1) {
4727 }
else if (total_shards == -1 && shard_index != -1) {
4729 <<
"Invalid environment variables: you have " 4730 << kTestShardIndex <<
" = " << shard_index
4731 <<
", but have left " << kTestTotalShards <<
" unset.\n";
4735 }
else if (total_shards != -1 && shard_index == -1) {
4737 <<
"Invalid environment variables: you have " 4738 << kTestTotalShards <<
" = " << total_shards
4739 <<
", but have left " << kTestShardIndex <<
" unset.\n";
4743 }
else if (shard_index < 0 || shard_index >= total_shards) {
4745 <<
"Invalid environment variables: we require 0 <= " 4746 << kTestShardIndex <<
" < " << kTestTotalShards
4747 <<
", but you have " << kTestShardIndex <<
"=" << shard_index
4748 <<
", " << kTestTotalShards <<
"=" << total_shards <<
".\n";
4754 return total_shards > 1;
4762 if (str_val == NULL) {
4768 str_val, &result)) {
4779 return (test_id % total_shards) == shard_index;
4790 const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?
4792 const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?
4799 int num_runnable_tests = 0;
4800 int num_selected_tests = 0;
4801 for (
size_t i = 0; i < test_cases_.size(); i++) {
4802 TestCase*
const test_case = test_cases_[
i];
4806 for (
size_t j = 0; j < test_case->
test_info_list().size(); j++) {
4811 const bool is_disabled =
4813 kDisableTestFilter) ||
4815 kDisableTestFilter);
4818 const bool matches_filter =
4823 const bool is_runnable =
4824 (
GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
4827 const bool is_selected = is_runnable &&
4828 (shard_tests == IGNORE_SHARDING_PROTOCOL ||
4830 num_runnable_tests));
4832 num_runnable_tests += is_runnable;
4833 num_selected_tests += is_selected;
4839 return num_selected_tests;
4848 for (
int i = 0; *str !=
'\0'; ++str) {
4849 if (i >= max_length) {
4867 const int kMaxParamLength = 250;
4869 for (
size_t i = 0; i < test_cases_.size(); i++) {
4870 const TestCase*
const test_case = test_cases_[
i];
4871 bool printed_test_case_name =
false;
4873 for (
size_t j = 0; j < test_case->
test_info_list().size(); j++) {
4877 if (!printed_test_case_name) {
4878 printed_test_case_name =
true;
4879 printf(
"%s.", test_case->
name());
4881 printf(
" # %s = ", kTypeParamLabel);
4888 printf(
" %s", test_info->
name());
4890 printf(
" # %s = ", kValueParamLabel);
4909 if (os_stack_trace_getter_ != getter) {
4910 delete os_stack_trace_getter_;
4911 os_stack_trace_getter_ = getter;
4919 if (os_stack_trace_getter_ == NULL) {
4920 #ifdef GTEST_OS_STACK_TRACE_GETTER_ 4921 os_stack_trace_getter_ =
new GTEST_OS_STACK_TRACE_GETTER_;
4924 #endif // GTEST_OS_STACK_TRACE_GETTER_ 4927 return os_stack_trace_getter_;
4933 return current_test_info_ ?
4934 &(current_test_info_->result_) : &ad_hoc_test_result_;
4945 static_cast<int>(test_cases_.size()), &test_case_indices_);
4948 for (
size_t i = 0; i < test_cases_.size(); i++) {
4949 test_cases_[
i]->ShuffleTests(
random());
4955 for (
size_t i = 0; i < test_cases_.size(); i++) {
4957 test_cases_[
i]->UnshuffleTests();
4959 test_case_indices_[
i] =
static_cast<int>(
i);
4983 class ClassUniqueToAlwaysTrue {};
4986 bool IsTrue(
bool condition) {
return condition; }
4989 #if GTEST_HAS_EXCEPTIONS 4993 throw ClassUniqueToAlwaysTrue();
4994 #endif // GTEST_HAS_EXCEPTIONS 5002 const size_t prefix_len = strlen(prefix);
5003 if (strncmp(*pstr, prefix, prefix_len) == 0) {
5004 *pstr += prefix_len;
5017 bool def_optional) {
5019 if (str == NULL || flag == NULL)
return NULL;
5023 const size_t flag_len = flag_str.length();
5024 if (strncmp(str, flag_str.c_str(), flag_len) != 0)
return NULL;
5027 const char* flag_end = str + flag_len;
5030 if (def_optional && (flag_end[0] ==
'\0')) {
5037 if (flag_end[0] !=
'=')
return NULL;
5040 return flag_end + 1;
5053 bool ParseBoolFlag(
const char* str,
const char* flag,
bool* value) {
5058 if (value_str == NULL)
return false;
5061 *value = !(*value_str ==
'0' || *value_str ==
'f' || *value_str ==
'F');
5075 if (value_str == NULL)
return false;
5092 if (value_str == NULL)
return false;
5133 const char* p = strchr(str,
'@');
5141 const char ch = p[1];
5145 }
else if (ch ==
'D') {
5147 }
else if (ch ==
'R') {
5149 }
else if (ch ==
'G') {
5151 }
else if (ch ==
'Y') {
5160 "This program contains tests written using " GTEST_NAME_ ". You can use the\n" 5161 "following command line flags to control its behavior:\n" 5165 " List the names of all tests instead of running them. The name of\n" 5166 " TEST(Foo, Bar) is \"Foo.Bar\".\n" 5168 "[@G-@YNEGATIVE_PATTERNS]@D\n" 5169 " Run only the tests whose name matches one of the positive patterns but\n" 5170 " none of the negative patterns. '?' matches any single character; '*'\n" 5171 " matches any substring; ':' separates two patterns.\n" 5173 " Run all disabled tests too.\n" 5177 " Run the tests repeatedly; use a negative count to repeat forever.\n" 5179 " Randomize tests' orders on every iteration.\n" 5181 " Random number seed to use for shuffling test orders (between 1 and\n" 5182 " 99999, or 0 to use a seed based on the current time).\n" 5186 " Enable/disable colored output. The default is @Gauto@D.\n" 5188 " Don't print the elapsed time of each test.\n" 5191 " Generate an XML report in the given directory or with the given file\n" 5192 " name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n" 5193 #if GTEST_CAN_STREAM_RESULTS_ 5195 " Stream test results to the given server.\n" 5196 #endif // GTEST_CAN_STREAM_RESULTS_ 5198 "Assertion Behavior:\n" 5199 #if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS 5201 " Set the default death test style.\n" 5202 #endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS 5204 " Turn assertion failures into debugger break-points.\n" 5206 " Turn assertion failures into C++ exceptions.\n" 5208 " Do not report exceptions as test failures. Instead, allow them\n" 5209 " to crash the program or throw a pop-up (on Windows).\n" 5212 "the corresponding\n" 5213 "environment variable of a flag (all letters in upper-case). For example, to\n" 5215 "color=no@D or set\n" 5218 "For more information, please read the " GTEST_NAME_ " documentation at\n" 5220 "(not one in your own code or tests), please report it to\n" 5252 #if GTEST_USE_OWN_FLAGFILE_FLAG_ 5257 "Unable to open file \"%s\"\n",
5264 std::vector<std::string>
lines;
5266 for (
size_t i = 0; i < lines.size(); ++
i) {
5267 if (lines[i].
empty())
5273 #endif // GTEST_USE_OWN_FLAGFILE_FLAG_ 5278 template <
typename CharType>
5280 for (
int i = 1; i < *argc; i++) {
5282 const char*
const arg = arg_string.c_str();
5288 bool remove_flag =
false;
5291 #if GTEST_USE_OWN_FLAGFILE_FLAG_ 5295 #endif // GTEST_USE_OWN_FLAGFILE_FLAG_ 5296 }
else if (arg_string ==
"--help" || arg_string ==
"-h" ||
5297 arg_string ==
"-?" || arg_string ==
"/?" ||
5309 for (
int j = i; j != *argc; j++) {
5310 argv[j] = argv[j + 1];
5343 template <
typename CharType>
5348 if (*argc <= 0)
return;
5351 for (
int i = 0; i != *argc; i++) {
5371 #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) 5372 GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
5373 #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) 5375 #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) 5381 #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) 5382 GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
5383 #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) 5385 #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) const char kDeathTestUseFork[]
GTEST_API_ bool g_help_flag
std::string StringFromGTestEnv(const char *flag, const char *default_val)
int failed_test_count() const
void SetDefaultResultPrinter(TestEventListener *listener)
TestPartResultReporterInterface * GetTestPartResultReporterForCurrentThread()
#define GTEST_FLAG_PREFIX_
class UnitTestImpl * GetUnitTestImpl()
internal::SetUpTestCaseFunc SetUpTestCaseFunc
const char * type_param() const
Int32 Int32FromGTestEnv(const char *flag, Int32 default_val)
~ScopedPrematureExitFile()
bool IsTrue(bool condition)
void RecordProperty(const std::string &xml_element, const TestProperty &test_property)
const char * original_working_dir() const
bool fatally_failed() const
void ReportFailureInUnknownLocation(TestPartResult::Type result_type, const std::string &message)
int disabled_test_count() const
int GetRandomSeedFromFlag(Int32 random_seed_flag)
ScopedPrematureExitFile(const char *premature_exit_filepath)
Result HandleExceptionsInMethodIfSupported(T *object, Result(T::*method)(), const char *location)
GTEST_DEFINE_int32_(random_seed, internal::Int32FromGTestEnv("random_seed", 0),"Random number seed to use when shuffling test orders. Must be in range ""[1, 99999], or 0 to use a seed based on the current time.")
static bool HasFatalFailure()
Integral2 random(Integral1 low, Integral2 up)
int successful_test_count() const
virtual void OnTestIterationStart(const UnitTest &unit_test, int iteration)
int reportable_disabled_test_count() const
TimeInMillis elapsed_time() const
static bool HasGoogleTestFlagPrefix(const char *str)
static int SumOverTestCaseList(const std::vector< TestCase * > &case_list, int(TestCase::*method)() const)
void(* TearDownTestCaseFunc)()
const char * summary() const
std::atomic< int64_t > sum(0)
GTEST_API_ std::string GetCurrentOsStackTraceExceptTop(UnitTest *unit_test, int skip_count)
GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms)
static const char kDisableTestFilter[]
E GetElementOr(const std::vector< E > &v, int i, E default_value)
int connect(NetworkSocket s, const sockaddr *name, socklen_t namelen)
int failed_test_count() const
virtual void OnEnvironmentsSetUpStart(const UnitTest &unit_test)
GTEST_API_ AssertionResult AssertionFailure()
const char kAlsoRunDisabledTestsFlag[]
UInt32 ChopLowBits(UInt32 *bits, int n)
PUSHMI_INLINE_VAR constexpr detail::filter_fn filter
virtual void OnEnvironmentsTearDownStart(const UnitTest &unit_test)=0
virtual void ReportTestPartResult(const TestPartResult &result)
const TestInfo * GetTestInfo(int i) const
static FilePath ConcatPaths(const FilePath &directory, const FilePath &relative_path)
const ::std::vector< testing::internal::string > & GetArgvs()
static const char * TestPartResultTypeToString(TestPartResult::Type type)
static std::string EscapeXmlAttribute(const std::string &str)
static std::string EscapeXml(const std::string &str, bool is_attribute)
GTEST_API_ std::vector< EditType > CalculateOptimalEdits(const std::vector< size_t > &left, const std::vector< size_t > &right)
const char kListTestsFlag[]
void PrintFullTestCommentIfPresent(const TestInfo &test_info)
TestPartResultReporterInterface * GetGlobalTestPartResultReporter()
AssertionResult CmpHelperEQ(const char *lhs_expression, const char *rhs_expression, const T1 &lhs, const T2 &rhs)
SingleFailureChecker(const TestPartResultArray *results, TestPartResult::Type type, const string &substr)
#define GTEST_FLAG_PREFIX_DASH_
void RegisterParameterizedTests()
GTEST_API_ TestInfo * MakeAndRegisterTestInfo(const char *test_case_name, const char *name, const char *type_param, const char *value_param, CodeLocation code_location, TypeId fixture_class_id, SetUpTestCaseFunc set_up_tc, TearDownTestCaseFunc tear_down_tc, TestFactoryBase *factory)
::std::string PrintToString(const T &value)
const char kStreamResultToFlag[]
TypeWithSize< 4 >::Int Int32
static bool IsNormalizableWhitespace(char c)
FILE * FOpen(const char *path, const char *mode)
TestCase(const char *name, const char *a_type_param, Test::SetUpTestCaseFunc set_up_tc, Test::TearDownTestCaseFunc tear_down_tc)
GTEST_API_ AssertionResult CmpHelperSTRCASEEQ(const char *s1_expression, const char *s2_expression, const char *s1, const char *s2)
const char * message() const
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
StreamCodecFactory stream
#define GTEST_LOG_(severity)
::std::string FormatFileLocation(const char *file, int line)
static bool EndsWithCaseInsensitive(const std::string &str, const std::string &suffix)
virtual void ReportTestPartResult(const TestPartResult &result)
GTEST_API_ bool ShouldUseColor(bool stdout_is_tty)
static void PrintXmlTestCase(::std::ostream *stream, const TestCase &test_case)
ScopedFakeTestPartResultReporter(TestPartResultArray *result)
GTEST_API_ AssertionResult CmpHelperSTRCASENE(const char *s1_expression, const char *s2_expression, const char *s1, const char *s2)
TypeWithSize< 4 >::UInt UInt32
TestEventListener * Release(TestEventListener *listener)
GTEST_API_ bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id)
void ListTestsMatchingFilter()
static const char * GetDefaultFilter()
bool operator()(const TestCase *test_case) const
static bool TestPartNonfatallyFailed(const TestPartResult &result)
TestEventListener * repeater()
uint32_t digits10(uint64_t v)
bool ParseInt32(const Message &src_text, const char *str, Int32 *value)
std::chrono::steady_clock::time_point now()
void(* SetUpTestCaseFunc)()
void SuppressEventForwarding()
virtual void OnTestIterationStart(const UnitTest &unit_test, int iteration)=0
PrettyUnitTestResultPrinter()
static auto const forever
void SetGlobalTestPartResultReporter(TestPartResultReporterInterface *reporter)
void RecordProperty(const std::string &key, const std::string &value)
static void PrintXmlUnitTest(::std::ostream *stream, const UnitTest &unit_test)
void ColoredPrintf(GTestColor color, const char *fmt,...)
void SplitString(const ::std::string &str, char delimiter,::std::vector< ::std::string > *dest)
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
virtual void OnEnvironmentsSetUpEnd(const UnitTest &)
bool ParseGoogleTestFlag(const char *const arg)
GTEST_API_ AssertionResult DoubleNearPredFormat(const char *expr1, const char *expr2, const char *abs_error_expr, double val1, double val2, double abs_error)
static std::string GetAbsolutePathToOutputFile()
Message & operator<<(const T &val)
GTEST_API_ bool SkipPrefix(const char *prefix, const char **pstr)
GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms)
virtual void OnTestStart(const TestInfo &test_info)=0
static bool ValidateTestProperty(const std::string &xml_element, const TestProperty &test_property)
void operator=(const Message &message) const
virtual void OnTestCaseEnd(const TestCase &test_case)
int reportable_disabled_test_count() const
const TestPartResult & GetTestPartResult(int i) const
std::vector< TestInfo * > & test_info_list()
const TestProperty & GetTestProperty(int i) const
internal::TearDownTestCaseFunc TearDownTestCaseFunc
bool IsUtf16SurrogatePair(wchar_t first, wchar_t second)
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)
int test_case_to_run_count() const
GTEST_API_ std::string CodePointToUtf8(UInt32 code_point)
const char kBreakOnFailureFlag[]
static const char kTestTotalShards[]
static bool PatternMatchesString(const char *pattern, const char *str)
std::string FormatForComparisonFailureMessage(const T1 &value, const T2 &)
bool ParseBoolFlag(const char *str, const char *flag, bool *value)
#define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings)
bool prefix(Cursor &c, uint32_t expected)
static std::string FormatByte(unsigned char value)
int reportable_test_count() const
int disabled_test_count() const
int total_test_count() const
AssertionResult HasOneFailure(const char *, const char *, const char *, const TestPartResultArray &results, TestPartResult::Type type, const string &substr)
const UInt32 kMaxCodePoint3
static const char *const kElidedFramesMarker
requires And< SemiMovable< VN >... > &&SemiMovable< E > auto error(E e)
static std::vector< std::string > GetReservedAttributesForElement(const std::string &xml_element)
::std::vector< testing::internal::string > g_argvs
virtual void OnTestProgramStart(const UnitTest &)
void PushGTestTrace(const internal::TraceInfo &trace) GTEST_LOCK_EXCLUDED_(mutex_)
static std::string FormatHexInt(int value)
virtual void OnTestIterationEnd(const UnitTest &unit_test, int iteration)
const char kRandomSeedFlag[]
TimeInMillis start_timestamp() const
int total_test_count() const
std::string StreamableToString(const T &streamable)
AssertionResult(const AssertionResult &other)
const char kShuffleFlag[]
static const char kTestShardStatusFile[]
std::string ReadEntireFile(FILE *file)
bool HasNonfatalFailure() const
FOLLY_PUSH_WARNING RHS rhs
int reportable_test_count() const
#define GTEST_REVERSE_REPEATER_METHOD_(Name, Type)
#define EXPECT_PRED_FORMAT3(pred_format, v1, v2, v3)
void PostFlagParsingInit()
const internal::TypeId fixture_class_id_
void AddTestInfo(TestInfo *test_info)
void BENCHFUN() replace(size_t iters, size_t arg)
Gen range(Value begin, Value end)
void set_os_stack_trace_getter(OsStackTraceGetterInterface *getter)
DefaultGlobalTestPartResultReporter(UnitTestImpl *unit_test)
void Set(const FilePath &rhs)
#define GTEST_REPEATER_METHOD_(Name, Type)
GTEST_API_ TypeId GetTestTypeId()
static std::string TestPropertiesAsXmlAttributes(const TestResult &result)
std::list< std::pair< char, const char * > > hunk_adds_
static std::string FormatCountableNoun(int count, const char *singular_form, const char *plural_form)
#define GTEST_PROJECT_URL_
bool is_reportable() const
const char * name() const
int test_case_to_run_count() const
virtual void OnTestIterationEnd(const UnitTest &unit_test, int iteration)
virtual void OnTestIterationEnd(const UnitTest &unit_test, int iteration)=0
int test_to_run_count() const
virtual void OnTestProgramEnd(const UnitTest &unit_test)=0
TestCase * GetMutableTestCase(int i)
OsStackTraceGetterInterface * os_stack_trace_getter()
const char kDeathTestStyleFlag[]
GTEST_API_ AssertionResult AssertionSuccess()
void set_forwarding_enabled(bool enable)
static bool CaseInsensitiveWideCStringEquals(const wchar_t *lhs, const wchar_t *rhs)
const UInt32 kMaxCodePoint1
constexpr auto empty(C const &c) -> decltype(c.empty())
#define GTEST_HAS_GETTIMEOFDAY_
static std::string GetOutputFormat()
TestEventListeners & listeners()
void SetDefaultXmlGenerator(TestEventListener *listener)
bool forwarding_enabled() const
const int kMaxStackTraceDepth
static bool IsValidXmlCharacter(char c)
virtual void ReportTestPartResult(const TestPartResult &result)
void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc, Test::TearDownTestCaseFunc tear_down_tc, TestInfo *test_info)
static const char kValueParamLabel[]
static const char kDeathTestCaseFilter[]
static bool CStringEquals(const char *lhs, const char *rhs)
int reportable_test_count() const
void RecordProperty(const TestProperty &test_property)
FilePath RemoveFileName() const
void SetTestPartResultReporterForCurrentThread(TestPartResultReporterInterface *reporter)
auto lock(SynchronizedLocker...lockersIn) -> std::tuple< typename SynchronizedLocker::LockedPtr... >
static const char *const kReservedTestSuitesAttributes[]
AssertHelper(TestPartResult::Type type, const char *file, int line, const char *message)
int successful_test_count() const
#define GTEST_CHECK_(condition)
int successful_test_case_count() const
static bool WideCStringEquals(const wchar_t *lhs, const wchar_t *rhs)
GTEST_API_ const TypeId kTestTypeIdInGoogleTest
static bool GTestIsInitialized()
const std::string & string() const
auto end(TestAdlIterable &instance)
bool CaseInsensitiveCStringEquals(const char *lhs, const char *rhs)
const TestCase * GetTestCase(int i) const
TestInfo * GetMutableTestInfo(int i)
GTEST_API_ bool AlwaysTrue()
static bool CaseInsensitiveCStringEquals(const char *lhs, const char *rhs)
const char * file_name() const
static void PrintColorEncoded(const char *str)
void repeat(F const &func)
AssertionResult FloatingPointLE(const char *expr1, const char *expr2, RawType val1, RawType val2)
void AddTestPartResult(const TestPartResult &test_part_result)
Encoder::MutableCompressedList list
const TestCase * current_test_case() const
static std::string FormatTestCaseCount(int test_case_count)
void swap(AssertionResult &other)
int StrCaseCmp(const char *s1, const char *s2)
virtual void OnTestCaseStart(const TestCase &test_case)
TestResult * current_test_result()
bool HasFatalFailure() const
static map< string, int > m
UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first, wchar_t second)
static void OutputXmlAttribute(std::ostream *stream, const std::string &element_name, const std::string &name, const std::string &value)
ScopedTrace(const char *file, int line, const Message &message)
bool ParseStringFlag(const char *str, const char *flag, std::string *value)
const char * value_param() const
#define GTEST_FLAG_PREFIX_UPPER_
std::string GetString() const
int failed_test_count() const
static const char kUniversalFilter[]
GTEST_API_ AssertionResult IsSubstring(const char *needle_expr, const char *haystack_expr, const char *needle, const char *haystack)
GTEST_API_ FilePath GetCurrentExecutableName()
NetworkSocket socket(int af, int type, int protocol)
int test_to_run_count() const
GTEST_API_ TimeInMillis GetTimeInMillis()
int total_test_case_count() const
int total_test_case_count() const
std::array< uint8_t, 32 > Random
S lines(StringPiece source)
static void PrintOnOneLine(const char *str, int max_length)
static std::string FormatTestCount(int test_count)
static const char *const value
TestInfo(const std::string &test_case_name, const std::string &name, const char *a_type_param, const char *a_value_param, internal::CodeLocation a_code_location, internal::TypeId fixture_class_id, internal::TestFactoryBase *factory)
virtual string CurrentStackTrace(int max_depth, int skip_count)
static std::string RemoveInvalidXmlCharacters(const std::string &str)
void ShuffleTests(internal::Random *random)
const char * test_case_name() const
static bool TestPartFatallyFailed(const TestPartResult &result)
static GTEST_DEFINE_STATIC_MUTEX_(g_log_mutex)
const TestCase * GetTestCase(int i) const
const TestPartResult & GetTestPartResult(int index) const
const TestInfo * current_test_info() const GTEST_LOCK_EXCLUDED_(mutex_)
static const char *const kReservedTestCaseAttributes[]
static std::string EscapeXmlText(const char *str)
virtual void OnEnvironmentsTearDownEnd(const UnitTest &unit_test)=0
static FilePath GenerateUniqueFileName(const FilePath &directory, const FilePath &base_name, const char *extension)
int failed_test_case_count() const
GTEST_API_ std::string WideStringToUtf8(const wchar_t *str, int num_chars)
bool EventForwardingEnabled() const
const char * ParseFlagValue(const char *str, const char *flag, bool def_optional)
::std::string FormatCompilerIndependentFileLocation(const char *file, int line)
virtual ~TestEventRepeater()
internal::scoped_ptr< ::std::string > message_
GTEST_API_ AssertionResult CmpHelperSTRNE(const char *s1_expression, const char *s2_expression, const char *s1, const char *s2)
const TestResult & ad_hoc_test_result() const
GTEST_API_ const char kStackTraceMarker[]
static void PrintTestPartResult(const TestPartResult &test_part_result)
int test_property_count() const
void ShuffleRange(internal::Random *random, int begin, int end, std::vector< E > *v)
bool BoolFromGTestEnv(const char *flag, bool default_val)
bool IsAbsolutePath() const
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_DEFINE_bool_(death_test_use_fork, internal::BoolFromGTestEnv("death_test_use_fork", false),"Instructs to use fork()/_exit() instead of clone() in death tests. ""Ignored and always uses fork() on POSIX systems where clone() is not ""implemented. Useful when running under valgrind or similar tools if ""those do not support clone(). Valgrind 3.3.1 will just fail if ""it sees an unsupported combination of clone() flags. ""It is not recommended to use this flag w/o valgrind though it will ""work in 99% of the cases. Once valgrind is fixed, this flag will ""most likely be removed.")
Environment * AddEnvironment(Environment *env)
TestCaseNameIs(const std::string &name)
static bool ShouldRunTestCase(const TestCase *test_case)
int reportable_disabled_test_count() const
virtual void OnTestIterationEnd(const UnitTest &unit_test, int iteration)
int CountIf(const Container &c, Predicate predicate)
int disabled_test_count() const
uint64_t diff(uint64_t a, uint64_t b)
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()
const char kStackTraceDepthFlag[]
const char * GetAnsiColorCode(GTestColor color)
const T & move(const T &t)
const char kCatchExceptionsFlag[]
#define GTEST_IMPL_CMP_HELPER_(op_name, op)
const char kInternalRunDeathTestFlag[]
void InitGoogleTestImpl(int *argc, CharType **argv)
int Run() GTEST_MUST_USE_RESULT_
void ParseGoogleTestFlagsOnlyImpl(int *argc, CharType **argv)
XmlUnitTestResultPrinter(const char *output_file)
int FilterTests(ReactionToSharding shard_tests)
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)
TestEventListener * Release(TestEventListener *listener)
static std::string FormatWordList(const std::vector< std::string > &words)
GTEST_API_ void ParseGoogleTestFlagsOnly(int *argc, char **argv)
void ConfigureXmlOutput()
static bool HasSameFixtureClass()
void Shuffle(internal::Random *random, std::vector< E > *v)
virtual void OnTestCaseStart(const TestCase &test_case)=0
GTEST_API_ std::string GetBoolAssertionFailureMessage(const AssertionResult &assertion_result, const char *expression_text, const char *actual_predicate_value, const char *expected_predicate_value)
int successful_test_count() const
int total_test_count() const
GTEST_API_ std::string CreateUnifiedDiff(const std::vector< std::string > &left, const std::vector< std::string > &right, size_t context=2)
static const char kTestShardIndex[]
void RunTearDownTestCase()
virtual void OnEnvironmentsTearDownEnd(const UnitTest &)
#define GTEST_DISABLE_MSC_WARNINGS_POP_()
static bool TestCasePassed(const TestCase *test_case)
virtual void OnEnvironmentsSetUpEnd(const UnitTest &unit_test)=0
#define GTEST_LOCK_EXCLUDED_(locks)
GTEST_API_ std::string StringStreamToString(::std::stringstream *stream)
static const char kColorEncodedHelpMessage[]
virtual void UponLeavingGTest()=0
int total_part_count() const
AssertionResult operator!() const
static void TearDownEnvironment(Environment *env)
virtual void OnTestProgramStart(const UnitTest &unit_test)=0
void set_should_run(bool should)
GTEST_API_ AssertionResult DoubleLE(const char *expr1, const char *expr2, double val1, double val2)
const UInt32 kMaxCodePoint4
GTEST_API_ void InitGoogleTest(int *argc, char **argv)
int failed_test_case_count() const
const char * name() const
int successful_test_case_count() const
virtual void OnTestStart(const TestInfo &test_info)
TimeInMillis elapsed_time() const
const TestResult * result() const
GTEST_API_ AssertionResult IsNotSubstring(const char *needle_expr, const char *haystack_expr, const char *needle, const char *haystack)
static UnitTest * GetInstance()
void swap(SwapTrackingAlloc< T > &, SwapTrackingAlloc< T > &)
static bool PortableLocaltime(time_t seconds, struct tm *out)
void ClearTestPartResults()
void for_each(T const &range, Function< void(typename T::value_type const &) const > const &func)
#define GTEST_DISALLOW_COPY_AND_ASSIGN_(type)
GTEST_DEFINE_string_(internal_run_death_test,"","Indicates the file, line number, temporal index of ""the single death test to run, and a file descriptor to ""which a success code may be sent, all separated by ""the '|' characters. This flag is specified if and only if the current ""process is a sub-process launched for running a thread-safe ""death test. FOR INTERNAL USE ONLY.")
const UInt32 kMaxCodePoint2
static void PrintTestName(const char *test_case, const char *test)
std::list< std::pair< char, const char * > > hunk_removes_
const char * type_param() const
TypeWithSize< 8 >::Int TimeInMillis
static void OutputXmlTestInfo(::std::ostream *stream, const char *test_case_name, const TestInfo &test_info)
UInt32 Generate(UInt32 range)
static bool TestCaseFailed(const TestCase *test_case)
void ForEach(const Container &c, Functor functor)
FilePath RemoveDirectoryName() const
bool nonfatally_failed() const
static void RecordProperty(const std::string &key, const std::string &value)
const TestResult & ad_hoc_test_result() const
static bool FilterMatchesTest(const std::string &test_case_name, const std::string &test_name)
const char * GetEnv(const char *name)
GTEST_API_ Int32 Int32FromEnvOrDie(const char *env_var, Int32 default_val)
virtual void TestBody()=0
virtual void UponLeavingGTest()
static std::string FormatIntWidth2(int value)
void WriteToShardStatusFileIfNeeded()
UnitTestImpl(UnitTest *parent)
int close(NetworkSocket s)
static std::string ShowWideCString(const wchar_t *wide_c_str)
static constexpr uint64_t data[1]
virtual void OnTestIterationStart(const UnitTest &unit_test, int iteration)
static void PrintFailedTests(const UnitTest &unit_test)
std::list< std::pair< char, const char * > > hunk_
virtual void OnTestPartResult(const TestPartResult &result)
static bool MatchesFilter(const std::string &name, const char *filter)
DefaultPerThreadTestPartResultReporter(UnitTestImpl *unit_test)
std::vector< std::string > ArrayAsVector(const char *const (&array)[kSize])
const TestCase * current_test_case() const GTEST_LOCK_EXCLUDED_(mutex_)
virtual void OnEnvironmentsTearDownStart(const UnitTest &unit_test)
GMockOutputTest ExpectedCall FILE
#define GTEST_FLAG_SAVER_
static bool HasNonfatalFailure()
const char kPrintTimeFlag[]
TestInfo * current_test_info()
const char kThrowOnFailureFlag[]
bool ValidateTestPropertyName(const std::string &property_name, const std::vector< std::string > &reserved_names)
void PrintTo(const ReferenceWrapper< T > &ref,::std::ostream *os)
folly::Function< void()> parent
void Append(TestEventListener *listener)
static std::string PrintTestPartResultToString(const TestPartResult &test_part_result)
GTEST_API_ bool ParseInt32Flag(const char *str, const char *flag, Int32 *value)
virtual void OnTestEnd(const TestInfo &test_info)
virtual ~ScopedFakeTestPartResultReporter()
constexpr detail::First first
virtual void OnTestProgramEnd(const UnitTest &)
const char kFlagfileFlag[]
GTEST_API_ AssertionResult FloatLE(const char *expr1, const char *expr2, float val1, float val2)
std::string CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_
static void OutputXmlCDataSection(::std::ostream *stream, const char *data)
TimeInMillis elapsed_time() const
static const char kTypeParamLabel[]