109 #ifndef GTEST_INCLUDE_GTEST_GTEST_SPI_H_
110 #define GTEST_INCLUDE_GTEST_GTEST_SPI_H_
130 INTERCEPT_ALL_THREADS
174 const string& substr);
211 #define EXPECT_FATAL_FAILURE(statement, substr) \
213 class GTestExpectFatalFailureHelper {\
215 static void Execute() { statement; }\
217 ::testing::TestPartResultArray gtest_failures;\
218 ::testing::internal::SingleFailureChecker gtest_checker(\
219 >est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
221 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
222 ::testing::ScopedFakeTestPartResultReporter:: \
223 INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\
224 GTestExpectFatalFailureHelper::Execute();\
226 } while (::testing::internal::AlwaysFalse())
228 #define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
230 class GTestExpectFatalFailureHelper {\
232 static void Execute() { statement; }\
234 ::testing::TestPartResultArray gtest_failures;\
235 ::testing::internal::SingleFailureChecker gtest_checker(\
236 >est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
238 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
239 ::testing::ScopedFakeTestPartResultReporter:: \
240 INTERCEPT_ALL_THREADS, >est_failures);\
241 GTestExpectFatalFailureHelper::Execute();\
243 } while (::testing::internal::AlwaysFalse())
277 #define EXPECT_NONFATAL_FAILURE(statement, substr) \
279 ::testing::TestPartResultArray gtest_failures;\
280 ::testing::internal::SingleFailureChecker gtest_checker(\
281 >est_failures, ::testing::TestPartResult::kNonFatalFailure, \
284 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
285 ::testing::ScopedFakeTestPartResultReporter:: \
286 INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\
287 if (::testing::internal::AlwaysTrue()) { statement; }\
289 } while (::testing::internal::AlwaysFalse())
291 #define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
293 ::testing::TestPartResultArray gtest_failures;\
294 ::testing::internal::SingleFailureChecker gtest_checker(\
295 >est_failures, ::testing::TestPartResult::kNonFatalFailure, \
298 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
299 ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \
301 if (::testing::internal::AlwaysTrue()) { statement; }\
303 } while (::testing::internal::AlwaysFalse())
305 #endif // GTEST_INCLUDE_GTEST_GTEST_SPI_H_
327 # define GTEST_HAS_GETTIMEOFDAY_ 1
333 # include <strings.h>
334 # include <sys/mman.h>
335 # include <sys/time.h>
339 #elif GTEST_OS_SYMBIAN
340 # define GTEST_HAS_GETTIMEOFDAY_ 1
341 # include <sys/time.h>
344 # define GTEST_HAS_GETTIMEOFDAY_ 1
345 # include <sys/time.h>
348 # include <strings.h>
350 #elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE.
352 # include <windows.h>
354 #elif GTEST_OS_WINDOWS // We are on Windows proper.
357 # include <sys/timeb.h>
358 # include <sys/types.h>
359 # include <sys/stat.h>
361 # if GTEST_OS_WINDOWS_MINGW
368 # define GTEST_HAS_GETTIMEOFDAY_ 1
369 # include <sys/time.h>
370 # endif // GTEST_OS_WINDOWS_MINGW
374 # include <windows.h>
381 # define GTEST_HAS_GETTIMEOFDAY_ 1
385 # include <sys/time.h>
388 #endif // GTEST_OS_LINUX
390 #if GTEST_HAS_EXCEPTIONS
391 # include <stdexcept>
394 #if GTEST_CAN_STREAM_RESULTS_
395 # include <arpa/inet.h>
404 #define GTEST_IMPLEMENTATION_ 1
441 #ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_
442 #define GTEST_SRC_GTEST_INTERNAL_INL_H_
446 #if !GTEST_IMPLEMENTATION_
448 # error "gtest-internal-inl.h is part of Google Test's internal implementation."
449 # error "It must not be included except by Google Test itself."
450 #endif // GTEST_IMPLEMENTATION_
454 #endif // !_WIN32_WCE
464 #if GTEST_CAN_STREAM_RESULTS_
465 # include <arpa/inet.h>
470 # include <windows.h>
471 #endif // GTEST_OS_WINDOWS
532 const char* str,
const char* flag,
Int32* value);
537 const unsigned int raw_seed = (random_seed_flag == 0) ?
539 static_cast<unsigned int>(random_seed_flag);
543 const int normalized_seed =
544 static_cast<int>((raw_seed - 1U) %
546 return normalized_seed;
554 <<
"Invalid random seed " << seed <<
" - must be in [1, "
556 const int next_seed = seed + 1;
663 const char* shard_index_str,
664 bool in_subprocess_for_death_test);
676 int total_shards,
int shard_index,
int test_id);
682 template <
class Container,
typename Predicate>
683 inline int CountIf(
const Container& c, Predicate predicate) {
687 for (
typename Container::const_iterator it = c.begin(); it != c.end(); ++it) {
695 template <
class Container,
typename Functor>
696 void ForEach(
const Container& c, Functor functor) {
697 std::for_each(c.begin(), c.end(), functor);
702 template <
typename E>
703 inline E
GetElementOr(
const std::vector<E>& v,
int i, E default_value) {
704 return (i < 0 || i >=
static_cast<int>(v.size())) ?
default_value : v[i];
711 template <
typename E>
714 const int size =
static_cast<int>(v->size());
716 <<
"Invalid shuffle range start " << begin <<
": must be in range [0, "
719 <<
"Invalid shuffle range finish " << end <<
": must be in range ["
720 << begin <<
", " << size <<
"].";
724 for (
int range_width = end - begin; range_width >= 2; range_width--) {
725 const int last_in_range = begin + range_width - 1;
726 const int selected = begin + random->
Generate(range_width);
727 std::swap((*v)[selected], (*v)[last_in_range]);
732 template <
typename E>
734 ShuffleRange(random, 0,
static_cast<int>(v->size()), v);
739 template <
typename T>
756 return test_property.
key() ==
key_;
792 static bool PatternMatchesString(
const char *pattern,
const char *str);
796 static bool FilterMatchesTest(
const std::string &test_case_name,
805 static int GTestShouldProcessSEH(DWORD exception_code);
806 #endif // GTEST_OS_WINDOWS
810 static bool MatchesFilter(
const std::string& name,
const char* filter);
925 void SetGlobalTestPartResultReporter(
932 void SetTestPartResultReporterForCurrentThread(
936 int successful_test_case_count()
const;
939 int failed_test_case_count()
const;
942 int total_test_case_count()
const;
946 int test_case_to_run_count()
const;
949 int successful_test_count()
const;
952 int failed_test_count()
const;
955 int reportable_disabled_test_count()
const;
958 int disabled_test_count()
const;
961 int reportable_test_count()
const;
964 int total_test_count()
const;
967 int test_to_run_count()
const;
977 bool Passed()
const {
return !Failed(); }
982 return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed();
988 const int index =
GetElementOr(test_case_indices_, i, -1);
989 return index < 0 ? NULL : test_cases_[i];
995 const int index =
GetElementOr(test_case_indices_, i, -1);
996 return index < 0 ? NULL : test_cases_[index];
1043 TestCase* GetTestCase(
const char* test_case_name,
1044 const char* type_param,
1065 if (original_working_dir_.IsEmpty()) {
1068 <<
"Failed to get the current working directory.";
1074 tear_down_tc)->AddTestInfo(test_info);
1077 #if GTEST_HAS_PARAM_TEST
1081 return parameterized_test_registry_;
1083 #endif // GTEST_HAS_PARAM_TEST
1087 current_test_case_ = a_current_test_case;
1094 current_test_info_ = a_current_test_info;
1103 void RegisterParameterizedTests();
1118 ad_hoc_test_result_.Clear();
1125 void RecordProperty(
const TestProperty& test_property);
1129 IGNORE_SHARDING_PROTOCOL
1138 int FilterTests(ReactionToSharding shard_tests);
1141 void ListTestsMatchingFilter();
1153 return *(gtest_trace_stack_.pointer());
1156 return gtest_trace_stack_.get();
1159 #if GTEST_HAS_DEATH_TEST
1160 void InitDeathTestSubprocessControlInfo() {
1161 internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());
1167 const InternalRunDeathTestFlag* internal_run_death_test_flag()
const {
1168 return internal_run_death_test_flag_.get();
1172 internal::DeathTestFactory* death_test_factory() {
1173 return death_test_factory_.get();
1176 void SuppressTestEventsIfInSubprocess();
1178 friend class ReplaceDeathTestFactory;
1179 #endif // GTEST_HAS_DEATH_TEST
1183 void ConfigureXmlOutput();
1185 #if GTEST_CAN_STREAM_RESULTS_
1188 void ConfigureStreamingOutput();
1196 void PostFlagParsingInit();
1206 void ShuffleTests();
1209 void UnshuffleTests();
1216 friend class ::testing::UnitTest;
1258 #if GTEST_HAS_PARAM_TEST
1264 bool parameterized_tests_registered_;
1265 #endif // GTEST_HAS_PARAM_TEST
1318 #if GTEST_HAS_DEATH_TEST
1323 #endif // GTEST_HAS_DEATH_TEST
1341 #if GTEST_USES_SIMPLE_RE
1345 GTEST_API_ bool IsInSet(
char ch,
const char* str);
1352 GTEST_API_ bool AtomMatchesChar(
bool escaped,
char pattern,
char ch);
1353 GTEST_API_ bool ValidateRegex(
const char* regex);
1354 GTEST_API_ bool MatchRegexAtHead(
const char* regex,
const char* str);
1355 GTEST_API_ bool MatchRepetitionAndRegexAtHead(
1356 bool escaped,
char ch,
char repeat,
const char* regex,
const char* str);
1357 GTEST_API_ bool MatchRegexAnywhere(
const char* regex,
const char* str);
1359 #endif // GTEST_USES_SIMPLE_RE
1366 #if GTEST_HAS_DEATH_TEST
1372 # if GTEST_OS_WINDOWS
1376 AutoHandle() : handle_(INVALID_HANDLE_VALUE) {}
1377 explicit AutoHandle(HANDLE handle) : handle_(handle) {}
1379 ~AutoHandle() { Reset(); }
1381 HANDLE Get()
const {
return handle_; }
1382 void Reset() { Reset(INVALID_HANDLE_VALUE); }
1383 void Reset(HANDLE handle) {
1384 if (handle != handle_) {
1385 if (handle_ != INVALID_HANDLE_VALUE)
1386 ::CloseHandle(handle_);
1396 # endif // GTEST_OS_WINDOWS
1402 template <
typename Integer>
1407 if (str.empty() || !
IsDigit(str[0])) {
1416 # if GTEST_OS_WINDOWS && !defined(__GNUC__)
1419 typedef unsigned __int64 BiggestConvertible;
1420 const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10);
1424 typedef unsigned long long BiggestConvertible;
1425 const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10);
1427 # endif // GTEST_OS_WINDOWS && !defined(__GNUC__)
1429 const bool parse_success = *end ==
'\0' && errno == 0;
1435 const Integer result =
static_cast<Integer
>(parsed);
1436 if (parse_success &&
static_cast<BiggestConvertible
>(result) == parsed) {
1442 #endif // GTEST_HAS_DEATH_TEST
1468 #if GTEST_CAN_STREAM_RESULTS_
1474 class AbstractSocketWriter {
1476 virtual ~AbstractSocketWriter() {}
1479 virtual void Send(
const string& message) = 0;
1482 virtual void CloseConnection() {}
1485 void SendLn(
const string& message) {
1486 Send(message +
"\n");
1491 class SocketWriter :
public AbstractSocketWriter {
1493 SocketWriter(
const string& host,
const string& port)
1494 : sockfd_(-1), host_name_(host), port_num_(port) {
1498 virtual ~SocketWriter() {
1504 virtual void Send(
const string& message) {
1506 <<
"Send() can be called only when there is a connection.";
1508 const int len =
static_cast<int>(message.length());
1509 if (write(sockfd_, message.c_str(), len) != len) {
1511 <<
"stream_result_to: failed to stream to "
1512 << host_name_ <<
":" << port_num_;
1518 void MakeConnection();
1521 void CloseConnection() {
1523 <<
"CloseConnection() can be called only when there is a connection.";
1530 const string host_name_;
1531 const string port_num_;
1537 static string UrlEncode(
const char* str);
1539 StreamingListener(
const string& host,
const string& port)
1540 : socket_writer_(new SocketWriter(host, port)) { Start(); }
1542 explicit StreamingListener(AbstractSocketWriter* socket_writer)
1543 : socket_writer_(socket_writer) { Start(); }
1545 void OnTestProgramStart(
const UnitTest& ) {
1546 SendLn(
"event=TestProgramStart");
1549 void OnTestProgramEnd(
const UnitTest& unit_test) {
1552 SendLn(
"event=TestProgramEnd&passed=" + FormatBool(unit_test.Passed()));
1555 socket_writer_->CloseConnection();
1558 void OnTestIterationStart(
const UnitTest& ,
int iteration) {
1559 SendLn(
"event=TestIterationStart&iteration=" +
1563 void OnTestIterationEnd(
const UnitTest& unit_test,
int ) {
1564 SendLn(
"event=TestIterationEnd&passed=" +
1565 FormatBool(unit_test.Passed()) +
"&elapsed_time=" +
1569 void OnTestCaseStart(
const TestCase& test_case) {
1570 SendLn(
std::string(
"event=TestCaseStart&name=") + test_case.name());
1573 void OnTestCaseEnd(
const TestCase& test_case) {
1574 SendLn(
"event=TestCaseEnd&passed=" + FormatBool(test_case.Passed())
1579 void OnTestStart(
const TestInfo& test_info) {
1580 SendLn(
std::string(
"event=TestStart&name=") + test_info.name());
1583 void OnTestEnd(
const TestInfo& test_info) {
1584 SendLn(
"event=TestEnd&passed=" +
1585 FormatBool((test_info.result())->Passed()) +
1590 void OnTestPartResult(
const TestPartResult& test_part_result) {
1591 const char* file_name = test_part_result.file_name();
1592 if (file_name == NULL)
1594 SendLn(
"event=TestPartResult&file=" + UrlEncode(file_name) +
1596 "&message=" + UrlEncode(test_part_result.message()));
1601 void SendLn(
const string& message) { socket_writer_->SendLn(message); }
1605 void Start() { SendLn(
"gtest_streaming_protocol_version=1.0"); }
1607 string FormatBool(
bool value) {
return value ?
"1" :
"0"; }
1609 const scoped_ptr<AbstractSocketWriter> socket_writer_;
1614 #endif // GTEST_CAN_STREAM_RESULTS_
1619 #endif // GTEST_SRC_GTEST_INTERNAL_INL_H_
1620 #undef GTEST_IMPLEMENTATION_
1622 #if GTEST_OS_WINDOWS
1623 # define vsnprintf _vsnprintf
1624 #endif // GTEST_OS_WINDOWS
1657 namespace internal {
1674 also_run_disabled_tests,
1676 "Run disabled tests too, in addition to the tests normally being run.");
1681 "True iff a failed assertion should be a debugger break-point.");
1687 " should catch exceptions and treat them as test failures.");
1692 "Whether to use colors in the output. Valid values: yes, no, "
1693 "and auto. 'auto' means to use colors if the output is "
1694 "being sent to a terminal and the TERM environment variable "
1695 "is set to a terminal type that supports colors.");
1700 "A colon-separated list of glob (not regex) patterns "
1701 "for filtering the tests to run, optionally followed by a "
1702 "'-' and a : separated list of negative patterns (tests to "
1703 "exclude). A test is run if it matches one of the positive "
1704 "patterns and does not match any of the negative patterns.");
1707 "List all tests without running them.");
1712 "A format (currently must be \"xml\"), optionally followed "
1713 "by a colon and an output file name or directory. A directory "
1714 "is indicated by a trailing pathname separator. "
1715 "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
1716 "If a directory is specified, output files will be created "
1717 "within that directory, with file-names based on the test "
1718 "executable's name and, if necessary, made unique by adding "
1725 " should display elapsed time in text output.");
1730 "Random number seed to use when shuffling test orders. Must be in range "
1731 "[1, 99999], or 0 to use a seed based on the current time.");
1736 "How many times to repeat each test. Specify a negative number "
1737 "for repeating forever. Useful for shaking out flaky tests.");
1740 show_internal_stack_frames,
false,
1741 "True iff " GTEST_NAME_ " should include internal stack frames when "
1742 "printing test failure stack traces.");
1748 " should randomize tests' order on every run.");
1753 "The maximum number of stack frames to print when an "
1754 "assertion fails. The valid range is 0 through 100, inclusive.");
1759 "This flag specifies the host name and the port number on which to stream "
1760 "test results. Example: \"localhost:555\". The flag is effective only on "
1766 "When this flag is specified, a failed assertion will throw an exception "
1767 "if exceptions are enabled or exit the program with a non-zero code "
1770 namespace internal {
1780 <<
"Cannot generate a number in the range [0, 0).";
1782 <<
"Generation of a number in [0, " << range <<
") was requested, "
1783 <<
"but this can only generate numbers in [0, " <<
kMaxRange <<
").";
1808 for (
size_t i = 0; i < case_list.size(); i++) {
1809 sum += (case_list[i]->*method)();
1834 const char* message)
1864 #if GTEST_OS_WINDOWS
1868 #endif // GTEST_OS_WINDOWS
1877 const char*
const gtest_output_flag =
GTEST_FLAG(output).c_str();
1878 if (gtest_output_flag == NULL)
return std::string(
"");
1880 const char*
const colon = strchr(gtest_output_flag,
':');
1881 return (colon == NULL) ?
1883 std::string(gtest_output_flag, colon - gtest_output_flag);
1889 const char*
const gtest_output_flag =
GTEST_FLAG(output).c_str();
1890 if (gtest_output_flag == NULL)
1893 const char*
const colon = strchr(gtest_output_flag,
':');
1911 return output_name.
string();
1929 return *str ==
'\0';
1936 return *pattern == *str &&
1943 const char *cur_pattern = filter;
1950 cur_pattern = strchr(cur_pattern,
':');
1953 if (cur_pattern == NULL) {
1966 const std::string& full_name = test_case_name +
"." + test_name.c_str();
1970 const char*
const p =
GTEST_FLAG(filter).c_str();
1971 const char*
const dash = strchr(p,
'-');
1980 if (positive.empty()) {
1996 int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
2005 const DWORD kCxxExceptionCode = 0xe06d7363;
2007 bool should_handle =
true;
2010 should_handle =
false;
2011 else if (exception_code == EXCEPTION_BREAKPOINT)
2012 should_handle =
false;
2013 else if (exception_code == kCxxExceptionCode)
2014 should_handle =
false;
2016 return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
2018 #endif // GTEST_HAS_SEH
2027 : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
2037 : intercept_mode_(intercept_mode),
2071 namespace internal {
2083 return GetTypeId<Test>();
2098 const string& substr) {
2101 "1 non-fatal failure");
2103 if (results.
size() != 1) {
2104 msg <<
"Expected: " << expected <<
"\n"
2105 <<
" Actual: " << results.
size() <<
" failures";
2106 for (
int i = 0; i < results.
size(); i++) {
2113 if (r.
type() != type) {
2119 if (strstr(r.
message(), substr.c_str()) == NULL) {
2135 const string& substr)
2136 : results_(results),
2265 #if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__)
2270 const DWORD kTenthMicrosInMilliSecond = 10000;
2272 SYSTEMTIME now_systime;
2273 FILETIME now_filetime;
2274 ULARGE_INTEGER now_int64;
2277 GetSystemTime(&now_systime);
2278 if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
2279 now_int64.LowPart = now_filetime.dwLowDateTime;
2280 now_int64.HighPart = now_filetime.dwHighDateTime;
2281 now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
2282 kJavaEpochToWinFileTimeDelta;
2283 return now_int64.QuadPart;
2286 #elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_
2295 # pragma warning(push) // Saves the current warning state.
2296 # pragma warning(disable:4996) // Temporarily disables warning 4996.
2298 # pragma warning(pop) // Restores the warning state.
2305 return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
2308 gettimeofday(&now, NULL);
2309 return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
2311 # error
"Don't know how to get the current time on your system."
2319 #if GTEST_OS_WINDOWS_MOBILE
2324 LPCWSTR String::AnsiToUtf16(
const char* ansi) {
2325 if (!ansi)
return NULL;
2326 const int length = strlen(ansi);
2327 const int unicode_length =
2328 MultiByteToWideChar(CP_ACP, 0, ansi, length,
2330 WCHAR* unicode =
new WCHAR[unicode_length + 1];
2331 MultiByteToWideChar(CP_ACP, 0, ansi, length,
2332 unicode, unicode_length);
2333 unicode[unicode_length] = 0;
2341 const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
2342 if (!utf16_str)
return NULL;
2343 const int ansi_length =
2344 WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
2345 NULL, 0, NULL, NULL);
2346 char* ansi =
new char[ansi_length + 1];
2347 WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
2348 ansi, ansi_length, NULL, NULL);
2349 ansi[ansi_length] = 0;
2353 #endif // GTEST_OS_WINDOWS_MOBILE
2361 if ( lhs == NULL )
return rhs == NULL;
2363 if ( rhs == NULL )
return false;
2365 return strcmp(lhs, rhs) == 0;
2368 #if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
2372 static void StreamWideCharsToMessage(
const wchar_t* wstr,
size_t length,
2374 for (
size_t i = 0; i != length; ) {
2375 if (wstr[i] != L
'\0') {
2376 *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
2377 while (i != length && wstr[i] != L
'\0')
2386 #endif // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
2398 *
ss_ << std::setprecision(std::numeric_limits<double>::digits10 + 2);
2410 #if GTEST_HAS_STD_WSTRING
2414 internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(),
this);
2417 #endif // GTEST_HAS_STD_WSTRING
2419 #if GTEST_HAS_GLOBAL_WSTRING
2423 internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(),
this);
2426 #endif // GTEST_HAS_GLOBAL_WSTRING
2437 : success_(other.success_),
2438 message_(other.message_.
get() != NULL ?
2467 namespace internal {
2485 const char* actual_expression,
2488 bool ignoring_case) {
2490 msg <<
"Value of: " << actual_expression;
2491 if (actual_value != actual_expression) {
2492 msg <<
"\n Actual: " << actual_value;
2495 msg <<
"\nExpected: " << expected_expression;
2496 if (ignoring_case) {
2497 msg <<
" (ignoring case)";
2499 if (expected_value != expected_expression) {
2500 msg <<
"\nWhich is: " << expected_value;
2509 const char* expression_text,
2510 const char* actual_predicate_value,
2511 const char* expected_predicate_value) {
2512 const char* actual_message = assertion_result.
message();
2514 msg <<
"Value of: " << expression_text
2515 <<
"\n Actual: " << actual_predicate_value;
2516 if (actual_message[0] !=
'\0')
2517 msg <<
" (" << actual_message <<
")";
2518 msg <<
"\nExpected: " << expected_predicate_value;
2519 return msg.GetString();
2525 const char* abs_error_expr,
2529 const double diff = fabs(val1 - val2);
2535 <<
"The difference between " << expr1 <<
" and " << expr2
2536 <<
" is " << diff <<
", which exceeds " << abs_error_expr <<
", where\n"
2537 << expr1 <<
" evaluates to " << val1 <<
",\n"
2538 << expr2 <<
" evaluates to " << val2 <<
", and\n"
2539 << abs_error_expr <<
" evaluates to " << abs_error <<
".";
2544 template <
typename RawType>
2556 if (lhs.AlmostEquals(rhs)) {
2564 ::std::stringstream val1_ss;
2565 val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
2568 ::std::stringstream val2_ss;
2569 val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
2573 <<
"Expected: (" << expr1 <<
") <= (" << expr2 <<
")\n"
2583 float val1,
float val2) {
2584 return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
2590 double val1,
double val2) {
2591 return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
2594 namespace internal {
2599 const char* actual_expression,
2602 if (expected == actual) {
2616 #define GTEST_IMPL_CMP_HELPER_(op_name, op)\
2617 AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
2618 BiggestInt val1, BiggestInt val2) {\
2619 if (val1 op val2) {\
2620 return AssertionSuccess();\
2622 return AssertionFailure() \
2623 << "Expected: (" << expr1 << ") " #op " (" << expr2\
2624 << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
2625 << " vs " << FormatForComparisonFailureMessage(val2, val1);\
2645 #undef GTEST_IMPL_CMP_HELPER_
2649 const char* actual_expression,
2650 const char* expected,
2651 const char* actual) {
2665 const char* actual_expression,
2666 const char* expected,
2667 const char* actual) {
2681 const char* s2_expression,
2688 << s2_expression <<
"), actual: \""
2689 << s1 <<
"\" vs \"" << s2 <<
"\"";
2695 const char* s2_expression,
2702 <<
"Expected: (" << s1_expression <<
") != ("
2703 << s2_expression <<
") (ignoring case), actual: \""
2704 << s1 <<
"\" vs \"" << s2 <<
"\"";
2718 bool IsSubstringPred(
const char* needle,
const char* haystack) {
2719 if (needle == NULL || haystack == NULL)
2720 return needle == haystack;
2722 return strstr(haystack, needle) != NULL;
2725 bool IsSubstringPred(
const wchar_t* needle,
const wchar_t* haystack) {
2726 if (needle == NULL || haystack == NULL)
2727 return needle == haystack;
2729 return wcsstr(haystack, needle) != NULL;
2733 template <
typename StringType>
2734 bool IsSubstringPred(
const StringType& needle,
2735 const StringType& haystack) {
2736 return haystack.find(needle) != StringType::npos;
2743 template <
typename StringType>
2744 AssertionResult IsSubstringImpl(
2745 bool expected_to_be_substring,
2746 const char* needle_expr,
const char* haystack_expr,
2747 const StringType& needle,
const StringType& haystack) {
2748 if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
2751 const bool is_wide_string =
sizeof(needle[0]) > 1;
2752 const char*
const begin_string_quote = is_wide_string ?
"L\"" :
"\"";
2754 <<
"Value of: " << needle_expr <<
"\n"
2755 <<
" Actual: " << begin_string_quote << needle <<
"\"\n"
2756 <<
"Expected: " << (expected_to_be_substring ?
"" :
"not ")
2757 <<
"a substring of " << haystack_expr <<
"\n"
2758 <<
"Which is: " << begin_string_quote << haystack <<
"\"";
2768 const char* needle_expr,
const char* haystack_expr,
2769 const char* needle,
const char* haystack) {
2770 return IsSubstringImpl(
true, needle_expr, haystack_expr, needle, haystack);
2774 const char* needle_expr,
const char* haystack_expr,
2775 const wchar_t* needle,
const wchar_t* haystack) {
2776 return IsSubstringImpl(
true, needle_expr, haystack_expr, needle, haystack);
2780 const char* needle_expr,
const char* haystack_expr,
2781 const char* needle,
const char* haystack) {
2782 return IsSubstringImpl(
false, needle_expr, haystack_expr, needle, haystack);
2786 const char* needle_expr,
const char* haystack_expr,
2787 const wchar_t* needle,
const wchar_t* haystack) {
2788 return IsSubstringImpl(
false, needle_expr, haystack_expr, needle, haystack);
2792 const char* needle_expr,
const char* haystack_expr,
2794 return IsSubstringImpl(
true, needle_expr, haystack_expr, needle, haystack);
2798 const char* needle_expr,
const char* haystack_expr,
2800 return IsSubstringImpl(
false, needle_expr, haystack_expr, needle, haystack);
2803 #if GTEST_HAS_STD_WSTRING
2805 const char* needle_expr,
const char* haystack_expr,
2807 return IsSubstringImpl(
true, needle_expr, haystack_expr, needle, haystack);
2811 const char* needle_expr,
const char* haystack_expr,
2813 return IsSubstringImpl(
false, needle_expr, haystack_expr, needle, haystack);
2815 #endif // GTEST_HAS_STD_WSTRING
2817 namespace internal {
2819 #if GTEST_OS_WINDOWS
2824 AssertionResult HRESULTFailureHelper(
const char* expr,
2825 const char* expected,
2827 # if GTEST_OS_WINDOWS_MOBILE
2830 const char error_text[] =
"";
2837 const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
2838 FORMAT_MESSAGE_IGNORE_INSERTS;
2839 const DWORD kBufSize = 4096;
2841 char error_text[kBufSize] = {
'\0' };
2842 DWORD message_length = ::FormatMessageA(kFlags,
2850 for (; message_length &&
IsSpace(error_text[message_length - 1]);
2852 error_text[message_length - 1] =
'\0';
2855 # endif // GTEST_OS_WINDOWS_MOBILE
2859 <<
"Expected: " << expr <<
" " << expected <<
".\n"
2860 <<
" Actual: " << error_hex <<
" " << error_text <<
"\n";
2865 AssertionResult IsHRESULTSuccess(
const char* expr,
long hr) {
2866 if (SUCCEEDED(hr)) {
2869 return HRESULTFailureHelper(expr,
"succeeds", hr);
2872 AssertionResult IsHRESULTFailure(
const char* expr,
long hr) {
2876 return HRESULTFailureHelper(expr,
"fails", hr);
2879 #endif // GTEST_OS_WINDOWS
2909 const UInt32 low_bits = *bits & ((
static_cast<UInt32>(1) << n) - 1);
2928 str[0] =
static_cast<char>(code_point);
2931 str[1] =
static_cast<char>(0x80 |
ChopLowBits(&code_point, 6));
2932 str[0] =
static_cast<char>(0xC0 | code_point);
2935 str[2] =
static_cast<char>(0x80 |
ChopLowBits(&code_point, 6));
2936 str[1] =
static_cast<char>(0x80 |
ChopLowBits(&code_point, 6));
2937 str[0] =
static_cast<char>(0xE0 | code_point);
2940 str[3] =
static_cast<char>(0x80 |
ChopLowBits(&code_point, 6));
2941 str[2] =
static_cast<char>(0x80 |
ChopLowBits(&code_point, 6));
2942 str[1] =
static_cast<char>(0x80 |
ChopLowBits(&code_point, 6));
2943 str[0] =
static_cast<char>(0xF0 | code_point);
2956 return sizeof(wchar_t) == 2 &&
2957 (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;
2963 const UInt32 mask = (1 << 10) - 1;
2964 return (
sizeof(
wchar_t) == 2) ?
2965 (((first & mask) << 10) | (second & mask)) + 0x10000 :
2968 static_cast<UInt32>(first);
2985 if (num_chars == -1)
2986 num_chars =
static_cast<int>(wcslen(str));
2988 ::std::stringstream stream;
2989 for (
int i = 0; i < num_chars; ++i) {
2990 UInt32 unicode_code_point;
2992 if (str[i] == L
'\0') {
2999 unicode_code_point =
static_cast<UInt32>(str[i]);
3010 if (wide_c_str == NULL)
return "(null)";
3022 if (lhs == NULL)
return rhs == NULL;
3024 if (rhs == NULL)
return false;
3026 return wcscmp(lhs, rhs) == 0;
3031 const char* actual_expression,
3032 const wchar_t* expected,
3033 const wchar_t* actual) {
3047 const char* s2_expression,
3049 const wchar_t* s2) {
3055 << s2_expression <<
"), actual: "
3087 const wchar_t* rhs) {
3088 if (lhs == NULL)
return rhs == NULL;
3090 if (rhs == NULL)
return false;
3092 #if GTEST_OS_WINDOWS
3093 return _wcsicmp(lhs, rhs) == 0;
3094 #elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID
3095 return wcscasecmp(lhs, rhs) == 0;
3101 left = towlower(*lhs++);
3102 right = towlower(*rhs++);
3103 }
while (left && left == right);
3104 return left == right;
3105 #endif // OS selector
3112 const size_t str_len = str.length();
3113 const size_t suffix_len = suffix.length();
3114 return (str_len >= suffix_len) &&
3121 std::stringstream ss;
3122 ss << std::setfill(
'0') << std::setw(2) << value;
3128 std::stringstream ss;
3129 ss << std::hex << std::uppercase << value;
3135 std::stringstream ss;
3136 ss << std::setfill(
'0') << std::setw(2) << std::hex << std::uppercase
3137 <<
static_cast<unsigned int>(value);
3145 const char*
const start = str.c_str();
3146 const char*
const end =
start + str.length();
3149 result.reserve(2 * (end -
start));
3150 for (
const char* ch =
start; ch != end; ++ch) {
3166 if (user_msg_string.empty()) {
3170 return gtest_msg +
"\n" + user_msg_string;
3179 : death_test_count_(0),
3224 const std::vector<TestProperty>::iterator property_with_matching_key =
3231 property_with_matching_key->SetValue(test_property.
value());
3268 template <
int kSize>
3270 return std::vector<std::string>(array, array + kSize);
3275 if (xml_element ==
"testsuites") {
3277 }
else if (xml_element ==
"testsuite") {
3279 }
else if (xml_element ==
"testcase") {
3282 GTEST_CHECK_(
false) <<
"Unrecognized xml_element provided: " << xml_element;
3285 return std::vector<std::string>();
3290 for (
size_t i = 0; i < words.size(); ++i) {
3291 if (i > 0 && words.size() > 2) {
3294 if (i == words.size() - 1) {
3295 word_list <<
"and ";
3297 word_list <<
"'" << words[i] <<
"'";
3303 const std::vector<std::string>& reserved_names) {
3304 if (std::find(reserved_names.begin(), reserved_names.end(), property_name) !=
3305 reserved_names.end()) {
3306 ADD_FAILURE() <<
"Reserved key used in RecordProperty(): " << property_name
3376 : gtest_flag_saver_(new internal::GTestFlagSaver) {
3404 value_message << value;
3408 namespace internal {
3436 const char*
const first_test_name = first_test_info->
name();
3441 const char*
const this_test_name = this_test_info->
name();
3443 if (this_fixture_id != first_fixture_id) {
3449 if (first_is_TEST || this_is_TEST) {
3456 const char*
const TEST_name =
3457 first_is_TEST ? first_test_name : this_test_name;
3458 const char*
const TEST_F_name =
3459 first_is_TEST ? this_test_name : first_test_name;
3462 <<
"All tests in the same test case must use the same test fixture\n"
3463 <<
"class, so mixing TEST_F and TEST in the same test case is\n"
3466 <<
"test " << TEST_F_name <<
" is defined using TEST_F but\n"
3467 <<
"test " << TEST_name <<
" is defined using TEST. You probably\n"
3468 <<
"want to change the TEST to TEST_F or move it to another test\n"
3474 <<
"All tests in the same test case must use the same test fixture\n"
3475 <<
"class. However, in test case "
3477 <<
"you defined test " << first_test_name
3478 <<
" and test " << this_test_name <<
"\n"
3479 <<
"using two different test fixture classes. This can happen if\n"
3480 <<
"the two classes are from different namespaces or translation\n"
3481 <<
"units and have the same name. You should probably rename one\n"
3482 <<
"of the classes to put the tests into different test cases.";
3496 static std::string* FormatSehExceptionMessage(DWORD exception_code,
3497 const char* location) {
3499 message <<
"SEH exception with code 0x" << std::setbase(16) <<
3500 exception_code << std::setbase(10) <<
" thrown in " << location <<
".";
3505 #endif // GTEST_HAS_SEH
3507 namespace internal {
3509 #if GTEST_HAS_EXCEPTIONS
3512 static std::string FormatCxxExceptionMessage(
const char* description,
3513 const char* location) {
3515 if (description != NULL) {
3516 message <<
"C++ exception with description \"" << description <<
"\"";
3518 message <<
"Unknown C++ exception";
3520 message <<
" thrown in " << location <<
".";
3522 return message.GetString();
3526 const TestPartResult& test_part_result);
3528 GoogleTestFailureException::GoogleTestFailureException(
3529 const TestPartResult& failure)
3532 #endif // GTEST_HAS_EXCEPTIONS
3542 template <
class T,
typename Result>
3544 T*
object, Result (T::*method)(),
const char* location) {
3547 return (object->*method)();
3548 } __except (internal::UnitTestOptions::GTestShouldProcessSEH(
3549 GetExceptionCode())) {
3553 std::string* exception_message = FormatSehExceptionMessage(
3554 GetExceptionCode(), location);
3556 *exception_message);
3557 delete exception_message;
3558 return static_cast<Result
>(0);
3562 return (object->*method)();
3563 #endif // GTEST_HAS_SEH
3569 template <
class T,
typename Result>
3571 T*
object, Result (T::*method)(),
const char* location) {
3596 #if GTEST_HAS_EXCEPTIONS
3599 }
catch (
const internal::GoogleTestFailureException&) {
3604 }
catch (
const std::exception& e) {
3607 FormatCxxExceptionMessage(e.what(), location));
3611 FormatCxxExceptionMessage(NULL, location));
3613 return static_cast<Result
>(0);
3616 #endif // GTEST_HAS_EXCEPTIONS
3618 return (object->*method)();
3626 if (!HasSameFixtureClass())
return;
3632 if (!HasFatalFailure()) {
3635 this, &Test::TestBody,
"the test body");
3643 this, &Test::TearDown,
"TearDown()");
3647 bool Test::HasFatalFailure() {
3652 bool Test::HasNonfatalFailure() {
3654 HasNonfatalFailure();
3663 const char* a_type_param,
3664 const char* a_value_param,
3667 : test_case_name_(a_test_case_name),
3669 type_param_(a_type_param ? new
std::
string(a_type_param) : NULL),
3670 value_param_(a_value_param ? new
std::
string(a_value_param) : NULL),
3671 fixture_class_id_(fixture_class_id),
3673 is_disabled_(false),
3674 matches_filter_(false),
3681 namespace internal {
3701 const char* test_case_name,
3703 const char* type_param,
3704 const char* value_param,
3710 new TestInfo(test_case_name, name, type_param, value_param,
3711 fixture_class_id, factory);
3716 #if GTEST_HAS_PARAM_TEST
3718 const char* file,
int line) {
3721 <<
"Attempted redefinition of test case " << test_case_name <<
".\n"
3722 <<
"All tests in the same test case must use the same test fixture\n"
3723 <<
"class. However, in test case " << test_case_name <<
", you tried\n"
3724 <<
"to define a test using a fixture class different from the one\n"
3725 <<
"used earlier. This can happen if the two fixture classes are\n"
3726 <<
"from different namespaces and have the same name. You should\n"
3727 <<
"probably rename one of the classes to put the tests into different\n"
3733 #endif // GTEST_HAS_PARAM_TEST
3752 explicit TestNameIs(
const char* name)
3756 bool operator()(
const TestInfo * test_info)
const {
3757 return test_info && test_info->name() ==
name_;
3766 namespace internal {
3772 #if GTEST_HAS_PARAM_TEST
3773 if (!parameterized_tests_registered_) {
3774 parameterized_test_registry_.RegisterTests();
3775 parameterized_tests_registered_ =
true;
3803 "the test fixture's constructor");
3878 type_param_(a_type_param ? new
std::
string(a_type_param) : NULL),
3879 set_up_tc_(set_up_tc),
3880 tear_down_tc_(tear_down_tc),
3964 const char * singular_form,
3965 const char * plural_form) {
3967 (count == 1 ? singular_form : plural_form);
3997 return "Unknown result type";
4001 namespace internal {
4010 << test_part_result.
message()).GetString();
4017 printf(
"%s\n", result.c_str());
4023 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4027 ::OutputDebugStringA(result.c_str());
4028 ::OutputDebugStringA(
"\n");
4041 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4048 case COLOR_YELLOW:
return FOREGROUND_RED | FOREGROUND_GREEN;
4062 default:
return NULL;
4066 #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4070 const char*
const gtest_color =
GTEST_FLAG(color).c_str();
4073 #if GTEST_OS_WINDOWS
4076 return stdout_is_tty;
4080 const bool term_supports_color =
4088 return stdout_is_tty && term_supports_color;
4089 #endif // GTEST_OS_WINDOWS
4107 va_start(args, fmt);
4109 #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS || GTEST_OS_IOS
4110 const bool use_color =
false;
4112 static const bool in_color_mode =
4114 const bool use_color = in_color_mode && (color !=
COLOR_DEFAULT);
4115 #endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
4124 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4125 const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
4128 CONSOLE_SCREEN_BUFFER_INFO buffer_info;
4129 GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
4130 const WORD old_color_attrs = buffer_info.wAttributes;
4136 SetConsoleTextAttribute(stdout_handle,
4137 GetColorAttribute(color) | FOREGROUND_INTENSITY);
4142 SetConsoleTextAttribute(stdout_handle, old_color_attrs);
4147 #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4157 const char*
const type_param = test_info.
type_param();
4158 const char*
const value_param = test_info.
value_param();
4160 if (type_param != NULL || value_param != NULL) {
4162 if (type_param != NULL) {
4164 if (value_param != NULL)
4167 if (value_param != NULL) {
4180 printf(
"%s.%s", test_case,
test);
4204 const UnitTest& unit_test,
int iteration) {
4206 printf(
"\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
4208 const char*
const filter =
GTEST_FLAG(filter).c_str();
4220 "Note: This is test shard %d of %s.\n",
4221 static_cast<int>(shard_index) + 1,
4227 "Note: Randomizing tests' orders with a seed of %d .\n",
4232 printf(
"Running %s from %s.\n",
4241 printf(
"Global test environment set-up.\n");
4249 printf(
"%s from %s", counts.c_str(), test_case.
name());
4302 printf(
"%s from %s (%s ms total)\n\n",
4303 counts.c_str(), test_case.
name(),
4311 printf(
"Global test environment tear-down\n");
4318 if (failed_test_count == 0) {
4333 printf(
"%s.%s", test_case.
name(), test_info.
name());
4343 printf(
"%s from %s ran.",
4347 printf(
" (%s ms total)",
4355 if (!unit_test.
Passed()) {
4358 printf(
"%s, listed below:\n",
FormatTestCount(failed_test_count).c_str());
4360 printf(
"\n%2d FAILED %s\n", num_failures,
4361 num_failures == 1 ?
"TEST" :
"TESTS");
4365 if (num_disabled && !
GTEST_FLAG(also_run_disabled_tests)) {
4366 if (!num_failures) {
4370 " YOU HAVE %d DISABLED %s\n\n",
4372 num_disabled == 1 ?
"TEST" :
"TESTS");
4429 for (
size_t i = 0; i <
listeners_.size(); ++i) {
4441 #define GTEST_REPEATER_METHOD_(Name, Type) \
4442 void TestEventRepeater::Name(const Type& parameter) { \
4443 if (forwarding_enabled_) { \
4444 for (size_t i = 0; i < listeners_.size(); i++) { \
4445 listeners_[i]->Name(parameter); \
4451 #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
4452 void TestEventRepeater::Name(const Type& parameter) { \
4453 if (forwarding_enabled_) { \
4454 for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \
4455 listeners_[i]->Name(parameter); \
4472 #undef GTEST_REPEATER_METHOD_
4473 #undef GTEST_REVERSE_REPEATER_METHOD_
4478 for (
size_t i = 0; i <
listeners_.size(); i++) {
4479 listeners_[i]->OnTestIterationStart(unit_test, iteration);
4487 for (
int i =
static_cast<int>(
listeners_.size()) - 1; i >= 0; i--) {
4488 listeners_[i]->OnTestIterationEnd(unit_test, iteration);
4506 return c == 0x9 || c == 0xA || c == 0xD;
4545 const char* test_case_name,
4570 : output_file_(output_file) {
4572 fprintf(stderr,
"XML output file may not be null\n");
4581 FILE* xmlout = NULL;
4588 if (xmlout == NULL) {
4600 "Unable to open file \"%s\"\n",
4605 std::stringstream stream;
4627 for (
size_t i = 0; i < str.size(); ++i) {
4628 const char ch = str[i];
4672 output.reserve(str.size());
4673 for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
4675 output.push_back(*it);
4698 ::std::stringstream ss;
4707 time_t seconds =
static_cast<time_t
>(ms / 1000);
4709 # pragma warning(push) // Saves the current warning state.
4710 # pragma warning(disable:4996) // Temporarily disables warning 4996
4712 const struct tm*
const time_struct = localtime(&seconds);
4713 # pragma warning(pop) // Restores the warning state again.
4715 const struct tm*
const time_struct = localtime(&seconds);
4717 if (time_struct == NULL)
4732 const char* segment =
data;
4733 *stream <<
"<![CDATA[";
4735 const char*
const next_segment = strstr(segment,
"]]>");
4736 if (next_segment != NULL) {
4738 segment,
static_cast<std::streamsize
>(next_segment - segment));
4739 *stream <<
"]]>]]><![CDATA[";
4740 segment = next_segment + strlen(
"]]>");
4750 std::ostream* stream,
4754 const std::vector<std::string>& allowed_names =
4757 GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
4758 allowed_names.end())
4759 <<
"Attribute " << name <<
" is not allowed for element <" << element_name
4768 const char* test_case_name,
4773 *stream <<
" <testcase";
4795 if (++failures == 1) {
4800 const string summary = location +
"\n" + part.
summary();
4801 *stream <<
" <failure message=\""
4804 const string detail = location +
"\n" + part.
message();
4806 *stream <<
"</failure>\n";
4813 *stream <<
" </testcase>\n";
4820 *stream <<
" <" << kTestsuite;
4827 stream, kTestsuite,
"disabled",
4839 *stream <<
" </" << kTestsuite <<
">\n";
4847 *stream <<
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
4848 *stream <<
"<" << kTestsuites;
4855 stream, kTestsuites,
"disabled",
4859 stream, kTestsuites,
"timestamp",
4878 *stream <<
"</" << kTestsuites <<
">\n";
4888 attributes <<
" " <<
property.key() <<
"="
4896 #if GTEST_CAN_STREAM_RESULTS_
4903 string StreamingListener::UrlEncode(
const char* str) {
4905 result.reserve(strlen(str) + 1);
4906 for (
char ch = *str; ch !=
'\0'; ch = *++str) {
4915 result.push_back(ch);
4922 void StreamingListener::SocketWriter::MakeConnection() {
4924 <<
"MakeConnection() can't be called when there is already a connection.";
4927 memset(&hints, 0,
sizeof(hints));
4928 hints.ai_family = AF_UNSPEC;
4929 hints.ai_socktype = SOCK_STREAM;
4930 addrinfo* servinfo = NULL;
4934 const int error_num = getaddrinfo(
4935 host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
4936 if (error_num != 0) {
4937 GTEST_LOG_(WARNING) <<
"stream_result_to: getaddrinfo() failed: "
4938 << gai_strerror(error_num);
4942 for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != NULL;
4943 cur_addr = cur_addr->ai_next) {
4945 cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol);
4946 if (sockfd_ != -1) {
4948 if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
4955 freeaddrinfo(servinfo);
4957 if (sockfd_ == -1) {
4958 GTEST_LOG_(WARNING) <<
"stream_result_to: failed to connect to "
4959 << host_name_ <<
":" << port_num_;
4964 #endif // GTEST_CAN_STREAM_RESULTS__
4975 trace.
message = message.GetString();
5017 if (premature_exit_filepath != NULL && *premature_exit_filepath !=
'\0') {
5021 FILE* pfile =
posix::FOpen(premature_exit_filepath,
"w");
5022 fwrite(
"0", 1, 1, pfile);
5044 : repeater_(new internal::TestEventRepeater()),
5045 default_result_printer_(NULL),
5046 default_xml_generator_(NULL) {
5085 if (listener != NULL)
5101 if (listener != NULL)
5137 #if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
5143 #endif // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
5263 const char* file_name,
5271 if (impl_->gtest_trace_stack().size() > 0) {
5274 for (
int i =
static_cast<int>(impl_->gtest_trace_stack().size());
5282 if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) {
5288 msg.GetString().c_str());
5289 impl_->GetTestPartResultReporterForCurrentThread()->
5290 ReportTestPartResult(result);
5299 #if GTEST_OS_WINDOWS
5309 *
static_cast<volatile int*
>(NULL) = 1;
5310 #endif // GTEST_OS_WINDOWS
5312 #if GTEST_HAS_EXCEPTIONS
5313 throw internal::GoogleTestFailureException(result);
5339 const bool in_death_test_child_process =
5364 in_death_test_child_process ?
5376 if (
impl()->catch_exceptions() || in_death_test_child_process) {
5377 # if !GTEST_OS_WINDOWS_MOBILE
5379 SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
5380 SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
5381 # endif // !GTEST_OS_WINDOWS_MOBILE
5383 # if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
5387 _set_error_mode(_OUT_TO_STDERR);
5390 # if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
5403 _set_abort_behavior(
5405 _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
5408 #endif // GTEST_HAS_SEH
5413 "auxiliary test code (environments or event listeners)") ? 0 : 1;
5441 #if GTEST_HAS_PARAM_TEST
5447 return impl_->parameterized_test_registry();
5449 #endif // GTEST_HAS_PARAM_TEST
5466 impl_->gtest_trace_stack().push_back(trace);
5476 namespace internal {
5481 # pragma warning(push)
5482 # pragma warning(disable:4355)
5484 default_global_test_part_result_reporter_(this),
5485 default_per_thread_test_part_result_reporter_(this),
5486 # pragma warning(pop)
5488 default_global_test_part_result_reporter_(this),
5489 default_per_thread_test_part_result_reporter_(this),
5491 global_test_part_result_repoter_(
5492 &default_global_test_part_result_reporter_),
5493 per_thread_test_part_result_reporter_(
5494 &default_per_thread_test_part_result_reporter_),
5496 parameterized_test_registry_(),
5497 parameterized_tests_registered_(false),
5499 last_death_test_case_(-1),
5500 current_test_case_(NULL),
5501 current_test_info_(NULL),
5502 ad_hoc_test_result_(),
5503 os_stack_trace_getter_(NULL),
5504 post_flag_parse_init_performed_(false),
5507 start_timestamp_(0),
5509 #if GTEST_HAS_DEATH_TEST
5510 death_test_factory_(new DefaultDeathTestFactory),
5513 catch_exceptions_(false) {
5537 xml_element =
"testcase";
5540 xml_element =
"testsuite";
5543 xml_element =
"testsuites";
5549 #if GTEST_HAS_DEATH_TEST
5552 void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
5553 if (internal_run_death_test_flag_.get() != NULL)
5556 #endif // GTEST_HAS_DEATH_TEST
5562 if (output_format ==
"xml") {
5565 }
else if (output_format !=
"") {
5566 printf(
"WARNING: unrecognized output format \"%s\" ignored.\n",
5567 output_format.c_str());
5572 #if GTEST_CAN_STREAM_RESULTS_
5575 void UnitTestImpl::ConfigureStreamingOutput() {
5577 if (!target.empty()) {
5578 const size_t pos = target.find(
':');
5579 if (pos != std::string::npos) {
5581 target.substr(pos+1)));
5583 printf(
"WARNING: unrecognized streaming target \"%s\" ignored.\n",
5589 #endif // GTEST_CAN_STREAM_RESULTS_
5601 #if GTEST_HAS_DEATH_TEST
5602 InitDeathTestSubprocessControlInfo();
5603 SuppressTestEventsIfInSubprocess();
5604 #endif // GTEST_HAS_DEATH_TEST
5615 #if GTEST_CAN_STREAM_RESULTS_
5617 ConfigureStreamingOutput();
5618 #endif // GTEST_CAN_STREAM_RESULTS_
5638 return test_case != NULL && strcmp(test_case->
name(),
name_.c_str()) == 0;
5658 const char* type_param,
5662 const std::vector<TestCase*>::const_iterator test_case =
5671 new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc);
5689 return new_test_case;
5710 "\nThis test program did NOT call ::testing::InitGoogleTest "
5711 "before calling RUN_ALL_TESTS(). Please fix it.\n");
5730 bool in_subprocess_for_death_test =
false;
5732 #if GTEST_HAS_DEATH_TEST
5733 in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL);
5734 #endif // GTEST_HAS_DEATH_TEST
5737 in_subprocess_for_death_test);
5741 const bool has_tests_to_run =
FilterTests(should_shard
5756 bool failed =
false;
5765 const int repeat = in_subprocess_for_death_test ? 1 :
GTEST_FLAG(repeat);
5767 const bool forever = repeat < 0;
5768 for (
int i = 0; forever || i != repeat; i++) {
5776 if (has_tests_to_run &&
GTEST_FLAG(shuffle)) {
5788 if (has_tests_to_run) {
5845 if (test_shard_file != NULL) {
5849 "Could not write to the test shard status file \"%s\" "
5850 "specified by the %s environment variable.\n",
5866 const char* shard_index_env,
5867 bool in_subprocess_for_death_test) {
5868 if (in_subprocess_for_death_test) {
5875 if (total_shards == -1 && shard_index == -1) {
5877 }
else if (total_shards == -1 && shard_index != -1) {
5879 <<
"Invalid environment variables: you have "
5885 }
else if (total_shards != -1 && shard_index == -1) {
5887 <<
"Invalid environment variables: you have "
5893 }
else if (shard_index < 0 || shard_index >= total_shards) {
5895 <<
"Invalid environment variables: we require 0 <= "
5904 return total_shards > 1;
5912 if (str_val == NULL) {
5918 str_val, &result)) {
5929 return (test_id % total_shards) == shard_index;
5949 int num_runnable_tests = 0;
5950 int num_selected_tests = 0;
5956 for (
size_t j = 0; j < test_case->
test_info_list().size(); j++) {
5961 const bool is_disabled =
5968 const bool matches_filter =
5973 const bool is_runnable =
5974 (
GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
5977 const bool is_selected = is_runnable &&
5980 num_runnable_tests));
5982 num_runnable_tests += is_runnable;
5983 num_selected_tests += is_selected;
5989 return num_selected_tests;
5998 for (
int i = 0; *str !=
'\0'; ++str) {
5999 if (i >= max_length) {
6017 const int kMaxParamLength = 250;
6021 bool printed_test_case_name =
false;
6023 for (
size_t j = 0; j < test_case->
test_info_list().size(); j++) {
6027 if (!printed_test_case_name) {
6028 printed_test_case_name =
true;
6029 printf(
"%s.", test_case->
name());
6038 printf(
" %s", test_info->
name());
6129 class ClassUniqueToAlwaysTrue {};
6132 bool IsTrue(
bool condition) {
return condition; }
6135 #if GTEST_HAS_EXCEPTIONS
6139 throw ClassUniqueToAlwaysTrue();
6140 #endif // GTEST_HAS_EXCEPTIONS
6148 const size_t prefix_len = strlen(prefix);
6149 if (strncmp(*pstr, prefix, prefix_len) == 0) {
6150 *pstr += prefix_len;
6163 bool def_optional) {
6165 if (str == NULL || flag == NULL)
return NULL;
6169 const size_t flag_len = flag_str.length();
6170 if (strncmp(str, flag_str.c_str(), flag_len) != 0)
return NULL;
6173 const char* flag_end = str + flag_len;
6176 if (def_optional && (flag_end[0] ==
'\0')) {
6183 if (flag_end[0] !=
'=')
return NULL;
6186 return flag_end + 1;
6204 if (value_str == NULL)
return false;
6207 *value = !(*value_str ==
'0' || *value_str ==
'f' || *value_str ==
'F');
6221 if (value_str == NULL)
return false;
6238 if (value_str == NULL)
return false;
6279 const char* p = strchr(str,
'@');
6287 const char ch = p[1];
6291 }
else if (ch ==
'D') {
6293 }
else if (ch ==
'R') {
6295 }
else if (ch ==
'G') {
6297 }
else if (ch ==
'Y') {
6306 "This program contains tests written using " GTEST_NAME_ ". You can use the\n"
6307 "following command line flags to control its behavior:\n"
6311 " List the names of all tests instead of running them. The name of\n"
6312 " TEST(Foo, Bar) is \"Foo.Bar\".\n"
6314 "[@G-@YNEGATIVE_PATTERNS]@D\n"
6315 " Run only the tests whose name matches one of the positive patterns but\n"
6316 " none of the negative patterns. '?' matches any single character; '*'\n"
6317 " matches any substring; ':' separates two patterns.\n"
6319 " Run all disabled tests too.\n"
6323 " Run the tests repeatedly; use a negative count to repeat forever.\n"
6325 " Randomize tests' orders on every iteration.\n"
6327 " Random number seed to use for shuffling test orders (between 1 and\n"
6328 " 99999, or 0 to use a seed based on the current time).\n"
6332 " Enable/disable colored output. The default is @Gauto@D.\n"
6334 " Don't print the elapsed time of each test.\n"
6337 " Generate an XML report in the given directory or with the given file\n"
6338 " name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n"
6339 #if GTEST_CAN_STREAM_RESULTS_
6341 " Stream test results to the given server.\n"
6342 #endif // GTEST_CAN_STREAM_RESULTS_
6344 "Assertion Behavior:\n"
6345 #if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
6347 " Set the default death test style.\n"
6348 #endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
6350 " Turn assertion failures into debugger break-points.\n"
6352 " Turn assertion failures into C++ exceptions.\n"
6354 " Do not report exceptions as test failures. Instead, allow them\n"
6355 " to crash the program or throw a pop-up (on Windows).\n"
6358 "the corresponding\n"
6359 "environment variable of a flag (all letters in upper-case). For example, to\n"
6361 "color=no@D or set\n"
6364 "For more information, please read the " GTEST_NAME_ " documentation at\n"
6366 "(not one in your own code or tests), please report it to\n"
6372 template <
typename CharType>
6374 for (
int i = 1; i < *argc; i++) {
6376 const char*
const arg = arg_string.c_str();
6414 for (
int j = i; j != *argc; j++) {
6415 argv[j] = argv[j + 1];
6424 }
else if (arg_string ==
"--help" || arg_string ==
"-h" ||
6425 arg_string ==
"-?" || arg_string ==
"/?" ||
6454 template <
typename CharType>
6461 if (*argc <= 0)
return;
6465 #if GTEST_HAS_DEATH_TEST
6468 for (
int i = 0; i != *argc; i++) {
6472 #endif // GTEST_HAS_DEATH_TEST
6534 #if GTEST_HAS_DEATH_TEST
6537 # include <crt_externs.h>
6538 # endif // GTEST_OS_MAC
6542 # include <limits.h>
6545 # include <signal.h>
6546 # endif // GTEST_OS_LINUX
6548 # include <stdarg.h>
6550 # if GTEST_OS_WINDOWS
6551 # include <windows.h>
6553 # include <sys/mman.h>
6554 # include <sys/wait.h>
6555 # endif // GTEST_OS_WINDOWS
6559 # endif // GTEST_OS_QNX
6561 #endif // GTEST_HAS_DEATH_TEST
6569 #define GTEST_IMPLEMENTATION_ 1
6570 #undef GTEST_IMPLEMENTATION_
6582 "Indicates how to run a death test in a forked child process: "
6583 "\"threadsafe\" (child process re-executes the test binary "
6584 "from the beginning, running only the specific death test) or "
6585 "\"fast\" (child process runs the death test immediately "
6589 death_test_use_fork,
6591 "Instructs to use fork()/_exit() instead of clone() in death tests. "
6592 "Ignored and always uses fork() on POSIX systems where clone() is not "
6593 "implemented. Useful when running under valgrind or similar tools if "
6594 "those do not support clone(). Valgrind 3.3.1 will just fail if "
6595 "it sees an unsupported combination of clone() flags. "
6596 "It is not recommended to use this flag w/o valgrind though it will "
6597 "work in 99% of the cases. Once valgrind is fixed, this flag will "
6598 "most likely be removed.");
6600 namespace internal {
6602 internal_run_death_test,
"",
6603 "Indicates the file, line number, temporal index of "
6604 "the single death test to run, and a file descriptor to "
6605 "which a success code may be sent, all separated by "
6606 "the '|' characters. This flag is specified if and only if the current "
6607 "process is a sub-process launched for running a thread-safe "
6608 "death test. FOR INTERNAL USE ONLY.");
6611 #if GTEST_HAS_DEATH_TEST
6613 namespace internal {
6617 static bool g_in_fast_death_test_child =
false;
6624 bool InDeathTestChild() {
6625 # if GTEST_OS_WINDOWS
6629 return !
GTEST_FLAG(internal_run_death_test).empty();
6633 if (
GTEST_FLAG(death_test_style) ==
"threadsafe")
6634 return !
GTEST_FLAG(internal_run_death_test).empty();
6636 return g_in_fast_death_test_child;
6643 ExitedWithCode::ExitedWithCode(
int exit_code) : exit_code_(exit_code) {
6647 bool ExitedWithCode::operator()(
int exit_status)
const {
6648 # if GTEST_OS_WINDOWS
6650 return exit_status == exit_code_;
6654 return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;
6656 # endif // GTEST_OS_WINDOWS
6659 # if !GTEST_OS_WINDOWS
6661 KilledBySignal::KilledBySignal(
int signum) : signum_(signum) {
6665 bool KilledBySignal::operator()(
int exit_status)
const {
6666 return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;
6668 # endif // !GTEST_OS_WINDOWS
6670 namespace internal {
6679 # if GTEST_OS_WINDOWS
6681 m <<
"Exited with exit status " << exit_code;
6685 if (WIFEXITED(exit_code)) {
6686 m <<
"Exited with exit status " << WEXITSTATUS(exit_code);
6687 }
else if (WIFSIGNALED(exit_code)) {
6688 m <<
"Terminated by signal " << WTERMSIG(exit_code);
6691 if (WCOREDUMP(exit_code)) {
6692 m <<
" (core dumped)";
6695 # endif // GTEST_OS_WINDOWS
6697 return m.GetString();
6702 bool ExitedUnsuccessfully(
int exit_status) {
6703 return !ExitedWithCode(0)(exit_status);
6706 # if !GTEST_OS_WINDOWS
6711 static std::string DeathTestThreadWarning(
size_t thread_count) {
6713 msg <<
"Death tests use fork(), which is unsafe particularly"
6714 <<
" in a threaded context. For this test, " <<
GTEST_NAME_ <<
" ";
6715 if (thread_count == 0)
6716 msg <<
"couldn't detect the number of threads.";
6718 msg <<
"detected " << thread_count <<
" threads.";
6719 return msg.GetString();
6721 # endif // !GTEST_OS_WINDOWS
6724 static const char kDeathTestLived =
'L';
6725 static const char kDeathTestReturned =
'R';
6726 static const char kDeathTestThrew =
'T';
6727 static const char kDeathTestInternalError =
'I';
6738 enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW };
6749 const InternalRunDeathTestFlag*
const flag =
6753 fputc(kDeathTestInternalError, parent);
6754 fprintf(parent,
"%s", message.c_str());
6758 fprintf(stderr,
"%s", message.c_str());
6766 # define GTEST_DEATH_TEST_CHECK_(expression) \
6768 if (!::testing::internal::IsTrue(expression)) { \
6770 ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
6771 + ::testing::internal::StreamableToString(__LINE__) + ": " \
6774 } while (::testing::internal::AlwaysFalse())
6783 # define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
6787 gtest_retval = (expression); \
6788 } while (gtest_retval == -1 && errno == EINTR); \
6789 if (gtest_retval == -1) { \
6791 ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
6792 + ::testing::internal::StreamableToString(__LINE__) + ": " \
6793 + #expression + " != -1"); \
6795 } while (::testing::internal::AlwaysFalse())
6806 static void FailFromInternalError(
int fd) {
6812 while ((num_read =
posix::Read(fd, buffer, 255)) > 0) {
6813 buffer[num_read] =
'\0';
6816 }
while (num_read == -1 && errno == EINTR);
6818 if (num_read == 0) {
6821 const int last_error = errno;
6822 GTEST_LOG_(FATAL) <<
"Error while reading death test internal: "
6823 << GetLastErrnoDescription() <<
" [" << last_error <<
"]";
6829 DeathTest::DeathTest() {
6832 DeathTestAbort(
"Cannot run a death test outside of a TEST or "
6833 "TEST_F construct");
6839 bool DeathTest::Create(
const char* statement,
const RE* regex,
6840 const char* file,
int line, DeathTest**
test) {
6842 statement, regex, file, line,
test);
6845 const char* DeathTest::LastMessage() {
6846 return last_death_test_message_.c_str();
6849 void DeathTest::set_last_death_test_message(
const std::string& message) {
6850 last_death_test_message_ = message;
6856 class DeathTestImpl :
public DeathTest {
6858 DeathTestImpl(
const char* a_statement,
const RE* a_regex)
6859 : statement_(a_statement),
6863 outcome_(IN_PROGRESS),
6868 ~DeathTestImpl() { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); }
6870 void Abort(AbortReason reason);
6871 virtual bool Passed(
bool status_ok);
6873 const char* statement()
const {
return statement_; }
6874 const RE* regex()
const {
return regex_; }
6875 bool spawned()
const {
return spawned_; }
6876 void set_spawned(
bool is_spawned) { spawned_ = is_spawned; }
6877 int status()
const {
return status_; }
6878 void set_status(
int a_status) { status_ = a_status; }
6879 DeathTestOutcome outcome()
const {
return outcome_; }
6880 void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; }
6881 int read_fd()
const {
return read_fd_; }
6882 void set_read_fd(
int fd) { read_fd_ = fd; }
6883 int write_fd()
const {
return write_fd_; }
6884 void set_write_fd(
int fd) { write_fd_ = fd; }
6890 void ReadAndInterpretStatusByte();
6895 const char*
const statement_;
6898 const RE*
const regex_;
6904 DeathTestOutcome outcome_;
6919 void DeathTestImpl::ReadAndInterpretStatusByte() {
6929 }
while (bytes_read == -1 && errno == EINTR);
6931 if (bytes_read == 0) {
6933 }
else if (bytes_read == 1) {
6935 case kDeathTestReturned:
6936 set_outcome(RETURNED);
6938 case kDeathTestThrew:
6941 case kDeathTestLived:
6944 case kDeathTestInternalError:
6945 FailFromInternalError(read_fd());
6948 GTEST_LOG_(FATAL) <<
"Death test child process reported "
6949 <<
"unexpected status byte ("
6950 <<
static_cast<unsigned int>(flag) <<
")";
6953 GTEST_LOG_(FATAL) <<
"Read from death test child process failed: "
6954 << GetLastErrnoDescription();
6956 GTEST_DEATH_TEST_CHECK_SYSCALL_(
posix::Close(read_fd()));
6968 const char status_ch =
6969 reason == TEST_DID_NOT_DIE ? kDeathTestLived :
6970 reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned;
6972 GTEST_DEATH_TEST_CHECK_SYSCALL_(
posix::Write(write_fd(), &status_ch, 1));
6989 for (
size_t at = 0; ; ) {
6990 const size_t line_end = output.find(
'\n', at);
6991 ret +=
"[ DEATH ] ";
6992 if (line_end == ::std::string::npos) {
6993 ret += output.substr(at);
6996 ret += output.substr(at, line_end + 1 - at);
7024 bool DeathTestImpl::Passed(
bool status_ok) {
7030 bool success =
false;
7033 buffer <<
"Death test: " << statement() <<
"\n";
7034 switch (outcome()) {
7036 buffer <<
" Result: failed to die.\n"
7037 <<
" Error msg:\n" << FormatDeathTestOutput(error_message);
7040 buffer <<
" Result: threw an exception.\n"
7041 <<
" Error msg:\n" << FormatDeathTestOutput(error_message);
7044 buffer <<
" Result: illegal return in test statement.\n"
7045 <<
" Error msg:\n" << FormatDeathTestOutput(error_message);
7049 const bool matched = RE::PartialMatch(error_message.c_str(), *regex());
7053 buffer <<
" Result: died but not with expected error.\n"
7054 <<
" Expected: " << regex()->pattern() <<
"\n"
7055 <<
"Actual msg:\n" << FormatDeathTestOutput(error_message);
7058 buffer <<
" Result: died but not with expected exit code:\n"
7059 <<
" " << ExitSummary(status()) <<
"\n"
7060 <<
"Actual msg:\n" << FormatDeathTestOutput(error_message);
7066 <<
"DeathTest::Passed somehow called before conclusion of test";
7069 DeathTest::set_last_death_test_message(buffer.GetString());
7073 # if GTEST_OS_WINDOWS
7102 class WindowsDeathTest :
public DeathTestImpl {
7104 WindowsDeathTest(
const char* a_statement,
7108 : DeathTestImpl(a_statement, a_regex), file_(file), line_(line) {}
7112 virtual TestRole AssumeRole();
7116 const char*
const file_;
7120 AutoHandle write_handle_;
7122 AutoHandle child_handle_;
7127 AutoHandle event_handle_;
7133 int WindowsDeathTest::Wait() {
7139 const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() };
7140 switch (::WaitForMultipleObjects(2,
7145 case WAIT_OBJECT_0 + 1:
7148 GTEST_DEATH_TEST_CHECK_(
false);
7153 write_handle_.Reset();
7154 event_handle_.Reset();
7156 ReadAndInterpretStatusByte();
7162 GTEST_DEATH_TEST_CHECK_(
7163 WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(),
7166 GTEST_DEATH_TEST_CHECK_(
7167 ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE);
7168 child_handle_.Reset();
7169 set_status(
static_cast<int>(status_code));
7178 DeathTest::TestRole WindowsDeathTest::AssumeRole() {
7180 const InternalRunDeathTestFlag*
const flag =
7181 impl->internal_run_death_test_flag();
7182 const TestInfo*
const info = impl->current_test_info();
7183 const int death_test_index = info->result()->death_test_count();
7188 set_write_fd(flag->write_fd());
7189 return EXECUTE_TEST;
7194 SECURITY_ATTRIBUTES handles_are_inheritable = {
7195 sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };
7196 HANDLE read_handle, write_handle;
7197 GTEST_DEATH_TEST_CHECK_(
7198 ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable,
7201 set_read_fd(::_open_osfhandle(
reinterpret_cast<intptr_t
>(read_handle),
7203 write_handle_.Reset(write_handle);
7204 event_handle_.Reset(::CreateEvent(
7205 &handles_are_inheritable,
7209 GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL);
7212 info->test_case_name() +
"." + info->name();
7224 char executable_path[_MAX_PATH + 1];
7225 GTEST_DEATH_TEST_CHECK_(
7226 _MAX_PATH + 1 != ::GetModuleFileNameA(NULL,
7231 std::string(::GetCommandLineA()) +
" " + filter_flag +
" \"" +
7232 internal_flag +
"\"";
7234 DeathTest::set_last_death_test_message(
"");
7241 STARTUPINFOA startup_info;
7242 memset(&startup_info, 0,
sizeof(STARTUPINFO));
7243 startup_info.dwFlags = STARTF_USESTDHANDLES;
7244 startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE);
7245 startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE);
7246 startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE);
7248 PROCESS_INFORMATION process_info;
7249 GTEST_DEATH_TEST_CHECK_(::CreateProcessA(
7251 const_cast<char*
>(command_line.c_str()),
7257 UnitTest::GetInstance()->original_working_dir(),
7259 &process_info) != FALSE);
7260 child_handle_.Reset(process_info.hProcess);
7261 ::CloseHandle(process_info.hThread);
7263 return OVERSEE_TEST;
7265 # else // We are not on Windows.
7270 class ForkingDeathTest :
public DeathTestImpl {
7272 ForkingDeathTest(
const char* statement,
const RE* regex);
7278 void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; }
7286 ForkingDeathTest::ForkingDeathTest(
const char* a_statement,
const RE* a_regex)
7287 : DeathTestImpl(a_statement, a_regex),
7293 int ForkingDeathTest::Wait() {
7297 ReadAndInterpretStatusByte();
7300 GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0));
7301 set_status(status_value);
7302 return status_value;
7307 class NoExecDeathTest :
public ForkingDeathTest {
7309 NoExecDeathTest(
const char* a_statement,
const RE* a_regex) :
7310 ForkingDeathTest(a_statement, a_regex) { }
7311 virtual TestRole AssumeRole();
7316 DeathTest::TestRole NoExecDeathTest::AssumeRole() {
7318 if (thread_count != 1) {
7319 GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count);
7323 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
7325 DeathTest::set_last_death_test_message(
"");
7336 const pid_t child_pid = fork();
7337 GTEST_DEATH_TEST_CHECK_(child_pid != -1);
7338 set_child_pid(child_pid);
7339 if (child_pid == 0) {
7340 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0]));
7341 set_write_fd(pipe_fd[1]);
7349 g_in_fast_death_test_child =
true;
7350 return EXECUTE_TEST;
7352 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
7353 set_read_fd(pipe_fd[0]);
7355 return OVERSEE_TEST;
7362 class ExecDeathTest :
public ForkingDeathTest {
7364 ExecDeathTest(
const char* a_statement,
const RE* a_regex,
7365 const char* file,
int line) :
7366 ForkingDeathTest(a_statement, a_regex), file_(file), line_(line) { }
7367 virtual TestRole AssumeRole();
7369 static ::std::vector<testing::internal::string>
7370 GetArgvsForDeathTestChildProcess() {
7371 ::std::vector<testing::internal::string> args = GetInjectableArgvs();
7375 const char*
const file_;
7384 args_.push_back(NULL);
7388 for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
7393 void AddArgument(
const char* argument) {
7397 template <
typename Str>
7398 void AddArguments(const ::std::vector<Str>& arguments) {
7399 for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
7400 i != arguments.end();
7405 char*
const* Argv() {
7410 std::vector<char*> args_;
7415 struct ExecDeathTestArgs {
7421 inline char** GetEnviron() {
7425 return *_NSGetEnviron();
7430 extern "C" char** environ;
7431 inline char** GetEnviron() {
return environ; }
7432 # endif // GTEST_OS_MAC
7438 static int ExecDeathTestChildMain(
void* child_arg) {
7439 ExecDeathTestArgs*
const args =
static_cast<ExecDeathTestArgs*
>(child_arg);
7440 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd));
7445 const char*
const original_dir =
7446 UnitTest::GetInstance()->original_working_dir();
7448 if (chdir(original_dir) != 0) {
7449 DeathTestAbort(
std::string(
"chdir(\"") + original_dir +
"\") failed: " +
7450 GetLastErrnoDescription());
7451 return EXIT_FAILURE;
7459 execve(args->argv[0], args->argv, GetEnviron());
7460 DeathTestAbort(
std::string(
"execve(") + args->argv[0] +
", ...) in " +
7461 original_dir +
" failed: " +
7462 GetLastErrnoDescription());
7463 return EXIT_FAILURE;
7465 # endif // !GTEST_OS_QNX
7476 void StackLowerThanAddress(
const void* ptr,
bool* result)
GTEST_NO_INLINE_;
7477 void StackLowerThanAddress(
const void* ptr,
bool* result) {
7479 *result = (&dummy < ptr);
7482 bool StackGrowsDown() {
7485 StackLowerThanAddress(&dummy, &result);
7496 static pid_t ExecDeathTestSpawnChild(
char*
const* argv,
int close_fd) {
7497 ExecDeathTestArgs args = { argv,
close_fd };
7498 pid_t child_pid = -1;
7503 const int cwd_fd = open(
".", O_RDONLY);
7504 GTEST_DEATH_TEST_CHECK_(cwd_fd != -1);
7505 GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC));
7509 const char*
const original_dir =
7510 UnitTest::GetInstance()->original_working_dir();
7512 if (chdir(original_dir) != 0) {
7513 DeathTestAbort(
std::string(
"chdir(\"") + original_dir +
"\") failed: " +
7514 GetLastErrnoDescription());
7515 return EXIT_FAILURE;
7520 GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD));
7521 GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD,
7522 fd_flags | FD_CLOEXEC));
7523 struct inheritance inherit = {0};
7525 child_pid = spawn(args.argv[0], 0, NULL, &inherit, args.argv, GetEnviron());
7527 GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1);
7528 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));
7530 # else // GTEST_OS_QNX
7535 struct sigaction saved_sigprof_action;
7536 struct sigaction ignore_sigprof_action;
7537 memset(&ignore_sigprof_action, 0,
sizeof(ignore_sigprof_action));
7538 sigemptyset(&ignore_sigprof_action.sa_mask);
7539 ignore_sigprof_action.sa_handler = SIG_IGN;
7540 GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction(
7541 SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));
7542 # endif // GTEST_OS_LINUX
7544 # if GTEST_HAS_CLONE
7545 const bool use_fork =
GTEST_FLAG(death_test_use_fork);
7548 static const bool stack_grows_down = StackGrowsDown();
7549 const size_t stack_size = getpagesize();
7551 void*
const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE,
7552 MAP_ANON | MAP_PRIVATE, -1, 0);
7553 GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED);
7561 const size_t kMaxStackAlignment = 64;
7562 void*
const stack_top =
7563 static_cast<char*
>(stack) +
7564 (stack_grows_down ? stack_size - kMaxStackAlignment : 0);
7565 GTEST_DEATH_TEST_CHECK_(stack_size > kMaxStackAlignment &&
7566 reinterpret_cast<intptr_t
>(stack_top) % kMaxStackAlignment == 0);
7568 child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args);
7570 GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);
7573 const bool use_fork =
true;
7574 # endif // GTEST_HAS_CLONE
7576 if (use_fork && (child_pid = fork()) == 0) {
7577 ExecDeathTestChildMain(&args);
7580 # endif // GTEST_OS_QNX
7582 GTEST_DEATH_TEST_CHECK_SYSCALL_(
7583 sigaction(SIGPROF, &saved_sigprof_action, NULL));
7584 # endif // GTEST_OS_LINUX
7586 GTEST_DEATH_TEST_CHECK_(child_pid != -1);
7594 DeathTest::TestRole ExecDeathTest::AssumeRole() {
7596 const InternalRunDeathTestFlag*
const flag =
7597 impl->internal_run_death_test_flag();
7598 const TestInfo*
const info = impl->current_test_info();
7599 const int death_test_index = info->result()->death_test_count();
7602 set_write_fd(flag->write_fd());
7603 return EXECUTE_TEST;
7607 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
7610 GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
7614 + info->test_case_name() +
"." + info->name();
7621 args.AddArguments(GetArgvsForDeathTestChildProcess());
7622 args.AddArgument(filter_flag.c_str());
7623 args.AddArgument(internal_flag.c_str());
7625 DeathTest::set_last_death_test_message(
"");
7632 const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]);
7633 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
7634 set_child_pid(child_pid);
7635 set_read_fd(pipe_fd[0]);
7637 return OVERSEE_TEST;
7640 # endif // !GTEST_OS_WINDOWS
7647 bool DefaultDeathTestFactory::Create(
const char* statement,
const RE* regex,
7648 const char* file,
int line,
7651 const InternalRunDeathTestFlag*
const flag =
7652 impl->internal_run_death_test_flag();
7653 const int death_test_index = impl->current_test_info()
7654 ->increment_death_test_count();
7657 if (death_test_index > flag->index()) {
7658 DeathTest::set_last_death_test_message(
7660 +
") somehow exceeded expected maximum ("
7665 if (!(flag->file() == file && flag->line() == line &&
7666 flag->index() == death_test_index)) {
7672 # if GTEST_OS_WINDOWS
7674 if (
GTEST_FLAG(death_test_style) ==
"threadsafe" ||
7676 *
test =
new WindowsDeathTest(statement, regex, file, line);
7681 if (
GTEST_FLAG(death_test_style) ==
"threadsafe") {
7682 *
test =
new ExecDeathTest(statement, regex, file, line);
7683 }
else if (
GTEST_FLAG(death_test_style) ==
"fast") {
7684 *
test =
new NoExecDeathTest(statement, regex);
7687 # endif // GTEST_OS_WINDOWS
7690 DeathTest::set_last_death_test_message(
7691 "Unknown death test style \"" +
GTEST_FLAG(death_test_style)
7692 +
"\" encountered");
7703 ::std::vector< ::std::string>* dest) {
7704 ::std::vector< ::std::string> parsed;
7705 ::std::string::size_type pos = 0;
7707 const ::std::string::size_type colon = str.find(delimiter, pos);
7708 if (colon == ::std::string::npos) {
7709 parsed.push_back(str.substr(pos));
7712 parsed.push_back(str.substr(pos, colon - pos));
7719 # if GTEST_OS_WINDOWS
7723 int GetStatusFileDescriptor(
unsigned int parent_process_id,
7724 size_t write_handle_as_size_t,
7725 size_t event_handle_as_size_t) {
7726 AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,
7728 parent_process_id));
7729 if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {
7730 DeathTestAbort(
"Unable to open parent process " +
7738 const HANDLE write_handle =
7739 reinterpret_cast<HANDLE
>(write_handle_as_size_t);
7740 HANDLE dup_write_handle;
7745 if (!::DuplicateHandle(parent_process_handle.Get(), write_handle,
7746 ::GetCurrentProcess(), &dup_write_handle,
7750 DUPLICATE_SAME_ACCESS)) {
7751 DeathTestAbort(
"Unable to duplicate the pipe handle " +
7753 " from the parent process " +
7757 const HANDLE event_handle =
reinterpret_cast<HANDLE
>(event_handle_as_size_t);
7758 HANDLE dup_event_handle;
7760 if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,
7761 ::GetCurrentProcess(), &dup_event_handle,
7764 DUPLICATE_SAME_ACCESS)) {
7765 DeathTestAbort(
"Unable to duplicate the event handle " +
7767 " from the parent process " +
7771 const int write_fd =
7772 ::_open_osfhandle(
reinterpret_cast<intptr_t
>(dup_write_handle), O_APPEND);
7773 if (write_fd == -1) {
7774 DeathTestAbort(
"Unable to convert pipe handle " +
7776 " to a file descriptor");
7781 ::SetEvent(dup_event_handle);
7785 # endif // GTEST_OS_WINDOWS
7790 InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
7791 if (
GTEST_FLAG(internal_run_death_test) ==
"")
return NULL;
7797 ::std::vector< ::std::string> fields;
7798 SplitString(
GTEST_FLAG(internal_run_death_test).c_str(),
'|', &fields);
7801 # if GTEST_OS_WINDOWS
7803 unsigned int parent_process_id = 0;
7804 size_t write_handle_as_size_t = 0;
7805 size_t event_handle_as_size_t = 0;
7807 if (fields.size() != 6
7808 || !ParseNaturalNumber(fields[1], &line)
7809 || !ParseNaturalNumber(fields[2], &index)
7810 || !ParseNaturalNumber(fields[3], &parent_process_id)
7811 || !ParseNaturalNumber(fields[4], &write_handle_as_size_t)
7812 || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
7813 DeathTestAbort(
"Bad --gtest_internal_run_death_test flag: " +
7816 write_fd = GetStatusFileDescriptor(parent_process_id,
7817 write_handle_as_size_t,
7818 event_handle_as_size_t);
7821 if (fields.size() != 4
7822 || !ParseNaturalNumber(fields[1], &line)
7823 || !ParseNaturalNumber(fields[2], &index)
7824 || !ParseNaturalNumber(fields[3], &write_fd)) {
7825 DeathTestAbort(
"Bad --gtest_internal_run_death_test flag: "
7829 # endif // GTEST_OS_WINDOWS
7831 return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);
7836 #endif // GTEST_HAS_DEATH_TEST
7873 #if GTEST_OS_WINDOWS_MOBILE
7874 # include <windows.h>
7875 #elif GTEST_OS_WINDOWS
7876 # include <direct.h>
7878 #elif GTEST_OS_SYMBIAN
7880 # include <sys/syslimits.h>
7882 # include <limits.h>
7884 #endif // GTEST_OS_WINDOWS_MOBILE
7886 #if GTEST_OS_WINDOWS
7887 # define GTEST_PATH_MAX_ _MAX_PATH
7888 #elif defined(PATH_MAX)
7889 # define GTEST_PATH_MAX_ PATH_MAX
7890 #elif defined(_XOPEN_PATH_MAX)
7891 # define GTEST_PATH_MAX_ _XOPEN_PATH_MAX
7893 # define GTEST_PATH_MAX_ _POSIX_PATH_MAX
7894 #endif // GTEST_OS_WINDOWS
7898 namespace internal {
7900 #if GTEST_OS_WINDOWS
7906 const char kAlternatePathSeparator =
'/';
7908 const char kAlternatePathSeparatorString[] =
"/";
7909 # if GTEST_OS_WINDOWS_MOBILE
7915 const DWORD kInvalidFileAttributes = 0xffffffff;
7918 # endif // GTEST_OS_WINDOWS_MOBILE
7923 #endif // GTEST_OS_WINDOWS
7927 #if GTEST_HAS_ALT_PATH_SEP_
7936 #if GTEST_OS_WINDOWS_MOBILE
7940 #elif GTEST_OS_WINDOWS
7942 return FilePath(_getcwd(cwd,
sizeof(cwd)) == NULL ?
"" : cwd);
7945 return FilePath(getcwd(cwd,
sizeof(cwd)) == NULL ?
"" : cwd);
7946 #endif // GTEST_OS_WINDOWS_MOBILE
7957 0,
pathname_.length() - dot_extension.length()));
7967 #if GTEST_HAS_ALT_PATH_SEP_
7968 const char*
const last_alt_sep = strrchr(
c_str(), kAlternatePathSeparator);
7970 if (last_alt_sep != NULL &&
7971 (last_sep == NULL || last_alt_sep > last_sep)) {
7972 return last_alt_sep;
7986 return last_sep ?
FilePath(last_sep + 1) : *
this;
8015 const char* extension) {
8018 file = base_name.
string() +
"." + extension;
8031 return relative_path;
8039 #if GTEST_OS_WINDOWS_MOBILE
8040 LPCWSTR unicode = String::AnsiToUtf16(
pathname_.c_str());
8041 const DWORD attributes = GetFileAttributes(unicode);
8043 return attributes != kInvalidFileAttributes;
8047 #endif // GTEST_OS_WINDOWS_MOBILE
8053 bool result =
false;
8054 #if GTEST_OS_WINDOWS
8063 #if GTEST_OS_WINDOWS_MOBILE
8064 LPCWSTR unicode = String::AnsiToUtf16(path.
c_str());
8065 const DWORD attributes = GetFileAttributes(unicode);
8067 if ((attributes != kInvalidFileAttributes) &&
8068 (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
8075 #endif // GTEST_OS_WINDOWS_MOBILE
8083 #if GTEST_OS_WINDOWS
8095 const char*
const name =
pathname_.c_str();
8096 #if GTEST_OS_WINDOWS
8098 ((name[0] >=
'a' && name[0] <=
'z') ||
8099 (name[0] >=
'A' && name[0] <=
'Z')) &&
8117 const char* extension) {
8121 full_pathname.
Set(
MakeFileName(directory, base_name, number++, extension));
8123 return full_pathname;
8142 if (
pathname_.length() == 0 || this->DirectoryExists()) {
8155 #if GTEST_OS_WINDOWS_MOBILE
8157 LPCWSTR unicode = String::AnsiToUtf16(removed_sep.
c_str());
8158 int result = CreateDirectory(unicode, NULL) ? 0 : -1;
8160 #elif GTEST_OS_WINDOWS
8163 int result = mkdir(
pathname_.c_str(), 0777);
8164 #endif // GTEST_OS_WINDOWS_MOBILE
8191 char*
const dest =
new char[
pathname_.length() + 1];
8192 char* dest_ptr = dest;
8193 memset(dest_ptr, 0,
pathname_.length() + 1);
8195 while (*src !=
'\0') {
8200 #if GTEST_HAS_ALT_PATH_SEP_
8201 if (*dest_ptr == kAlternatePathSeparator) {
8254 #if GTEST_OS_WINDOWS_MOBILE
8255 # include <windows.h>
8256 #elif GTEST_OS_WINDOWS
8258 # include <sys/stat.h>
8260 # include <unistd.h>
8261 #endif // GTEST_OS_WINDOWS_MOBILE
8264 # include <mach/mach_init.h>
8265 # include <mach/task.h>
8266 # include <mach/vm_map.h>
8267 #endif // GTEST_OS_MAC
8270 # include <devctl.h>
8271 # include <sys/procfs.h>
8272 #endif // GTEST_OS_QNX
8280 #define GTEST_IMPLEMENTATION_ 1
8281 #undef GTEST_IMPLEMENTATION_
8284 namespace internal {
8286 #if defined(_MSC_VER) || defined(__BORLANDC__)
8300 const task_t task = mach_task_self();
8301 mach_msg_type_number_t thread_count;
8302 thread_act_array_t thread_list;
8303 const kern_return_t status = task_threads(task, &thread_list, &thread_count);
8304 if (status == KERN_SUCCESS) {
8308 reinterpret_cast<vm_address_t
>(thread_list),
8309 sizeof(thread_t) * thread_count);
8310 return static_cast<size_t>(thread_count);
8321 const int fd = open(
"/proc/self/as", O_RDONLY);
8325 procfs_info process_info;
8327 devctl(fd, DCMD_PROC_INFO, &process_info,
sizeof(process_info), NULL);
8329 if (status == EOK) {
8330 return static_cast<size_t>(process_info.num_threads);
8344 #endif // GTEST_OS_MAC
8346 #if GTEST_USES_POSIX_RE
8364 if (!re.is_valid_)
return false;
8367 return regexec(&re.full_regex_, str, 1, &match, 0) == 0;
8373 if (!re.is_valid_)
return false;
8376 return regexec(&re.partial_regex_, str, 1, &match, 0) == 0;
8385 const size_t full_regex_len = strlen(regex) + 10;
8386 char*
const full_pattern =
new char[full_regex_len];
8388 snprintf(full_pattern, full_regex_len,
"^(%s)$", regex);
8399 const char*
const partial_regex = (*regex ==
'\0') ?
"()" : regex;
8403 <<
"Regular expression \"" << regex
8404 <<
"\" is not a valid POSIX Extended regular expression.";
8406 delete[] full_pattern;
8409 #elif GTEST_USES_SIMPLE_RE
8413 bool IsInSet(
char ch,
const char* str) {
8414 return ch !=
'\0' && strchr(str, ch) != NULL;
8420 bool IsAsciiDigit(
char ch) {
return '0' <= ch && ch <=
'9'; }
8421 bool IsAsciiPunct(
char ch) {
8422 return IsInSet(ch,
"^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
8424 bool IsRepeat(
char ch) {
return IsInSet(ch,
"?*+"); }
8425 bool IsAsciiWhiteSpace(
char ch) {
return IsInSet(ch,
" \f\n\r\t\v"); }
8426 bool IsAsciiWordChar(
char ch) {
8427 return (
'a' <= ch && ch <=
'z') || (
'A' <= ch && ch <=
'Z') ||
8428 (
'0' <= ch && ch <=
'9') || ch ==
'_';
8432 bool IsValidEscape(
char c) {
8433 return (IsAsciiPunct(c) || IsInSet(c,
"dDfnrsStvwW"));
8438 bool AtomMatchesChar(
bool escaped,
char pattern_char,
char ch) {
8440 switch (pattern_char) {
8441 case 'd':
return IsAsciiDigit(ch);
8442 case 'D':
return !IsAsciiDigit(ch);
8443 case 'f':
return ch ==
'\f';
8444 case 'n':
return ch ==
'\n';
8445 case 'r':
return ch ==
'\r';
8446 case 's':
return IsAsciiWhiteSpace(ch);
8447 case 'S':
return !IsAsciiWhiteSpace(ch);
8448 case 't':
return ch ==
'\t';
8449 case 'v':
return ch ==
'\v';
8450 case 'w':
return IsAsciiWordChar(ch);
8451 case 'W':
return !IsAsciiWordChar(ch);
8453 return IsAsciiPunct(pattern_char) && pattern_char == ch;
8456 return (pattern_char ==
'.' && ch !=
'\n') || pattern_char == ch;
8460 std::string FormatRegexSyntaxError(
const char* regex,
int index) {
8461 return (Message() <<
"Syntax error at index " << index
8462 <<
" in simple regular expression \"" << regex <<
"\": ").GetString();
8467 bool ValidateRegex(
const char* regex) {
8468 if (regex == NULL) {
8472 ADD_FAILURE() <<
"NULL is not a valid simple regular expression.";
8476 bool is_valid =
true;
8479 bool prev_repeatable =
false;
8480 for (
int i = 0; regex[i]; i++) {
8481 if (regex[i] ==
'\\') {
8483 if (regex[i] ==
'\0') {
8484 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
8485 <<
"'\\' cannot appear at the end.";
8489 if (!IsValidEscape(regex[i])) {
8490 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
8491 <<
"invalid escape sequence \"\\" << regex[i] <<
"\".";
8494 prev_repeatable =
true;
8496 const char ch = regex[i];
8498 if (ch ==
'^' && i > 0) {
8500 <<
"'^' can only appear at the beginning.";
8502 }
else if (ch ==
'$' && regex[i + 1] !=
'\0') {
8504 <<
"'$' can only appear at the end.";
8506 }
else if (IsInSet(ch,
"()[]{}|")) {
8508 <<
"'" << ch <<
"' is unsupported.";
8510 }
else if (IsRepeat(ch) && !prev_repeatable) {
8512 <<
"'" << ch <<
"' can only follow a repeatable token.";
8516 prev_repeatable = !IsInSet(ch,
"^$?*+");
8530 bool MatchRepetitionAndRegexAtHead(
8531 bool escaped,
char c,
char repeat,
const char* regex,
8533 const size_t min_count = (repeat ==
'+') ? 1 : 0;
8534 const size_t max_count = (repeat ==
'?') ? 1 :
8535 static_cast<size_t>(-1) - 1;
8539 for (
size_t i = 0; i <= max_count; ++i) {
8541 if (i >= min_count && MatchRegexAtHead(regex, str + i)) {
8548 if (str[i] ==
'\0' || !AtomMatchesChar(escaped, c, str[i]))
8557 bool MatchRegexAtHead(
const char* regex,
const char* str) {
8564 return *str ==
'\0';
8567 const bool escaped = *regex ==
'\\';
8570 if (IsRepeat(regex[1])) {
8574 return MatchRepetitionAndRegexAtHead(
8575 escaped, regex[0], regex[1], regex + 2, str);
8580 return (*str !=
'\0') && AtomMatchesChar(escaped, *regex, *str) &&
8581 MatchRegexAtHead(regex + 1, str + 1);
8593 bool MatchRegexAnywhere(
const char* regex,
const char* str) {
8594 if (regex == NULL || str == NULL)
8598 return MatchRegexAtHead(regex + 1, str);
8602 if (MatchRegexAtHead(regex, str))
8604 }
while (*str++ !=
'\0');
8612 free(
const_cast<char*
>(full_pattern_));
8617 return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);
8623 return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);
8629 if (regex != NULL) {
8639 const size_t len = strlen(regex);
8643 char* buffer =
static_cast<char*
>(malloc(len + 3));
8644 full_pattern_ = buffer;
8651 memcpy(buffer, regex, len);
8654 if (len == 0 || regex[len - 1] !=
'$')
8660 #endif // GTEST_USES_POSIX_RE
8670 return file_name +
":";
8685 const char* file,
int line) {
8696 : severity_(severity) {
8697 const char*
const marker =
8700 severity ==
GTEST_ERROR ?
"[ ERROR ]" :
"[ FATAL ]";
8701 GetStream() << ::std::endl << marker <<
" "
8716 # pragma warning(push)
8717 # pragma warning(disable: 4996)
8720 #if GTEST_HAS_STREAM_REDIRECTION
8723 class CapturedStream {
8726 explicit CapturedStream(
int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {
8727 # if GTEST_OS_WINDOWS
8728 char temp_dir_path[MAX_PATH + 1] = {
'\0' };
8729 char temp_file_path[MAX_PATH + 1] = {
'\0' };
8731 ::GetTempPathA(
sizeof(temp_dir_path), temp_dir_path);
8732 const UINT success = ::GetTempFileNameA(temp_dir_path,
8737 <<
"Unable to create a temporary file in " << temp_dir_path;
8738 const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
8739 GTEST_CHECK_(captured_fd != -1) <<
"Unable to open temporary file "
8741 filename_ = temp_file_path;
8747 # if GTEST_OS_LINUX_ANDROID
8762 char name_template[] =
"/sdcard/gtest_captured_stream.XXXXXX";
8764 char name_template[] =
"/tmp/captured_stream.XXXXXX";
8765 # endif // GTEST_OS_LINUX_ANDROID
8766 const int captured_fd = mkstemp(name_template);
8767 filename_ = name_template;
8768 # endif // GTEST_OS_WINDOWS
8770 dup2(captured_fd, fd_);
8775 remove(filename_.c_str());
8779 if (uncaptured_fd_ != -1) {
8782 dup2(uncaptured_fd_, fd_);
8783 close(uncaptured_fd_);
8784 uncaptured_fd_ = -1;
8787 FILE*
const file =
posix::FOpen(filename_.c_str(),
"r");
8798 static size_t GetFileSize(FILE* file);
8809 size_t CapturedStream::GetFileSize(FILE* file) {
8810 fseek(file, 0, SEEK_END);
8811 return static_cast<size_t>(ftell(file));
8815 std::string CapturedStream::ReadEntireFile(FILE* file) {
8816 const size_t file_size = GetFileSize(file);
8817 char*
const buffer =
new char[file_size];
8819 size_t bytes_last_read = 0;
8820 size_t bytes_read = 0;
8822 fseek(file, 0, SEEK_SET);
8827 bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
8828 bytes_read += bytes_last_read;
8829 }
while (bytes_last_read > 0 && bytes_read < file_size);
8838 # pragma warning(pop)
8841 static CapturedStream* g_captured_stderr = NULL;
8842 static CapturedStream* g_captured_stdout = NULL;
8845 void CaptureStream(
int fd,
const char* stream_name, CapturedStream** stream) {
8846 if (*stream != NULL) {
8847 GTEST_LOG_(FATAL) <<
"Only one " << stream_name
8848 <<
" capturer can exist at a time.";
8850 *stream =
new CapturedStream(fd);
8854 std::string GetCapturedStream(CapturedStream** captured_stream) {
8855 const std::string content = (*captured_stream)->GetCapturedString();
8857 delete *captured_stream;
8858 *captured_stream = NULL;
8875 return GetCapturedStream(&g_captured_stdout);
8880 return GetCapturedStream(&g_captured_stderr);
8883 #endif // GTEST_HAS_STREAM_REDIRECTION
8885 #if GTEST_HAS_DEATH_TEST
8888 ::std::vector<testing::internal::string> g_argvs;
8890 static const ::std::vector<testing::internal::string>* g_injected_test_argvs =
8893 void SetInjectableArgvs(const ::std::vector<testing::internal::string>* argvs) {
8894 if (g_injected_test_argvs != argvs)
8895 delete g_injected_test_argvs;
8896 g_injected_test_argvs = argvs;
8899 const ::std::vector<testing::internal::string>& GetInjectableArgvs() {
8900 if (g_injected_test_argvs != NULL) {
8901 return *g_injected_test_argvs;
8905 #endif // GTEST_HAS_DEATH_TEST
8907 #if GTEST_OS_WINDOWS_MOBILE
8911 TerminateProcess(GetCurrentProcess(), 1);
8914 #endif // GTEST_OS_WINDOWS_MOBILE
8924 for (
size_t i = 0; i != full_flag.length(); i++) {
8925 env_var <<
ToUpper(full_flag.c_str()[i]);
8937 const long long_value = strtol(str, &end, 10);
8943 msg <<
"WARNING: " << src_text
8944 <<
" is expected to be a 32-bit integer, but actually"
8945 <<
" has value \"" << str <<
"\".\n";
8946 printf(
"%s",
msg.GetString().c_str());
8952 const Int32 result =
static_cast<Int32>(long_value);
8953 if (long_value == LONG_MAX || long_value == LONG_MIN ||
8956 result != long_value
8960 msg <<
"WARNING: " << src_text
8961 <<
" is expected to be a 32-bit integer, but actually"
8962 <<
" has value " << str <<
", which overflows.\n";
8963 printf(
"%s",
msg.GetString().c_str());
8978 const char*
const string_value =
posix::GetEnv(env_var.c_str());
8979 return string_value == NULL ?
8988 const char*
const string_value =
posix::GetEnv(env_var.c_str());
8989 if (string_value == NULL) {
8996 string_value, &result)) {
8997 printf(
"The default value %s is used.\n",
9069 using ::std::ostream;
9072 void PrintByteSegmentInObjectTo(
const unsigned char* obj_bytes,
size_t start,
9073 size_t count, ostream* os) {
9075 for (
size_t i = 0; i != count; i++) {
9076 const size_t j =
start + i;
9091 void PrintBytesInObjectToImpl(
const unsigned char* obj_bytes,
size_t count,
9094 *os << count <<
"-byte object <";
9096 const size_t kThreshold = 132;
9097 const size_t kChunkSize = 64;
9102 if (count < kThreshold) {
9103 PrintByteSegmentInObjectTo(obj_bytes, 0, count, os);
9105 PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os);
9108 const size_t resume_pos = (count - kChunkSize + 1)/2*2;
9109 PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os);
9116 namespace internal2 {
9125 PrintBytesInObjectToImpl(obj_bytes, count, os);
9130 namespace internal {
9147 return 0x20 <= c && c <= 0x7E;
9154 template <
typename Un
signedChar,
typename Char>
9156 switch (
static_cast<wchar_t>(c)) {
9189 *os << static_cast<char>(c);
9210 return PrintAsCharLiteralTo<wchar_t>(c, os);
9218 static_cast<wchar_t>(
static_cast<unsigned char>(c)), os);
9225 template <
typename Un
signedChar,
typename Char>
9228 *os << ((
sizeof(c) > 1) ?
"L'" :
"'");
9229 const CharFormat format = PrintAsCharLiteralTo<UnsignedChar>(c, os);
9237 *os <<
" (" <<
static_cast<int>(c);
9242 if (format ==
kHexEscape || (1 <= c && c <= 9)) {
9250 void PrintTo(
unsigned char c, ::std::ostream* os) {
9251 PrintCharAndCodeTo<unsigned char>(c, os);
9254 PrintCharAndCodeTo<unsigned char>(c, os);
9260 PrintCharAndCodeTo<wchar_t>(wc, os);
9267 template <
typename CharType>
9269 const CharType* begin,
size_t len, ostream* os) {
9270 const char*
const kQuoteBegin =
sizeof(CharType) == 1 ?
"\"" :
"L\"";
9272 bool is_previous_hex =
false;
9273 for (
size_t index = 0; index < len; ++index) {
9274 const CharType cur = begin[index];
9275 if (is_previous_hex &&
IsXDigit(cur)) {
9279 *os <<
"\" " << kQuoteBegin;
9288 template <
typename CharType>
9290 const CharType* begin,
size_t len, ostream* os) {
9298 if (len > 0 && begin[len - 1] ==
'\0') {
9308 *os <<
" (no terminating NUL)";
9327 *os << ImplicitCast_<const void*>(
s) <<
" pointing to ";
9338 #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
9344 *os << ImplicitCast_<const void*>(
s) <<
" pointing to ";
9348 #endif // wchar_t is native
9351 #if GTEST_HAS_GLOBAL_STRING
9355 #endif // GTEST_HAS_GLOBAL_STRING
9362 #if GTEST_HAS_GLOBAL_WSTRING
9366 #endif // GTEST_HAS_GLOBAL_WSTRING
9368 #if GTEST_HAS_STD_WSTRING
9372 #endif // GTEST_HAS_STD_WSTRING
9416 #define GTEST_IMPLEMENTATION_ 1
9417 #undef GTEST_IMPLEMENTATION_
9427 return stack_trace == NULL ?
message :
9437 "Non-fatal failure") <<
":\n"
9438 << result.
message() << std::endl;
9443 array_.push_back(result);
9448 if (index < 0 || index >=
size()) {
9449 printf(
"\nInvalid index (%d) into TestPartResultArray.\n", index);
9458 return static_cast<int>(
array_.size());
9461 namespace internal {
9464 : has_new_fatal_failure_(false),
9466 GetTestPartResultReporterForCurrentThread()) {
9518 namespace internal {
9520 #if GTEST_HAS_TYPED_TEST_P
9524 static const char* SkipSpaces(
const char* str) {
9533 const char* TypedTestCasePState::VerifyRegisteredTestNames(
9534 const char* file,
int line,
const char* registered_tests) {
9535 typedef ::std::set<const char*>::const_iterator DefinedTestIter;
9540 registered_tests = SkipSpaces(registered_tests);
9543 ::std::set<std::string> tests;
9544 for (
const char* names = registered_tests; names != NULL;
9545 names = SkipComma(names)) {
9546 const std::string name = GetPrefixUntilComma(names);
9547 if (tests.count(name) != 0) {
9548 errors <<
"Test " << name <<
" is listed more than once.\n";
9553 for (DefinedTestIter it = defined_test_names_.begin();
9554 it != defined_test_names_.end();
9565 errors <<
"No test named " << name
9566 <<
" can be found in this test case.\n";
9570 for (DefinedTestIter it = defined_test_names_.begin();
9571 it != defined_test_names_.end();
9573 if (tests.count(*it) == 0) {
9574 errors <<
"You forgot to list test " << *it <<
".\n";
9578 const std::string& errors_str = errors.GetString();
9579 if (errors_str !=
"") {
9581 errors_str.c_str());
9586 return registered_tests;
9589 #endif // GTEST_HAS_TYPED_TEST_P