39 #include "gtest/gtest.h"
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_
329 # define GTEST_HAS_GETTIMEOFDAY_ 1
335 # include <strings.h>
336 # include <sys/mman.h>
337 # include <sys/time.h>
341 #elif GTEST_OS_SYMBIAN
342 # define GTEST_HAS_GETTIMEOFDAY_ 1
343 # include <sys/time.h>
346 # define GTEST_HAS_GETTIMEOFDAY_ 1
347 # include <sys/time.h>
350 # include <strings.h>
352 #elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE.
354 # include <windows.h>
357 #elif GTEST_OS_WINDOWS // We are on Windows proper.
360 # include <sys/timeb.h>
361 # include <sys/types.h>
362 # include <sys/stat.h>
364 # if GTEST_OS_WINDOWS_MINGW
371 # define GTEST_HAS_GETTIMEOFDAY_ 1
372 # include <sys/time.h>
373 # endif // GTEST_OS_WINDOWS_MINGW
377 # include <windows.h>
385 # define GTEST_HAS_GETTIMEOFDAY_ 1
389 # include <sys/time.h>
392 #endif // GTEST_OS_LINUX
394 #if GTEST_HAS_EXCEPTIONS
395 # include <stdexcept>
398 #if GTEST_CAN_STREAM_RESULTS_
399 # include <arpa/inet.h>
401 # include <sys/socket.h>
402 # include <sys/types.h>
410 #define GTEST_IMPLEMENTATION_ 1
447 #ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_
448 #define GTEST_SRC_GTEST_INTERNAL_INL_H_
452 #if !GTEST_IMPLEMENTATION_
454 # error "gtest-internal-inl.h is part of Google Test's internal implementation."
455 # error "It must not be included except by Google Test itself."
456 #endif // GTEST_IMPLEMENTATION_
460 #endif // !_WIN32_WCE
470 #if GTEST_CAN_STREAM_RESULTS_
471 # include <arpa/inet.h>
476 # include <windows.h>
477 #endif // GTEST_OS_WINDOWS
544 const unsigned int raw_seed = (random_seed_flag == 0) ?
546 static_cast<unsigned int>(random_seed_flag);
550 const int normalized_seed =
551 static_cast<int>((raw_seed - 1U) %
553 return normalized_seed;
561 <<
"Invalid random seed " <<
seed <<
" - must be in [1, "
563 const int next_seed =
seed + 1;
670 const char* shard_index_str,
671 bool in_subprocess_for_death_test);
683 int total_shards,
int shard_index,
int test_id);
689 template <
class Container,
typename Predicate>
690 inline int CountIf(
const Container& c, Predicate predicate) {
694 for (
typename Container::const_iterator
it = c.begin();
it != c.end(); ++
it) {
702 template <
class Container,
typename Functor>
703 void ForEach(
const Container& c, Functor functor) {
704 std::for_each(c.begin(), c.end(), functor);
709 template <
typename E>
711 return (i < 0 || i >=
static_cast<int>(
v.size())) ? default_value :
v[
i];
718 template <
typename E>
721 const int size =
static_cast<int>(
v->size());
723 <<
"Invalid shuffle range start " <<
begin <<
": must be in range [0, "
726 <<
"Invalid shuffle range finish " <<
end <<
": must be in range ["
731 for (
int range_width =
end -
begin; range_width >= 2; range_width--) {
732 const int last_in_range =
begin + range_width - 1;
739 template <
typename E>
746 template <
typename T>
763 return test_property.
key() ==
key_;
803 static bool FilterMatchesTest(
const std::string &test_case_name,
812 static int GTestShouldProcessSEH(DWORD exception_code);
813 #endif // GTEST_OS_WINDOWS
817 static bool MatchesFilter(
const std::string&
name,
const char* filter);
922 void SetGlobalTestPartResultReporter(
929 void SetTestPartResultReporterForCurrentThread(
933 int successful_test_case_count()
const;
936 int failed_test_case_count()
const;
939 int total_test_case_count()
const;
943 int test_case_to_run_count()
const;
946 int successful_test_count()
const;
949 int failed_test_count()
const;
952 int reportable_disabled_test_count()
const;
955 int disabled_test_count()
const;
958 int reportable_test_count()
const;
961 int total_test_count()
const;
964 int test_to_run_count()
const;
974 bool Passed()
const {
return !Failed(); }
979 return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed();
986 return index < 0 ? NULL : test_cases_[
i];
1040 TestCase* GetTestCase(
const char* test_case_name,
1041 const char* type_param,
1065 <<
"Failed to get the current working directory.";
1071 tear_down_tc)->AddTestInfo(test_info);
1074 #if GTEST_HAS_PARAM_TEST
1078 return parameterized_test_registry_;
1080 #endif // GTEST_HAS_PARAM_TEST
1084 current_test_case_ = a_current_test_case;
1091 current_test_info_ = a_current_test_info;
1100 void RegisterParameterizedTests();
1115 ad_hoc_test_result_.Clear();
1122 void RecordProperty(
const TestProperty& test_property);
1126 IGNORE_SHARDING_PROTOCOL
1135 int FilterTests(ReactionToSharding shard_tests);
1138 void ListTestsMatchingFilter();
1150 return *(gtest_trace_stack_.pointer());
1153 return gtest_trace_stack_.get();
1156 #if GTEST_HAS_DEATH_TEST
1157 void InitDeathTestSubprocessControlInfo() {
1158 internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());
1164 const InternalRunDeathTestFlag* internal_run_death_test_flag()
const {
1165 return internal_run_death_test_flag_.get();
1169 internal::DeathTestFactory* death_test_factory() {
1170 return death_test_factory_.get();
1173 void SuppressTestEventsIfInSubprocess();
1175 friend class ReplaceDeathTestFactory;
1176 #endif // GTEST_HAS_DEATH_TEST
1180 void ConfigureXmlOutput();
1182 #if GTEST_CAN_STREAM_RESULTS_
1185 void ConfigureStreamingOutput();
1193 void PostFlagParsingInit();
1203 void ShuffleTests();
1206 void UnshuffleTests();
1213 friend class ::testing::UnitTest;
1255 #if GTEST_HAS_PARAM_TEST
1262 #endif // GTEST_HAS_PARAM_TEST
1315 #if GTEST_HAS_DEATH_TEST
1320 #endif // GTEST_HAS_DEATH_TEST
1338 #if GTEST_USES_SIMPLE_RE
1350 GTEST_API_ bool ValidateRegex(
const char* regex);
1351 GTEST_API_ bool MatchRegexAtHead(
const char* regex,
const char*
str);
1352 GTEST_API_ bool MatchRepetitionAndRegexAtHead(
1353 bool escaped,
char ch,
char repeat,
const char* regex,
const char*
str);
1354 GTEST_API_ bool MatchRegexAnywhere(
const char* regex,
const char*
str);
1356 #endif // GTEST_USES_SIMPLE_RE
1363 #if GTEST_HAS_DEATH_TEST
1373 template <
typename Integer>
1387 # if GTEST_OS_WINDOWS && !defined(__GNUC__)
1390 typedef unsigned __int64 BiggestConvertible;
1391 const BiggestConvertible parsed = _strtoui64(
str.c_str(), &
end, 10);
1395 typedef unsigned long long BiggestConvertible;
1396 const BiggestConvertible parsed = strtoull(
str.c_str(), &
end, 10);
1398 # endif // GTEST_OS_WINDOWS && !defined(__GNUC__)
1400 const bool parse_success = *
end ==
'\0' && errno == 0;
1406 const Integer
result =
static_cast<Integer
>(parsed);
1407 if (parse_success &&
static_cast<BiggestConvertible
>(
result) == parsed) {
1413 #endif // GTEST_HAS_DEATH_TEST
1426 test_result->RecordProperty(xml_element, property);
1439 #if GTEST_CAN_STREAM_RESULTS_
1445 class AbstractSocketWriter {
1447 virtual ~AbstractSocketWriter() {}
1450 virtual void Send(
const string&
message) = 0;
1453 virtual void CloseConnection() {}
1456 void SendLn(
const string&
message) {
1462 class SocketWriter :
public AbstractSocketWriter {
1464 SocketWriter(
const string& host,
const string&
port)
1465 : sockfd_(-1), host_name_(host), port_num_(
port) {
1469 virtual ~SocketWriter() {
1475 virtual void Send(
const string&
message) {
1477 <<
"Send() can be called only when there is a connection.";
1479 const int len =
static_cast<int>(
message.length());
1482 <<
"stream_result_to: failed to stream to "
1483 << host_name_ <<
":" << port_num_;
1489 void MakeConnection();
1492 void CloseConnection() {
1494 <<
"CloseConnection() can be called only when there is a connection.";
1501 const string host_name_;
1502 const string port_num_;
1508 static string UrlEncode(
const char*
str);
1510 StreamingListener(
const string& host,
const string&
port)
1511 : socket_writer_(
new SocketWriter(host,
port)) { Start(); }
1513 explicit StreamingListener(AbstractSocketWriter* socket_writer)
1514 : socket_writer_(socket_writer) { Start(); }
1516 void OnTestProgramStart(
const UnitTest& ) {
1517 SendLn(
"event=TestProgramStart");
1520 void OnTestProgramEnd(
const UnitTest& unit_test) {
1523 SendLn(
"event=TestProgramEnd&passed=" + FormatBool(unit_test.Passed()));
1526 socket_writer_->CloseConnection();
1529 void OnTestIterationStart(
const UnitTest& ,
int iteration) {
1530 SendLn(
"event=TestIterationStart&iteration=" +
1534 void OnTestIterationEnd(
const UnitTest& unit_test,
int ) {
1535 SendLn(
"event=TestIterationEnd&passed=" +
1536 FormatBool(unit_test.Passed()) +
"&elapsed_time=" +
1540 void OnTestCaseStart(
const TestCase& test_case) {
1541 SendLn(
std::string(
"event=TestCaseStart&name=") + test_case.name());
1544 void OnTestCaseEnd(
const TestCase& test_case) {
1545 SendLn(
"event=TestCaseEnd&passed=" + FormatBool(test_case.Passed())
1550 void OnTestStart(
const TestInfo& test_info) {
1551 SendLn(
std::string(
"event=TestStart&name=") + test_info.name());
1554 void OnTestEnd(
const TestInfo& test_info) {
1555 SendLn(
"event=TestEnd&passed=" +
1556 FormatBool((test_info.result())->Passed()) +
1561 void OnTestPartResult(
const TestPartResult& test_part_result) {
1562 const char* file_name = test_part_result.file_name();
1563 if (file_name == NULL)
1565 SendLn(
"event=TestPartResult&file=" + UrlEncode(file_name) +
1567 "&message=" + UrlEncode(test_part_result.message()));
1572 void SendLn(
const string&
message) { socket_writer_->SendLn(
message); }
1576 void Start() { SendLn(
"gtest_streaming_protocol_version=1.0"); }
1578 string FormatBool(
bool value) {
return value ?
"1" :
"0"; }
1580 const scoped_ptr<AbstractSocketWriter> socket_writer_;
1585 #endif // GTEST_CAN_STREAM_RESULTS_
1590 #endif // GTEST_SRC_GTEST_INTERNAL_INL_H_
1591 #undef GTEST_IMPLEMENTATION_
1593 #if GTEST_OS_WINDOWS
1594 # define vsnprintf _vsnprintf
1595 #endif // GTEST_OS_WINDOWS
1641 #ifdef GTEST_TEST_FILTER_ENV_VAR_
1642 const char*
const testbridge_test_only =
getenv(GTEST_TEST_FILTER_ENV_VAR_);
1643 if (testbridge_test_only != NULL) {
1644 return testbridge_test_only;
1646 #endif // GTEST_TEST_FILTER_ENV_VAR_
1651 also_run_disabled_tests,
1653 "Run disabled tests too, in addition to the tests normally being run.");
1658 "True iff a failed assertion should be a debugger break-point.");
1664 " should catch exceptions and treat them as test failures.");
1669 "Whether to use colors in the output. Valid values: yes, no, "
1670 "and auto. 'auto' means to use colors if the output is "
1671 "being sent to a terminal and the TERM environment variable "
1672 "is set to a terminal type that supports colors.");
1677 "A colon-separated list of glob (not regex) patterns "
1678 "for filtering the tests to run, optionally followed by a "
1679 "'-' and a : separated list of negative patterns (tests to "
1680 "exclude). A test is run if it matches one of the positive "
1681 "patterns and does not match any of the negative patterns.");
1684 "List all tests without running them.");
1689 "A format (currently must be \"xml\"), optionally followed "
1690 "by a colon and an output file name or directory. A directory "
1691 "is indicated by a trailing pathname separator. "
1692 "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
1693 "If a directory is specified, output files will be created "
1694 "within that directory, with file-names based on the test "
1695 "executable's name and, if necessary, made unique by adding "
1702 " should display elapsed time in text output.");
1707 "Random number seed to use when shuffling test orders. Must be in range "
1708 "[1, 99999], or 0 to use a seed based on the current time.");
1713 "How many times to repeat each test. Specify a negative number "
1714 "for repeating forever. Useful for shaking out flaky tests.");
1717 show_internal_stack_frames,
false,
1718 "True iff " GTEST_NAME_ " should include internal stack frames when "
1719 "printing test failure stack traces.");
1725 " should randomize tests' order on every run.");
1730 "The maximum number of stack frames to print when an "
1731 "assertion fails. The valid range is 0 through 100, inclusive.");
1736 "This flag specifies the host name and the port number on which to stream "
1737 "test results. Example: \"localhost:555\". The flag is effective only on "
1743 "When this flag is specified, a failed assertion will throw an exception "
1744 "if exceptions are enabled or exit the program with a non-zero code "
1747 #if GTEST_USE_OWN_FLAGFILE_FLAG_
1751 "This flag specifies the flagfile to read command-line flags from.");
1752 #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
1764 <<
"Cannot generate a number in the range [0, 0).";
1766 <<
"Generation of a number in [0, " <<
range <<
") was requested, "
1767 <<
"but this can only generate numbers in [0, " <<
kMaxRange <<
").";
1786 for (
size_t i = 0;
i < case_list.size();
i++) {
1816 AssertHelper::~AssertHelper() {
1835 ::std::vector<testing::internal::string>
g_argvs;
1837 const ::std::vector<testing::internal::string>&
GetArgvs() {
1838 #if defined(GTEST_CUSTOM_GET_ARGVS_)
1839 return GTEST_CUSTOM_GET_ARGVS_();
1840 #else // defined(GTEST_CUSTOM_GET_ARGVS_)
1842 #endif // defined(GTEST_CUSTOM_GET_ARGVS_)
1850 #if GTEST_OS_WINDOWS
1854 #endif // GTEST_OS_WINDOWS
1856 return result.RemoveDirectoryName();
1864 if (gtest_output_flag == NULL)
return std::string(
"");
1866 const char*
const colon = strchr(gtest_output_flag,
':');
1867 return (colon == NULL) ?
1869 std::
string(gtest_output_flag, colon - gtest_output_flag);
1874 std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
1876 if (gtest_output_flag == NULL)
1879 const char*
const colon = strchr(gtest_output_flag,
':');
1887 if (!output_name.IsAbsolutePath())
1896 if (!output_name.IsDirectory())
1897 return output_name.string();
1901 GetOutputFormat().
c_str()));
1915 return *
str ==
'\0';
1927 bool UnitTestOptions::MatchesFilter(
1929 const char *cur_pattern = filter;
1936 cur_pattern = strchr(cur_pattern,
':');
1939 if (cur_pattern == NULL) {
1950 bool UnitTestOptions::FilterMatchesTest(
const std::string &test_case_name,
1952 const std::string& full_name = test_case_name +
"." + test_name.c_str();
1957 const char*
const dash = strchr(p,
'-');
1966 if (positive.empty()) {
1974 return (MatchesFilter(full_name, positive.c_str()) &&
1975 !MatchesFilter(full_name,
negative.c_str()));
1982 int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
1991 const DWORD kCxxExceptionCode = 0xe06d7363;
1993 bool should_handle =
true;
1996 should_handle =
false;
1997 else if (exception_code == EXCEPTION_BREAKPOINT)
1998 should_handle =
false;
1999 else if (exception_code == kCxxExceptionCode)
2000 should_handle =
false;
2002 return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
2004 #endif // GTEST_HAS_SEH
2011 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
2012 TestPartResultArray*
result)
2013 : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
2022 InterceptMode intercept_mode, TestPartResultArray*
result)
2023 : intercept_mode_(intercept_mode),
2032 impl->SetGlobalTestPartResultReporter(
this);
2034 old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
2035 impl->SetTestPartResultReporterForCurrentThread(
this);
2046 impl->SetTestPartResultReporterForCurrentThread(
old_reporter_);
2053 const TestPartResult&
result) {
2069 return GetTypeId<Test>();
2084 const string& substr) {
2087 "1 non-fatal failure");
2090 msg <<
"Expected: " << expected <<
"\n"
2091 <<
" Actual: " <<
results.size() <<
" failures";
2099 if (
r.type() !=
type) {
2105 if (strstr(
r.message(), substr.c_str()) == NULL) {
2121 const string& substr)
2130 SingleFailureChecker::~SingleFailureChecker() {
2134 DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
2135 UnitTestImpl* unit_test) : unit_test_(unit_test) {}
2137 void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
2138 const TestPartResult&
result) {
2139 unit_test_->current_test_result()->AddTestPartResult(
result);
2140 unit_test_->listeners()->repeater()->OnTestPartResult(
result);
2143 DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
2144 UnitTestImpl* unit_test) : unit_test_(unit_test) {}
2146 void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
2147 const TestPartResult&
result) {
2148 unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(
result);
2152 TestPartResultReporterInterface*
2153 UnitTestImpl::GetGlobalTestPartResultReporter() {
2155 return global_test_part_result_repoter_;
2159 void UnitTestImpl::SetGlobalTestPartResultReporter(
2160 TestPartResultReporterInterface* reporter) {
2162 global_test_part_result_repoter_ = reporter;
2166 TestPartResultReporterInterface*
2167 UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
2168 return per_thread_test_part_result_reporter_.get();
2172 void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
2173 TestPartResultReporterInterface* reporter) {
2174 per_thread_test_part_result_reporter_.set(reporter);
2178 int UnitTestImpl::successful_test_case_count()
const {
2183 int UnitTestImpl::failed_test_case_count()
const {
2188 int UnitTestImpl::total_test_case_count()
const {
2189 return static_cast<int>(test_cases_.size());
2194 int UnitTestImpl::test_case_to_run_count()
const {
2199 int UnitTestImpl::successful_test_count()
const {
2204 int UnitTestImpl::failed_test_count()
const {
2209 int UnitTestImpl::reportable_disabled_test_count()
const {
2215 int UnitTestImpl::disabled_test_count()
const {
2220 int UnitTestImpl::reportable_test_count()
const {
2225 int UnitTestImpl::total_test_count()
const {
2230 int UnitTestImpl::test_to_run_count()
const {
2244 std::string UnitTestImpl::CurrentOsStackTraceExceptTop(
int skip_count) {
2245 return os_stack_trace_getter()->CurrentStackTrace(
2246 static_cast<int>(
GTEST_FLAG(stack_trace_depth)),
2255 #if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__)
2260 const DWORD kTenthMicrosInMilliSecond = 10000;
2262 SYSTEMTIME now_systime;
2263 FILETIME now_filetime;
2264 ULARGE_INTEGER now_int64;
2267 GetSystemTime(&now_systime);
2268 if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
2269 now_int64.LowPart = now_filetime.dwLowDateTime;
2270 now_int64.HighPart = now_filetime.dwHighDateTime;
2271 now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
2272 kJavaEpochToWinFileTimeDelta;
2273 return now_int64.QuadPart;
2276 #elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_
2288 #elif GTEST_HAS_GETTIMEOFDAY_
2290 gettimeofday(&
now, NULL);
2293 #
error "Don't know how to get the current time on your system."
2301 #if GTEST_OS_WINDOWS_MOBILE
2306 LPCWSTR String::AnsiToUtf16(
const char* ansi) {
2307 if (!ansi)
return NULL;
2308 const int length = strlen(ansi);
2309 const int unicode_length =
2310 MultiByteToWideChar(CP_ACP, 0, ansi,
length,
2312 WCHAR*
unicode =
new WCHAR[unicode_length + 1];
2313 MultiByteToWideChar(CP_ACP, 0, ansi,
length,
2323 const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
2324 if (!utf16_str)
return NULL;
2325 const int ansi_length =
2326 WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
2327 NULL, 0, NULL, NULL);
2328 char* ansi =
new char[ansi_length + 1];
2329 WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
2330 ansi, ansi_length, NULL, NULL);
2331 ansi[ansi_length] = 0;
2335 #endif // GTEST_OS_WINDOWS_MOBILE
2342 bool String::CStringEquals(
const char * lhs,
const char * rhs) {
2343 if ( lhs == NULL )
return rhs == NULL;
2345 if ( rhs == NULL )
return false;
2347 return strcmp(lhs, rhs) == 0;
2350 #if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
2356 for (
size_t i = 0;
i !=
length; ) {
2357 if (wstr[
i] !=
L'\0') {
2358 *msg << WideStringToUtf8(wstr + i, static_cast<int>(
length -
i));
2368 #endif // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
2371 ::std::vector< ::std::string>*
dest) {
2372 ::std::vector< ::std::string> parsed;
2373 ::std::string::size_type
pos = 0;
2375 const ::std::string::size_type colon =
str.find(delimiter,
pos);
2376 if (colon == ::std::string::npos) {
2377 parsed.push_back(
str.substr(
pos));
2380 parsed.push_back(
str.substr(
pos, colon -
pos));
2397 *ss_ << std::setprecision(std::numeric_limits<double>::digits10 + 2);
2409 #if GTEST_HAS_STD_WSTRING
2416 #endif // GTEST_HAS_STD_WSTRING
2418 #if GTEST_HAS_GLOBAL_WSTRING
2425 #endif // GTEST_HAS_GLOBAL_WSTRING
2436 : success_(other.success_),
2437 message_(other.message_.
get() != NULL ?
2459 return AssertionResult(
true);
2464 return AssertionResult(
false);
2475 namespace edit_distance {
2477 const std::vector<size_t>& right) {
2478 std::vector<std::vector<double> > costs(
2479 left.size() + 1, std::vector<double>(right.size() + 1));
2480 std::vector<std::vector<EditType> > best_move(
2481 left.size() + 1, std::vector<EditType>(right.size() + 1));
2484 for (
size_t l_i = 0; l_i < costs.size(); ++l_i) {
2485 costs[l_i][0] =
static_cast<double>(l_i);
2489 for (
size_t r_i = 1; r_i < costs[0].size(); ++r_i) {
2490 costs[0][r_i] =
static_cast<double>(r_i);
2491 best_move[0][r_i] =
kAdd;
2494 for (
size_t l_i = 0; l_i < left.size(); ++l_i) {
2495 for (
size_t r_i = 0; r_i < right.size(); ++r_i) {
2496 if (left[l_i] == right[r_i]) {
2498 costs[l_i + 1][r_i + 1] = costs[l_i][r_i];
2499 best_move[l_i + 1][r_i + 1] =
kMatch;
2503 const double add = costs[l_i + 1][r_i];
2504 const double remove = costs[l_i][r_i + 1];
2505 const double replace = costs[l_i][r_i];
2506 if (
add < remove &&
add < replace) {
2507 costs[l_i + 1][r_i + 1] =
add + 1;
2508 best_move[l_i + 1][r_i + 1] =
kAdd;
2509 }
else if (remove <
add && remove < replace) {
2510 costs[l_i + 1][r_i + 1] = remove + 1;
2511 best_move[l_i + 1][r_i + 1] =
kRemove;
2515 costs[l_i + 1][r_i + 1] = replace + 1.00001;
2516 best_move[l_i + 1][r_i + 1] =
kReplace;
2522 std::vector<EditType> best_path;
2523 for (
size_t l_i = left.size(), r_i = right.size(); l_i > 0 || r_i > 0;) {
2525 best_path.push_back(
move);
2536 class InternalStrings {
2540 if (
it !=
ids_.end())
return it->second;
2541 size_t id =
ids_.size();
2546 typedef std::map<std::string, size_t>
IdMap;
2553 const std::vector<std::string>& left,
2554 const std::vector<std::string>& right) {
2555 std::vector<size_t> left_ids, right_ids;
2557 InternalStrings intern_table;
2558 for (
size_t i = 0;
i < left.size(); ++
i) {
2559 left_ids.push_back(intern_table.GetId(left[
i]));
2561 for (
size_t i = 0;
i < right.size(); ++
i) {
2562 right_ids.push_back(intern_table.GetId(right[i]));
2576 Hunk(
size_t left_start,
size_t right_start)
2583 void PushLine(
char edit,
const char*
line) {
2588 hunk_.push_back(std::make_pair(
' ',
line));
2601 void PrintTo(std::ostream* os) {
2604 for (std::list<std::pair<char, const char*> >::const_iterator
it =
2607 *os <<
it->first <<
it->second <<
"\n";
2623 void PrintHeader(std::ostream* ss)
const {
2652 const std::vector<std::string>& right,
2656 size_t l_i = 0, r_i = 0, edit_i = 0;
2657 std::stringstream ss;
2658 while (edit_i < edits.size()) {
2660 while (edit_i < edits.size() && edits[edit_i] ==
kMatch) {
2668 Hunk hunk(l_i - prefix_context + 1, r_i - prefix_context + 1);
2669 for (
size_t i = prefix_context;
i > 0; --
i) {
2670 hunk.PushLine(
' ', left[l_i - i].
c_str());
2675 size_t n_suffix = 0;
2676 for (; edit_i < edits.size(); ++edit_i) {
2679 std::vector<EditType>::const_iterator
it = edits.begin() + edit_i;
2681 if (
it == edits.end() || (
it - edits.begin()) - edit_i >=
context) {
2689 n_suffix = edit ==
kMatch ? n_suffix + 1 : 0;
2692 hunk.PushLine(edit ==
kMatch ?
' ' :
'-', left[l_i].
c_str());
2695 hunk.PushLine(
'+', right[r_i].
c_str());
2699 l_i += edit !=
kAdd;
2703 if (!hunk.has_edits()) {
2720 std::vector<std::string> SplitEscapedString(
const std::string&
str) {
2721 std::vector<std::string>
lines;
2727 bool escaped =
false;
2731 if (
str[i] ==
'n') {
2736 escaped =
str[
i] ==
'\\';
2760 AssertionResult
EqFailure(
const char* lhs_expression,
2761 const char* rhs_expression,
2764 bool ignoring_case) {
2766 msg <<
" Expected: " << lhs_expression;
2767 if (lhs_value != lhs_expression) {
2768 msg <<
"\n Which is: " << lhs_value;
2770 msg <<
"\nTo be equal to: " << rhs_expression;
2771 if (rhs_value != rhs_expression) {
2772 msg <<
"\n Which is: " << rhs_value;
2775 if (ignoring_case) {
2776 msg <<
"\nIgnoring case";
2779 if (!lhs_value.empty() && !rhs_value.empty()) {
2780 const std::vector<std::string> lhs_lines =
2781 SplitEscapedString(lhs_value);
2782 const std::vector<std::string> rhs_lines =
2783 SplitEscapedString(rhs_value);
2784 if (lhs_lines.size() > 1 || rhs_lines.size() > 1) {
2785 msg <<
"\nWith diff:\n"
2795 const AssertionResult& assertion_result,
2796 const char* expression_text,
2797 const char* actual_predicate_value,
2798 const char* expected_predicate_value) {
2799 const char* actual_message = assertion_result.message();
2801 msg <<
"Value of: " << expression_text
2802 <<
"\n Actual: " << actual_predicate_value;
2803 if (actual_message[0] !=
'\0')
2804 msg <<
" (" << actual_message <<
")";
2805 msg <<
"\nExpected: " << expected_predicate_value;
2806 return msg.GetString();
2812 const char* abs_error_expr,
2822 <<
"The difference between " << expr1 <<
" and " << expr2
2823 <<
" is " <<
diff <<
", which exceeds " << abs_error_expr <<
", where\n"
2824 << expr1 <<
" evaluates to " <<
val1 <<
",\n"
2825 << expr2 <<
" evaluates to " <<
val2 <<
", and\n"
2826 << abs_error_expr <<
" evaluates to " << abs_error <<
".";
2831 template <
typename RawType>
2842 const FloatingPoint<RawType> lhs(
val1), rhs(
val2);
2843 if (lhs.AlmostEquals(rhs)) {
2851 ::std::stringstream val1_ss;
2852 val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
2855 ::std::stringstream val2_ss;
2856 val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
2860 <<
"Expected: (" << expr1 <<
") <= (" << expr2 <<
")\n"
2869 AssertionResult
FloatLE(
const char* expr1,
const char* expr2,
2871 return internal::FloatingPointLE<float>(expr1, expr2,
val1,
val2);
2876 AssertionResult
DoubleLE(
const char* expr1,
const char* expr2,
2878 return internal::FloatingPointLE<double>(expr1, expr2,
val1,
val2);
2885 AssertionResult
CmpHelperEQ(
const char* lhs_expression,
2886 const char* rhs_expression,
2903 #define GTEST_IMPL_CMP_HELPER_(op_name, op)\
2904 AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
2905 BiggestInt val1, BiggestInt val2) {\
2906 if (val1 op val2) {\
2907 return AssertionSuccess();\
2909 return AssertionFailure() \
2910 << "Expected: (" << expr1 << ") " #op " (" << expr2\
2911 << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
2912 << " vs " << FormatForComparisonFailureMessage(val2, val1);\
2932 #undef GTEST_IMPL_CMP_HELPER_
2936 const char* rhs_expression,
2952 const char* rhs_expression,
2968 const char* s2_expression,
2975 << s2_expression <<
"), actual: \""
2976 << s1 <<
"\" vs \"" << s2 <<
"\"";
2982 const char* s2_expression,
2989 <<
"Expected: (" << s1_expression <<
") != ("
2990 << s2_expression <<
") (ignoring case), actual: \""
2991 << s1 <<
"\" vs \"" << s2 <<
"\"";
3005 bool IsSubstringPred(
const char* needle,
const char* haystack) {
3006 if (needle == NULL || haystack == NULL)
3007 return needle == haystack;
3009 return strstr(haystack, needle) != NULL;
3012 bool IsSubstringPred(
const wchar_t* needle,
const wchar_t* haystack) {
3013 if (needle == NULL || haystack == NULL)
3014 return needle == haystack;
3016 return wcsstr(haystack, needle) != NULL;
3020 template <
typename StringType>
3021 bool IsSubstringPred(
const StringType& needle,
3023 return haystack.find(needle) != StringType::npos;
3030 template <
typename StringType>
3031 AssertionResult IsSubstringImpl(
3032 bool expected_to_be_substring,
3033 const char* needle_expr,
const char* haystack_expr,
3035 if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
3038 const bool is_wide_string =
sizeof(needle[0]) > 1;
3039 const char*
const begin_string_quote = is_wide_string ?
"L\"" :
"\"";
3041 <<
"Value of: " << needle_expr <<
"\n"
3042 <<
" Actual: " << begin_string_quote << needle <<
"\"\n"
3043 <<
"Expected: " << (expected_to_be_substring ?
"" :
"not ")
3044 <<
"a substring of " << haystack_expr <<
"\n"
3045 <<
"Which is: " << begin_string_quote << haystack <<
"\"";
3055 const char* needle_expr,
const char* haystack_expr,
3056 const char* needle,
const char* haystack) {
3057 return IsSubstringImpl(
true, needle_expr, haystack_expr, needle, haystack);
3061 const char* needle_expr,
const char* haystack_expr,
3062 const wchar_t* needle,
const wchar_t* haystack) {
3063 return IsSubstringImpl(
true, needle_expr, haystack_expr, needle, haystack);
3067 const char* needle_expr,
const char* haystack_expr,
3068 const char* needle,
const char* haystack) {
3069 return IsSubstringImpl(
false, needle_expr, haystack_expr, needle, haystack);
3073 const char* needle_expr,
const char* haystack_expr,
3074 const wchar_t* needle,
const wchar_t* haystack) {
3075 return IsSubstringImpl(
false, needle_expr, haystack_expr, needle, haystack);
3079 const char* needle_expr,
const char* haystack_expr,
3081 return IsSubstringImpl(
true, needle_expr, haystack_expr, needle, haystack);
3085 const char* needle_expr,
const char* haystack_expr,
3087 return IsSubstringImpl(
false, needle_expr, haystack_expr, needle, haystack);
3090 #if GTEST_HAS_STD_WSTRING
3092 const char* needle_expr,
const char* haystack_expr,
3094 return IsSubstringImpl(
true, needle_expr, haystack_expr, needle, haystack);
3098 const char* needle_expr,
const char* haystack_expr,
3100 return IsSubstringImpl(
false, needle_expr, haystack_expr, needle, haystack);
3102 #endif // GTEST_HAS_STD_WSTRING
3106 #if GTEST_OS_WINDOWS
3111 AssertionResult HRESULTFailureHelper(
const char* expr,
3112 const char* expected,
3114 # if GTEST_OS_WINDOWS_MOBILE
3117 const char error_text[] =
"";
3124 const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
3125 FORMAT_MESSAGE_IGNORE_INSERTS;
3126 const DWORD kBufSize = 4096;
3128 char error_text[kBufSize] = {
'\0' };
3129 DWORD message_length = ::FormatMessageA(kFlags,
3137 for (; message_length &&
IsSpace(error_text[message_length - 1]);
3139 error_text[message_length - 1] =
'\0';
3142 # endif // GTEST_OS_WINDOWS_MOBILE
3146 <<
"Expected: " << expr <<
" " << expected <<
".\n"
3147 <<
" Actual: " << error_hex <<
" " << error_text <<
"\n";
3152 AssertionResult IsHRESULTSuccess(
const char* expr,
long hr) {
3153 if (SUCCEEDED(hr)) {
3156 return HRESULTFailureHelper(expr,
"succeeds", hr);
3159 AssertionResult IsHRESULTFailure(
const char* expr,
long hr) {
3163 return HRESULTFailureHelper(expr,
"fails", hr);
3166 #endif // GTEST_OS_WINDOWS
3215 str[0] =
static_cast<char>(code_point);
3219 str[0] =
static_cast<char>(0xC0 | code_point);
3224 str[0] =
static_cast<char>(0xE0 | code_point);
3230 str[0] =
static_cast<char>(0xF0 | code_point);
3243 return sizeof(wchar_t) == 2 &&
3244 (
first & 0xFC00) == 0xD800 && (
second & 0xFC00) == 0xDC00;
3250 const UInt32 mask = (1 << 10) - 1;
3251 return (
sizeof(
wchar_t) == 2) ?
3252 (((
first & mask) << 10) | (
second & mask)) + 0x10000 :
3272 if (num_chars == -1)
3273 num_chars =
static_cast<int>(wcslen(
str));
3275 ::std::stringstream
stream;
3276 for (
int i = 0;
i < num_chars; ++
i) {
3277 UInt32 unicode_code_point;
3279 if (
str[i] == L
'\0') {
3286 unicode_code_point =
static_cast<UInt32>(
str[
i]);
3297 if (wide_c_str == NULL)
return "(null)";
3309 if (lhs == NULL)
return rhs == NULL;
3311 if (rhs == NULL)
return false;
3313 return wcscmp(lhs, rhs) == 0;
3318 const char* rhs_expression,
3320 const wchar_t* rhs) {
3334 const char* s2_expression,
3336 const wchar_t* s2) {
3342 << s2_expression <<
"), actual: "
3374 const wchar_t* rhs) {
3375 if (lhs == NULL)
return rhs == NULL;
3377 if (rhs == NULL)
return false;
3379 #if GTEST_OS_WINDOWS
3380 return _wcsicmp(lhs, rhs) == 0;
3381 #elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID
3382 return wcscasecmp(lhs, rhs) == 0;
3388 left = towlower(*lhs++);
3389 right = towlower(*rhs++);
3390 }
while (left && left == right);
3391 return left == right;
3392 #endif // OS selector
3399 const size_t str_len =
str.length();
3400 const size_t suffix_len =
suffix.length();
3401 return (str_len >= suffix_len) &&
3408 std::stringstream ss;
3409 ss << std::setfill(
'0') << std::setw(2) <<
value;
3415 std::stringstream ss;
3416 ss << std::hex << std::uppercase <<
value;
3422 std::stringstream ss;
3423 ss << std::setfill(
'0') << std::setw(2) << std::hex << std::uppercase
3424 <<
static_cast<unsigned int>(
value);
3432 const char*
const start =
str.c_str();
3452 const std::string user_msg_string = user_msg.GetString();
3453 if (user_msg_string.empty()) {
3457 return gtest_msg +
"\n" + user_msg_string;
3466 : death_test_count_(0),
3471 TestResult::~TestResult() {
3477 const TestPartResult& TestResult::GetTestPartResult(
int i)
const {
3478 if (i < 0 || i >= total_part_count())
3480 return test_part_results_.at(
i);
3486 const TestProperty& TestResult::GetTestProperty(
int i)
const {
3487 if (i < 0 || i >= test_property_count())
3489 return test_properties_.at(
i);
3493 void TestResult::ClearTestPartResults() {
3494 test_part_results_.clear();
3498 void TestResult::AddTestPartResult(
const TestPartResult& test_part_result) {
3499 test_part_results_.push_back(test_part_result);
3505 void TestResult::RecordProperty(
const std::string& xml_element,
3506 const TestProperty& test_property) {
3507 if (!ValidateTestProperty(xml_element, test_property)) {
3512 std::find_if(test_properties_.begin(), test_properties_.end(),
3513 internal::TestPropertyKeyIs(test_property.key()));
3514 if (property_with_matching_key == test_properties_.end()) {
3515 test_properties_.push_back(test_property);
3518 property_with_matching_key->SetValue(test_property.value());
3555 template <
int kSize>
3562 if (xml_element ==
"testsuites") {
3564 }
else if (xml_element ==
"testsuite") {
3566 }
else if (xml_element ==
"testcase") {
3569 GTEST_CHECK_(
false) <<
"Unrecognized xml_element provided: " << xml_element;
3572 return std::vector<std::string>();
3577 for (
size_t i = 0;
i <
words.size(); ++
i) {
3578 if (
i > 0 &&
words.size() > 2) {
3581 if (
i ==
words.size() - 1) {
3582 word_list <<
"and ";
3584 word_list <<
"'" <<
words[
i] <<
"'";
3593 ADD_FAILURE() <<
"Reserved key used in RecordProperty(): " << property_name
3603 bool TestResult::ValidateTestProperty(
const std::string& xml_element,
3604 const TestProperty& test_property) {
3611 test_part_results_.clear();
3612 test_properties_.clear();
3613 death_test_count_ = 0;
3618 bool TestResult::Failed()
const {
3619 for (
int i = 0;
i < total_part_count(); ++
i) {
3620 if (GetTestPartResult(
i).failed())
3628 return result.fatally_failed();
3632 bool TestResult::HasFatalFailure()
const {
3638 return result.nonfatally_failed();
3642 bool TestResult::HasNonfatalFailure()
const {
3648 int TestResult::total_part_count()
const {
3649 return static_cast<int>(test_part_results_.size());
3653 int TestResult::test_property_count()
const {
3654 return static_cast<int>(test_properties_.size());
3675 void Test::SetUp() {
3681 void Test::TearDown() {
3686 UnitTest::GetInstance()->RecordProperty(
key,
value);
3692 value_message <<
value;
3693 RecordProperty(
key, value_message.GetString().c_str());
3702 UnitTest::GetInstance()->AddTestPartResult(
3717 bool Test::HasSameFixtureClass() {
3719 const TestCase*
const test_case = impl->current_test_case();
3722 const TestInfo*
const first_test_info = test_case->test_info_list()[0];
3723 const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_;
3724 const char*
const first_test_name = first_test_info->name();
3727 const TestInfo*
const this_test_info = impl->current_test_info();
3728 const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_;
3729 const char*
const this_test_name = this_test_info->name();
3731 if (this_fixture_id != first_fixture_id) {
3737 if (first_is_TEST || this_is_TEST) {
3744 const char*
const TEST_name =
3745 first_is_TEST ? first_test_name : this_test_name;
3746 const char*
const TEST_F_name =
3747 first_is_TEST ? this_test_name : first_test_name;
3750 <<
"All tests in the same test case must use the same test fixture\n"
3751 <<
"class, so mixing TEST_F and TEST in the same test case is\n"
3752 <<
"illegal. In test case " << this_test_info->test_case_name()
3754 <<
"test " << TEST_F_name <<
" is defined using TEST_F but\n"
3755 <<
"test " << TEST_name <<
" is defined using TEST. You probably\n"
3756 <<
"want to change the TEST to TEST_F or move it to another test\n"
3762 <<
"All tests in the same test case must use the same test fixture\n"
3763 <<
"class. However, in test case "
3764 << this_test_info->test_case_name() <<
",\n"
3765 <<
"you defined test " << first_test_name
3766 <<
" and test " << this_test_name <<
"\n"
3767 <<
"using two different test fixture classes. This can happen if\n"
3768 <<
"the two classes are from different namespaces or translation\n"
3769 <<
"units and have the same name. You should probably rename one\n"
3770 <<
"of the classes to put the tests into different test cases.";
3784 static std::string* FormatSehExceptionMessage(DWORD exception_code,
3785 const char* location) {
3787 message <<
"SEH exception with code 0x" << std::setbase(16) <<
3788 exception_code << std::setbase(10) <<
" thrown in " << location <<
".";
3793 #endif // GTEST_HAS_SEH
3797 #if GTEST_HAS_EXCEPTIONS
3801 const char* location) {
3806 message <<
"Unknown C++ exception";
3808 message <<
" thrown in " << location <<
".";
3814 const TestPartResult& test_part_result);
3816 GoogleTestFailureException::GoogleTestFailureException(
3817 const TestPartResult& failure)
3820 #endif // GTEST_HAS_EXCEPTIONS
3830 template <
class T,
typename Result>
3835 return (object->*
method)();
3836 } __except (internal::UnitTestOptions::GTestShouldProcessSEH(
3837 GetExceptionCode())) {
3841 std::string* exception_message = FormatSehExceptionMessage(
3842 GetExceptionCode(), location);
3844 *exception_message);
3845 delete exception_message;
3846 return static_cast<Result>(0);
3850 return (object->*
method)();
3851 #endif // GTEST_HAS_SEH
3857 template <
class T,
typename Result>
3884 #if GTEST_HAS_EXCEPTIONS
3887 }
catch (
const internal::GoogleTestFailureException&) {
3892 }
catch (
const std::exception& e) {
3894 TestPartResult::kFatalFailure,
3895 FormatCxxExceptionMessage(
e.what(), location));
3898 TestPartResult::kFatalFailure,
3899 FormatCxxExceptionMessage(NULL, location));
3901 return static_cast<Result>(0);
3904 #endif // GTEST_HAS_EXCEPTIONS
3906 return (object->*
method)();
3914 if (!HasSameFixtureClass())
return;
3917 impl->os_stack_trace_getter()->UponLeavingGTest();
3920 if (!HasFatalFailure()) {
3921 impl->os_stack_trace_getter()->UponLeavingGTest();
3923 this, &Test::TestBody,
"the test body");
3929 impl->os_stack_trace_getter()->UponLeavingGTest();
3931 this, &Test::TearDown,
"TearDown()");
3935 bool Test::HasFatalFailure() {
3940 bool Test::HasNonfatalFailure() {
3942 HasNonfatalFailure();
3949 TestInfo::TestInfo(
const std::string& a_test_case_name,
3951 const char* a_type_param,
3952 const char* a_value_param,
3953 internal::CodeLocation a_code_location,
3955 internal::TestFactoryBase* factory)
3956 : test_case_name_(a_test_case_name),
3958 type_param_(a_type_param ?
new std::
string(a_type_param) : NULL),
3959 value_param_(a_value_param ?
new std::
string(a_value_param) : NULL),
3960 location_(a_code_location),
3961 fixture_class_id_(fixture_class_id),
3963 is_disabled_(
false),
3964 matches_filter_(
false),
3969 TestInfo::~TestInfo() {
delete factory_; }
3992 const char* test_case_name,
3994 const char* type_param,
3995 const char* value_param,
3996 CodeLocation code_location,
4000 TestFactoryBase* factory) {
4001 TestInfo*
const test_info =
4002 new TestInfo(test_case_name,
name, type_param, value_param,
4003 code_location, fixture_class_id, factory);
4008 #if GTEST_HAS_PARAM_TEST
4013 <<
"Attempted redefinition of test case " << test_case_name <<
".\n"
4014 <<
"All tests in the same test case must use the same test fixture\n"
4015 <<
"class. However, in test case " << test_case_name <<
", you tried\n"
4016 <<
"to define a test using a fixture class different from the one\n"
4017 <<
"used earlier. This can happen if the two fixture classes are\n"
4018 <<
"from different namespaces and have the same name. You should\n"
4019 <<
"probably rename one of the classes to put the tests into different\n"
4024 code_location.
line).c_str(),
4025 errors.GetString().c_str());
4027 #endif // GTEST_HAS_PARAM_TEST
4046 explicit TestNameIs(
const char*
name)
4050 bool operator()(
const TestInfo * test_info)
const {
4051 return test_info && test_info->name() ==
name_;
4065 void UnitTestImpl::RegisterParameterizedTests() {
4066 #if GTEST_HAS_PARAM_TEST
4067 if (!parameterized_tests_registered_) {
4068 parameterized_test_registry_.RegisterTests();
4069 parameterized_tests_registered_ =
true;
4079 if (!should_run_)
return;
4083 impl->set_current_test_info(
this);
4085 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
4088 repeater->OnTestStart(*
this);
4092 impl->os_stack_trace_getter()->UponLeavingGTest();
4096 factory_, &internal::TestFactoryBase::CreateTest,
4097 "the test fixture's constructor");
4101 if ((
test != NULL) && !Test::HasFatalFailure()) {
4108 impl->os_stack_trace_getter()->UponLeavingGTest();
4110 test, &Test::DeleteSelf_,
"the test fixture's destructor");
4115 repeater->OnTestEnd(*
this);
4119 impl->set_current_test_info(NULL);
4125 int TestCase::successful_test_count()
const {
4126 return CountIf(test_info_list_, TestPassed);
4130 int TestCase::failed_test_count()
const {
4131 return CountIf(test_info_list_, TestFailed);
4135 int TestCase::reportable_disabled_test_count()
const {
4136 return CountIf(test_info_list_, TestReportableDisabled);
4140 int TestCase::disabled_test_count()
const {
4141 return CountIf(test_info_list_, TestDisabled);
4145 int TestCase::reportable_test_count()
const {
4146 return CountIf(test_info_list_, TestReportable);
4150 int TestCase::test_to_run_count()
const {
4151 return CountIf(test_info_list_, ShouldRunTest);
4155 int TestCase::total_test_count()
const {
4156 return static_cast<int>(test_info_list_.size());
4172 type_param_(a_type_param ?
new std::
string(a_type_param) : NULL),
4173 set_up_tc_(set_up_tc),
4174 tear_down_tc_(tear_down_tc),
4258 const char * singular_form,
4259 const char * plural_form) {
4261 (
count == 1 ? singular_form : plural_form);
4291 return "Unknown result type";
4304 << test_part_result.
message()).GetString();
4317 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4321 ::OutputDebugStringA(
result.c_str());
4322 ::OutputDebugStringA(
"\n");
4335 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \
4336 !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
4343 case COLOR_YELLOW:
return FOREGROUND_RED | FOREGROUND_GREEN;
4357 default:
return NULL;
4361 #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4365 const char*
const gtest_color =
GTEST_FLAG(color).c_str();
4368 #if GTEST_OS_WINDOWS
4371 return stdout_is_tty;
4375 const bool term_supports_color =
4387 return stdout_is_tty && term_supports_color;
4388 #endif // GTEST_OS_WINDOWS
4408 #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS || \
4409 GTEST_OS_IOS || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT
4412 static const bool in_color_mode =
4414 const bool use_color = in_color_mode && (color !=
COLOR_DEFAULT);
4415 #endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
4424 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \
4425 !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
4426 const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
4429 CONSOLE_SCREEN_BUFFER_INFO buffer_info;
4430 GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
4431 const WORD old_color_attrs = buffer_info.wAttributes;
4437 SetConsoleTextAttribute(stdout_handle,
4438 GetColorAttribute(color) | FOREGROUND_INTENSITY);
4443 SetConsoleTextAttribute(stdout_handle, old_color_attrs);
4448 #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4458 const char*
const type_param = test_info.
type_param();
4459 const char*
const value_param = test_info.
value_param();
4461 if (type_param != NULL || value_param != NULL) {
4463 if (type_param != NULL) {
4465 if (value_param != NULL)
4468 if (value_param != NULL) {
4505 const UnitTest& unit_test,
int iteration) {
4507 printf(
"\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
4509 const char*
const filter =
GTEST_FLAG(filter).c_str();
4521 "Note: This is test shard %d of %s.\n",
4522 static_cast<int>(shard_index) + 1,
4528 "Note: Randomizing tests' orders with a seed of %d .\n",
4533 printf(
"Running %s from %s.\n",
4542 printf(
"Global test environment set-up.\n");
4550 printf(
"%s from %s", counts.c_str(), test_case.name());
4551 if (test_case.type_param() == NULL) {
4561 PrintTestName(test_info.test_case_name(), test_info.name());
4568 const TestPartResult&
result) {
4579 if (test_info.result()->Passed()) {
4584 PrintTestName(test_info.test_case_name(), test_info.name());
4585 if (test_info.result()->Failed())
4590 test_info.result()->elapsed_time()).c_str());
4603 printf(
"%s from %s (%s ms total)\n\n",
4604 counts.c_str(), test_case.name(),
4612 printf(
"Global test environment tear-down\n");
4618 const int failed_test_count = unit_test.failed_test_count();
4619 if (failed_test_count == 0) {
4623 for (
int i = 0;
i < unit_test.total_test_case_count(); ++
i) {
4624 const TestCase& test_case = *unit_test.GetTestCase(i);
4625 if (!test_case.should_run() || (test_case.failed_test_count() == 0)) {
4628 for (
int j = 0;
j < test_case.total_test_count(); ++
j) {
4629 const TestInfo& test_info = *test_case.GetTestInfo(j);
4630 if (!test_info.should_run() || test_info.result()->Passed()) {
4634 printf(
"%s.%s", test_case.name(), test_info.name());
4644 printf(
"%s from %s ran.",
4656 if (!unit_test.Passed()) {
4657 const int failed_test_count = unit_test.failed_test_count();
4665 int num_disabled = unit_test.reportable_disabled_test_count();
4666 if (num_disabled && !
GTEST_FLAG(also_run_disabled_tests)) {
4671 " YOU HAVE %d DISABLED %s\n\n",
4673 num_disabled == 1 ?
"TEST" :
"TESTS");
4684 class TestEventRepeater :
public TestEventListener {
4742 #define GTEST_REPEATER_METHOD_(Name, Type) \
4743 void TestEventRepeater::Name(const Type& parameter) { \
4744 if (forwarding_enabled_) { \
4745 for (size_t i = 0; i < listeners_.size(); i++) { \
4746 listeners_[i]->Name(parameter); \
4752 #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
4753 void TestEventRepeater::Name(const Type& parameter) { \
4754 if (forwarding_enabled_) { \
4755 for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \
4756 listeners_[i]->Name(parameter); \
4773 #undef GTEST_REPEATER_METHOD_
4774 #undef GTEST_REVERSE_REPEATER_METHOD_
4780 listeners_[
i]->OnTestIterationStart(unit_test, iteration);
4788 for (
int i =
static_cast<int>(
listeners_.size()) - 1; i >= 0; i--) {
4789 listeners_[
i]->OnTestIterationEnd(unit_test, iteration);
4797 class XmlUnitTestResultPrinter :
public EmptyTestEventListener {
4807 return c == 0x9 || c == 0xA || c == 0xD;
4846 const char* test_case_name,
4871 : output_file_(output_file) {
4873 fprintf(
stderr,
"XML output file may not be null\n");
4882 FILE* xmlout = NULL;
4886 if (
output_dir.CreateDirectoriesRecursively()) {
4889 if (xmlout == NULL) {
4901 "Unable to open file \"%s\"\n",
4906 std::stringstream
stream;
4928 for (
size_t i = 0;
i <
str.size(); ++
i) {
4964 return m.GetString();
4974 for (std::string::const_iterator
it =
str.begin();
it !=
str.end(); ++
it)
4999 ::std::stringstream ss;
5000 ss << (static_cast<double>(ms) * 1
e-3);
5005 #if defined(_MSC_VER)
5007 #elif defined(__MINGW32__) || defined(__MINGW64__)
5010 struct tm* tm_ptr = localtime(&
seconds);
5023 struct tm time_struct;
5038 const char* segment =
data;
5041 const char*
const next_segment = strstr(segment,
"]]>");
5042 if (next_segment != NULL) {
5044 segment,
static_cast<std::streamsize
>(next_segment - segment));
5045 *
stream <<
"]]>]]><![CDATA[";
5046 segment = next_segment + strlen(
"]]>");
5060 const std::vector<std::string>& allowed_names =
5064 allowed_names.end())
5074 const char* test_case_name,
5075 const TestInfo& test_info) {
5076 const TestResult&
result = *test_info.result();
5082 if (test_info.value_param() != NULL) {
5084 test_info.value_param());
5086 if (test_info.type_param() != NULL) {
5091 test_info.should_run() ?
"run" :
"notrun");
5098 for (
int i = 0;
i <
result.total_part_count(); ++
i) {
5099 const TestPartResult& part =
result.GetTestPartResult(
i);
5100 if (part.failed()) {
5105 part.file_name(), part.line_number());
5106 const string summary = location +
"\n" + part.summary();
5107 *
stream <<
" <failure message=\""
5110 const string detail = location +
"\n" + part.message();
5112 *
stream <<
"</failure>\n";
5119 *
stream <<
" </testcase>\n";
5126 *
stream <<
" <" << kTestsuite;
5133 stream, kTestsuite,
"disabled",
5145 *
stream <<
" </" << kTestsuite <<
">\n";
5153 *
stream <<
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
5154 *
stream <<
"<" << kTestsuites;
5161 stream, kTestsuites,
"disabled",
5165 stream, kTestsuites,
"timestamp",
5184 *
stream <<
"</" << kTestsuites <<
">\n";
5190 const TestResult&
result) {
5192 for (
int i = 0;
i <
result.test_property_count(); ++
i) {
5193 const TestProperty&
property =
result.GetTestProperty(
i);
5194 attributes <<
" " <<
property.key() <<
"="
5197 return attributes.GetString();
5202 #if GTEST_CAN_STREAM_RESULTS_
5209 string StreamingListener::UrlEncode(
const char*
str) {
5228 void StreamingListener::SocketWriter::MakeConnection() {
5230 <<
"MakeConnection() can't be called when there is already a connection.";
5233 memset(&hints, 0,
sizeof(hints));
5240 const int error_num = getaddrinfo(
5241 host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
5242 if (error_num != 0) {
5244 << gai_strerror(error_num);
5248 for (
addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != NULL;
5249 cur_addr = cur_addr->
ai_next) {
5251 cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol);
5252 if (sockfd_ != -1) {
5254 if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
5261 freeaddrinfo(servinfo);
5263 if (sockfd_ == -1) {
5265 << host_name_ <<
":" << port_num_;
5270 #endif // GTEST_CAN_STREAM_RESULTS__
5281 trace.message =
message.GetString();
5307 class ScopedPrematureExitFile {
5312 if (premature_exit_filepath != NULL && *premature_exit_filepath !=
'\0') {
5317 fwrite(
"0", 1, 1, pfile);
5340 default_result_printer_(NULL),
5341 default_xml_generator_(NULL) {
5351 repeater_->Append(listener);
5358 if (listener == default_result_printer_)
5359 default_result_printer_ = NULL;
5360 else if (listener == default_xml_generator_)
5361 default_xml_generator_ = NULL;
5362 return repeater_->Release(listener);
5375 if (default_result_printer_ != listener) {
5378 delete Release(default_result_printer_);
5379 default_result_printer_ = listener;
5380 if (listener != NULL)
5391 if (default_xml_generator_ != listener) {
5394 delete Release(default_xml_generator_);
5395 default_xml_generator_ = listener;
5396 if (listener != NULL)
5404 return repeater_->forwarding_enabled();
5408 repeater_->set_forwarding_enabled(
false);
5432 #if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
5433 static UnitTest*
const instance =
new UnitTest;
5438 #endif // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
5443 return impl()->successful_test_case_count();
5448 return impl()->failed_test_case_count();
5453 return impl()->total_test_case_count();
5459 return impl()->test_case_to_run_count();
5464 return impl()->successful_test_count();
5472 return impl()->reportable_disabled_test_count();
5477 return impl()->disabled_test_count();
5482 return impl()->reportable_test_count();
5494 return impl()->start_timestamp();
5499 return impl()->elapsed_time();
5512 return impl()->GetTestCase(i);
5518 return *impl()->ad_hoc_test_result();
5524 return impl()->GetMutableTestCase(
i);
5530 return *impl()->listeners();
5548 impl_->environments().push_back(
env);
5558 const char* file_name,
5566 if (
impl_->gtest_trace_stack().size() > 0) {
5569 for (
int i =
static_cast<int>(
impl_->gtest_trace_stack().size());
5571 const internal::TraceInfo& trace =
impl_->gtest_trace_stack()[
i - 1];
5573 <<
" " << trace.message;
5577 if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) {
5581 const TestPartResult
result =
5582 TestPartResult(
result_type, file_name, line_number,
5583 msg.GetString().c_str());
5584 impl_->GetTestPartResultReporterForCurrentThread()->
5585 ReportTestPartResult(
result);
5594 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
5604 *
static_cast<volatile int*
>(NULL) = 1;
5605 #endif // GTEST_OS_WINDOWS
5607 #if GTEST_HAS_EXCEPTIONS
5608 throw internal::GoogleTestFailureException(
result);
5634 const bool in_death_test_child_process =
5658 const internal::ScopedPrematureExitFile premature_exit_file(
5659 in_death_test_child_process ?
5664 impl()->set_catch_exceptions(
GTEST_FLAG(catch_exceptions));
5671 if (impl()->catch_exceptions() || in_death_test_child_process) {
5672 # if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
5674 SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
5675 SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
5676 # endif // !GTEST_OS_WINDOWS_MOBILE
5678 # if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
5682 _set_error_mode(_OUT_TO_STDERR);
5685 # if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
5698 _set_abort_behavior(
5700 _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
5703 #endif // GTEST_HAS_SEH
5708 "auxiliary test code (environments or event listeners)") ? 0 : 1;
5714 return impl_->original_working_dir_.c_str();
5722 return impl_->current_test_case();
5730 return impl_->current_test_info();
5736 #if GTEST_HAS_PARAM_TEST
5739 internal::ParameterizedTestCaseRegistry&
5742 return impl_->parameterized_test_registry();
5744 #endif // GTEST_HAS_PARAM_TEST
5748 impl_ =
new internal::UnitTestImpl(
this);
5761 impl_->gtest_trace_stack().push_back(trace);
5768 impl_->gtest_trace_stack().pop_back();
5776 default_global_test_part_result_reporter_(this),
5777 default_per_thread_test_part_result_reporter_(this),
5779 global_test_part_result_repoter_(
5780 &default_global_test_part_result_reporter_),
5781 per_thread_test_part_result_reporter_(
5782 &default_per_thread_test_part_result_reporter_),
5784 parameterized_test_registry_(),
5785 parameterized_tests_registered_(
false),
5787 last_death_test_case_(-1),
5788 current_test_case_(NULL),
5789 current_test_info_(NULL),
5790 ad_hoc_test_result_(),
5791 os_stack_trace_getter_(NULL),
5792 post_flag_parse_init_performed_(
false),
5795 start_timestamp_(0),
5797 #
if GTEST_HAS_DEATH_TEST
5798 death_test_factory_(
new DefaultDeathTestFactory),
5801 catch_exceptions_(
false) {
5805 UnitTestImpl::~UnitTestImpl() {
5807 ForEach(test_cases_, internal::Delete<TestCase>);
5810 ForEach(environments_, internal::Delete<Environment>);
5812 delete os_stack_trace_getter_;
5820 void UnitTestImpl::RecordProperty(
const TestProperty& test_property) {
5824 if (current_test_info_ != NULL) {
5825 xml_element =
"testcase";
5827 }
else if (current_test_case_ != NULL) {
5828 xml_element =
"testsuite";
5829 test_result = &(current_test_case_->ad_hoc_test_result_);
5831 xml_element =
"testsuites";
5834 test_result->RecordProperty(xml_element, test_property);
5837 #if GTEST_HAS_DEATH_TEST
5840 void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
5841 if (internal_run_death_test_flag_.get() != NULL)
5842 listeners()->SuppressEventForwarding();
5844 #endif // GTEST_HAS_DEATH_TEST
5848 void UnitTestImpl::ConfigureXmlOutput() {
5849 const std::string& output_format = UnitTestOptions::GetOutputFormat();
5850 if (output_format ==
"xml") {
5851 listeners()->SetDefaultXmlGenerator(
new XmlUnitTestResultPrinter(
5852 UnitTestOptions::GetAbsolutePathToOutputFile().
c_str()));
5853 }
else if (output_format !=
"") {
5854 printf(
"WARNING: unrecognized output format \"%s\" ignored.\n",
5855 output_format.c_str());
5860 #if GTEST_CAN_STREAM_RESULTS_
5863 void UnitTestImpl::ConfigureStreamingOutput() {
5867 if (
pos != std::string::npos) {
5868 listeners()->Append(
new StreamingListener(
target.substr(0,
pos),
5871 printf(
"WARNING: unrecognized streaming target \"%s\" ignored.\n",
5877 #endif // GTEST_CAN_STREAM_RESULTS_
5884 void UnitTestImpl::PostFlagParsingInit() {
5886 if (!post_flag_parse_init_performed_) {
5887 post_flag_parse_init_performed_ =
true;
5889 #if defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
5891 listeners()->Append(
new GTEST_CUSTOM_TEST_EVENT_LISTENER_());
5892 #endif // defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
5894 #if GTEST_HAS_DEATH_TEST
5895 InitDeathTestSubprocessControlInfo();
5896 SuppressTestEventsIfInSubprocess();
5897 #endif // GTEST_HAS_DEATH_TEST
5902 RegisterParameterizedTests();
5906 ConfigureXmlOutput();
5908 #if GTEST_CAN_STREAM_RESULTS_
5910 ConfigureStreamingOutput();
5911 #endif // GTEST_CAN_STREAM_RESULTS_
5931 return test_case != NULL && strcmp(test_case->
name(),
name_.c_str()) == 0;
5950 TestCase* UnitTestImpl::GetTestCase(
const char* test_case_name,
5951 const char* type_param,
5955 const std::vector<TestCase*>::const_iterator test_case =
5956 std::find_if(test_cases_.begin(), test_cases_.end(),
5959 if (test_case != test_cases_.end())
5964 new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc);
5973 ++last_death_test_case_;
5974 test_cases_.insert(test_cases_.begin() + last_death_test_case_,
5978 test_cases_.push_back(new_test_case);
5981 test_case_indices_.push_back(
static_cast<int>(test_case_indices_.size()));
5982 return new_test_case;
6003 "\nThis test program did NOT call ::testing::InitGoogleTest "
6004 "before calling RUN_ALL_TESTS(). Please fix it.\n");
6014 PostFlagParsingInit();
6023 bool in_subprocess_for_death_test =
false;
6025 #if GTEST_HAS_DEATH_TEST
6026 in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL);
6027 # if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
6028 if (in_subprocess_for_death_test) {
6029 GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_();
6031 # endif // defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
6032 #endif // GTEST_HAS_DEATH_TEST
6035 in_subprocess_for_death_test);
6039 const bool has_tests_to_run = FilterTests(should_shard
6040 ? HONOR_SHARDING_PROTOCOL
6041 : IGNORE_SHARDING_PROTOCOL) > 0;
6046 ListTestsMatchingFilter();
6054 bool failed =
false;
6056 TestEventListener* repeater = listeners()->repeater();
6059 repeater->OnTestProgramStart(*
parent_);
6063 const int repeat = in_subprocess_for_death_test ? 1 :
GTEST_FLAG(repeat);
6065 const bool forever = repeat < 0;
6066 for (
int i = 0; forever ||
i != repeat;
i++) {
6069 ClearNonAdHocTestResult();
6074 if (has_tests_to_run &&
GTEST_FLAG(shuffle)) {
6075 random()->Reseed(random_seed_);
6083 repeater->OnTestIterationStart(*
parent_, i);
6086 if (has_tests_to_run) {
6088 repeater->OnEnvironmentsSetUpStart(*
parent_);
6090 repeater->OnEnvironmentsSetUpEnd(*
parent_);
6095 for (
int test_index = 0; test_index < total_test_case_count();
6097 GetMutableTestCase(test_index)->Run();
6102 repeater->OnEnvironmentsTearDownStart(*
parent_);
6103 std::for_each(environments_.rbegin(), environments_.rend(),
6105 repeater->OnEnvironmentsTearDownEnd(*
parent_);
6111 repeater->OnTestIterationEnd(*
parent_, i);
6132 repeater->OnTestProgramEnd(*
parent_);
6143 if (test_shard_file != NULL) {
6147 "Could not write to the test shard status file \"%s\" "
6148 "specified by the %s environment variable.\n",
6164 const char* shard_index_env,
6165 bool in_subprocess_for_death_test) {
6166 if (in_subprocess_for_death_test) {
6173 if (total_shards == -1 && shard_index == -1) {
6175 }
else if (total_shards == -1 && shard_index != -1) {
6177 <<
"Invalid environment variables: you have "
6183 }
else if (total_shards != -1 && shard_index == -1) {
6185 <<
"Invalid environment variables: you have "
6191 }
else if (shard_index < 0 || shard_index >= total_shards) {
6193 <<
"Invalid environment variables: we require 0 <= "
6202 return total_shards > 1;
6210 if (str_val == NULL) {
6227 return (test_id % total_shards) == shard_index;
6237 int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
6238 const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?
6240 const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?
6247 int num_runnable_tests = 0;
6248 int num_selected_tests = 0;
6249 for (
size_t i = 0;
i < test_cases_.size();
i++) {
6250 TestCase*
const test_case = test_cases_[
i];
6251 const std::string &test_case_name = test_case->name();
6252 test_case->set_should_run(
false);
6254 for (
size_t j = 0;
j < test_case->test_info_list().
size();
j++) {
6255 TestInfo*
const test_info = test_case->test_info_list()[
j];
6259 const bool is_disabled =
6264 test_info->is_disabled_ = is_disabled;
6266 const bool matches_filter =
6269 test_info->matches_filter_ = matches_filter;
6271 const bool is_runnable =
6272 (
GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
6275 const bool is_selected = is_runnable &&
6276 (shard_tests == IGNORE_SHARDING_PROTOCOL ||
6278 num_runnable_tests));
6280 num_runnable_tests += is_runnable;
6281 num_selected_tests += is_selected;
6283 test_info->should_run_ = is_selected;
6284 test_case->set_should_run(test_case->should_run() || is_selected);
6287 return num_selected_tests;
6296 for (
int i = 0; *
str !=
'\0'; ++
str) {
6297 if (
i >= max_length) {
6313 void UnitTestImpl::ListTestsMatchingFilter() {
6315 const int kMaxParamLength = 250;
6317 for (
size_t i = 0;
i < test_cases_.size();
i++) {
6318 const TestCase*
const test_case = test_cases_[
i];
6319 bool printed_test_case_name =
false;
6325 if (!printed_test_case_name) {
6326 printed_test_case_name =
true;
6355 void UnitTestImpl::set_os_stack_trace_getter(
6356 OsStackTraceGetterInterface* getter) {
6357 if (os_stack_trace_getter_ != getter) {
6358 delete os_stack_trace_getter_;
6359 os_stack_trace_getter_ = getter;
6366 OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
6367 if (os_stack_trace_getter_ == NULL) {
6368 #ifdef GTEST_OS_STACK_TRACE_GETTER_
6369 os_stack_trace_getter_ =
new GTEST_OS_STACK_TRACE_GETTER_;
6371 os_stack_trace_getter_ =
new OsStackTraceGetter;
6372 #endif // GTEST_OS_STACK_TRACE_GETTER_
6375 return os_stack_trace_getter_;
6380 TestResult* UnitTestImpl::current_test_result() {
6381 return current_test_info_ ?
6382 &(current_test_info_->result_) : &ad_hoc_test_result_;
6387 void UnitTestImpl::ShuffleTests() {
6389 ShuffleRange(random(), 0, last_death_test_case_ + 1, &test_case_indices_);
6393 static_cast<int>(test_cases_.size()), &test_case_indices_);
6396 for (
size_t i = 0;
i < test_cases_.size();
i++) {
6397 test_cases_[
i]->ShuffleTests(random());
6402 void UnitTestImpl::UnshuffleTests() {
6403 for (
size_t i = 0;
i < test_cases_.size();
i++) {
6405 test_cases_[
i]->UnshuffleTests();
6407 test_case_indices_[
i] =
static_cast<int>(
i);
6431 class ClassUniqueToAlwaysTrue {};
6434 bool IsTrue(
bool condition) {
return condition; }
6437 #if GTEST_HAS_EXCEPTIONS
6441 throw ClassUniqueToAlwaysTrue();
6442 #endif // GTEST_HAS_EXCEPTIONS
6450 const size_t prefix_len = strlen(
prefix);
6451 if (strncmp(*pstr,
prefix, prefix_len) == 0) {
6452 *pstr += prefix_len;
6465 bool def_optional) {
6467 if (
str == NULL ||
flag == NULL)
return NULL;
6471 const size_t flag_len = flag_str.length();
6472 if (strncmp(
str, flag_str.c_str(), flag_len) != 0)
return NULL;
6475 const char* flag_end =
str + flag_len;
6478 if (def_optional && (flag_end[0] ==
'\0')) {
6485 if (flag_end[0] !=
'=')
return NULL;
6488 return flag_end + 1;
6506 if (value_str == NULL)
return false;
6509 *
value = !(*value_str ==
'0' || *value_str ==
'f' || *value_str ==
'F');
6523 if (value_str == NULL)
return false;
6540 if (value_str == NULL)
return false;
6581 const char* p = strchr(
str,
'@');
6589 const char ch = p[1];
6593 }
else if (
ch ==
'D') {
6595 }
else if (
ch ==
'R') {
6597 }
else if (
ch ==
'G') {
6599 }
else if (
ch ==
'Y') {
6608 "This program contains tests written using " GTEST_NAME_ ". You can use the\n"
6609 "following command line flags to control its behavior:\n"
6613 " List the names of all tests instead of running them. The name of\n"
6614 " TEST(Foo, Bar) is \"Foo.Bar\".\n"
6616 "[@G-@YNEGATIVE_PATTERNS]@D\n"
6617 " Run only the tests whose name matches one of the positive patterns but\n"
6618 " none of the negative patterns. '?' matches any single character; '*'\n"
6619 " matches any substring; ':' separates two patterns.\n"
6621 " Run all disabled tests too.\n"
6625 " Run the tests repeatedly; use a negative count to repeat forever.\n"
6627 " Randomize tests' orders on every iteration.\n"
6629 " Random number seed to use for shuffling test orders (between 1 and\n"
6630 " 99999, or 0 to use a seed based on the current time).\n"
6634 " Enable/disable colored output. The default is @Gauto@D.\n"
6636 " Don't print the elapsed time of each test.\n"
6639 " Generate an XML report in the given directory or with the given file\n"
6640 " name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n"
6641 #if GTEST_CAN_STREAM_RESULTS_
6643 " Stream test results to the given server.\n"
6644 #endif // GTEST_CAN_STREAM_RESULTS_
6646 "Assertion Behavior:\n"
6647 #if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
6649 " Set the default death test style.\n"
6650 #endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
6652 " Turn assertion failures into debugger break-points.\n"
6654 " Turn assertion failures into C++ exceptions.\n"
6656 " Do not report exceptions as test failures. Instead, allow them\n"
6657 " to crash the program or throw a pop-up (on Windows).\n"
6660 "the corresponding\n"
6661 "environment variable of a flag (all letters in upper-case). For example, to\n"
6663 "color=no@D or set\n"
6666 "For more information, please read the " GTEST_NAME_ " documentation at\n"
6668 "(not one in your own code or tests), please report it to\n"
6700 #if GTEST_USE_OWN_FLAGFILE_FLAG_
6705 "Unable to open file \"%s\"\n",
6712 std::vector<std::string>
lines;
6714 for (
size_t i = 0;
i <
lines.size(); ++
i) {
6721 #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
6726 template <
typename CharType>
6728 for (
int i = 1;
i < *argc;
i++) {
6730 const char*
const arg = arg_string.c_str();
6736 bool remove_flag =
false;
6739 #if GTEST_USE_OWN_FLAGFILE_FLAG_
6743 #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
6744 }
else if (arg_string ==
"--help" || arg_string ==
"-h" ||
6745 arg_string ==
"-?" || arg_string ==
"/?" ||
6757 for (
int j = i;
j != *argc;
j++) {
6758 argv[
j] = argv[
j + 1];
6791 template <
typename CharType>
6796 if (*argc <= 0)
return;
6799 for (
int i = 0;
i != *argc;
i++) {
6819 #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6820 GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
6821 #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6823 #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6829 #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6830 GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
6831 #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6833 #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6871 #if GTEST_HAS_DEATH_TEST
6874 # include <crt_externs.h>
6875 # endif // GTEST_OS_MAC
6879 # include <limits.h>
6882 # include <signal.h>
6883 # endif // GTEST_OS_LINUX
6885 # include <stdarg.h>
6887 # if GTEST_OS_WINDOWS
6888 # include <windows.h>
6890 # include <sys/mman.h>
6891 # include <sys/wait.h>
6892 # endif // GTEST_OS_WINDOWS
6896 # endif // GTEST_OS_QNX
6898 #endif // GTEST_HAS_DEATH_TEST
6906 #define GTEST_IMPLEMENTATION_ 1
6907 #undef GTEST_IMPLEMENTATION_
6919 "Indicates how to run a death test in a forked child process: "
6920 "\"threadsafe\" (child process re-executes the test binary "
6921 "from the beginning, running only the specific death test) or "
6922 "\"fast\" (child process runs the death test immediately "
6926 death_test_use_fork,
6928 "Instructs to use fork()/_exit() instead of clone() in death tests. "
6929 "Ignored and always uses fork() on POSIX systems where clone() is not "
6930 "implemented. Useful when running under valgrind or similar tools if "
6931 "those do not support clone(). Valgrind 3.3.1 will just fail if "
6932 "it sees an unsupported combination of clone() flags. "
6933 "It is not recommended to use this flag w/o valgrind though it will "
6934 "work in 99% of the cases. Once valgrind is fixed, this flag will "
6935 "most likely be removed.");
6939 internal_run_death_test,
"",
6940 "Indicates the file, line number, temporal index of "
6941 "the single death test to run, and a file descriptor to "
6942 "which a success code may be sent, all separated by "
6943 "the '|' characters. This flag is specified if and only if the current "
6944 "process is a sub-process launched for running a thread-safe "
6945 "death test. FOR INTERNAL USE ONLY.");
6948 #if GTEST_HAS_DEATH_TEST
6954 # if !GTEST_OS_WINDOWS
6955 static bool g_in_fast_death_test_child =
false;
6963 bool InDeathTestChild() {
6964 # if GTEST_OS_WINDOWS
6968 return !
GTEST_FLAG(internal_run_death_test).empty();
6972 if (
GTEST_FLAG(death_test_style) ==
"threadsafe")
6973 return !
GTEST_FLAG(internal_run_death_test).empty();
6975 return g_in_fast_death_test_child;
6986 bool ExitedWithCode::operator()(
int exit_status)
const {
6987 # if GTEST_OS_WINDOWS
6989 return exit_status == exit_code_;
6993 return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;
6995 # endif // GTEST_OS_WINDOWS
6998 # if !GTEST_OS_WINDOWS
7000 KilledBySignal::KilledBySignal(
int signum) : signum_(signum) {
7004 bool KilledBySignal::operator()(
int exit_status)
const {
7005 # if defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)
7008 if (GTEST_KILLED_BY_SIGNAL_OVERRIDE_(signum_, exit_status, &
result)) {
7012 # endif // defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)
7013 return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;
7015 # endif // !GTEST_OS_WINDOWS
7026 # if GTEST_OS_WINDOWS
7028 m <<
"Exited with exit status " <<
exit_code;
7033 m <<
"Exited with exit status " << WEXITSTATUS(
exit_code);
7035 m <<
"Terminated by signal " << WTERMSIG(
exit_code);
7039 m <<
" (core dumped)";
7042 # endif // GTEST_OS_WINDOWS
7044 return m.GetString();
7049 bool ExitedUnsuccessfully(
int exit_status) {
7050 return !ExitedWithCode(0)(exit_status);
7053 # if !GTEST_OS_WINDOWS
7058 static std::string DeathTestThreadWarning(
size_t thread_count) {
7060 msg <<
"Death tests use fork(), which is unsafe particularly"
7061 <<
" in a threaded context. For this test, " <<
GTEST_NAME_ <<
" ";
7062 if (thread_count == 0)
7063 msg <<
"couldn't detect the number of threads.";
7065 msg <<
"detected " << thread_count <<
" threads.";
7066 return msg.GetString();
7068 # endif // !GTEST_OS_WINDOWS
7071 static const char kDeathTestLived =
'L';
7072 static const char kDeathTestReturned =
'R';
7073 static const char kDeathTestThrew =
'T';
7074 static const char kDeathTestInternalError =
'I';
7085 enum DeathTestOutcome {
IN_PROGRESS, DIED, LIVED, RETURNED, THREW };
7096 const InternalRunDeathTestFlag*
const flag =
7100 fputc(kDeathTestInternalError, parent);
7101 fprintf(parent,
"%s",
message.c_str());
7113 # define GTEST_DEATH_TEST_CHECK_(expression) \
7115 if (!::testing::internal::IsTrue(expression)) { \
7117 ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
7118 + ::testing::internal::StreamableToString(__LINE__) + ": " \
7121 } while (::testing::internal::AlwaysFalse())
7130 # define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
7134 gtest_retval = (expression); \
7135 } while (gtest_retval == -1 && errno == EINTR); \
7136 if (gtest_retval == -1) { \
7138 ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
7139 + ::testing::internal::StreamableToString(__LINE__) + ": " \
7140 + #expression + " != -1"); \
7142 } while (::testing::internal::AlwaysFalse())
7153 static void FailFromInternalError(
int fd) {
7163 }
while (num_read == -1 && errno == EINTR);
7165 if (num_read == 0) {
7168 const int last_error = errno;
7170 << GetLastErrnoDescription() <<
" [" << last_error <<
"]";
7176 DeathTest::DeathTest() {
7179 DeathTestAbort(
"Cannot run a death test outside of a TEST or "
7180 "TEST_F construct");
7186 bool DeathTest::Create(
const char* statement,
const RE* regex,
7192 const char* DeathTest::LastMessage() {
7193 return last_death_test_message_.c_str();
7197 last_death_test_message_ =
message;
7203 class DeathTestImpl :
public DeathTest {
7205 DeathTestImpl(
const char* a_statement,
const RE* a_regex)
7206 : statement_(a_statement),
7215 ~DeathTestImpl() { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); }
7217 void Abort(AbortReason reason);
7218 virtual bool Passed(
bool status_ok);
7220 const char* statement()
const {
return statement_; }
7221 const RE* regex()
const {
return regex_; }
7222 bool spawned()
const {
return spawned_; }
7223 void set_spawned(
bool is_spawned) { spawned_ = is_spawned; }
7225 void set_status(
int a_status) {
status_ = a_status; }
7226 DeathTestOutcome outcome()
const {
return outcome_; }
7227 void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; }
7228 int read_fd()
const {
return read_fd_; }
7229 void set_read_fd(
int fd) { read_fd_ = fd; }
7230 int write_fd()
const {
return write_fd_; }
7231 void set_write_fd(
int fd) { write_fd_ = fd; }
7237 void ReadAndInterpretStatusByte();
7242 const char*
const statement_;
7245 const RE*
const regex_;
7251 DeathTestOutcome outcome_;
7266 void DeathTestImpl::ReadAndInterpretStatusByte() {
7276 }
while (
bytes_read == -1 && errno == EINTR);
7282 case kDeathTestReturned:
7283 set_outcome(RETURNED);
7285 case kDeathTestThrew:
7288 case kDeathTestLived:
7291 case kDeathTestInternalError:
7292 FailFromInternalError(read_fd());
7296 <<
"unexpected status byte ("
7297 <<
static_cast<unsigned int>(
flag) <<
")";
7301 << GetLastErrnoDescription();
7303 GTEST_DEATH_TEST_CHECK_SYSCALL_(
posix::Close(read_fd()));
7315 const char status_ch =
7316 reason == TEST_DID_NOT_DIE ? kDeathTestLived :
7317 reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned;
7319 GTEST_DEATH_TEST_CHECK_SYSCALL_(
posix::Write(write_fd(), &status_ch, 1));
7336 for (
size_t at = 0; ; ) {
7337 const size_t line_end =
output.find(
'\n', at);
7338 ret +=
"[ DEATH ] ";
7339 if (line_end == ::std::string::npos) {
7343 ret +=
output.substr(at, line_end + 1 - at);
7371 bool DeathTestImpl::Passed(
bool status_ok) {
7377 bool success =
false;
7380 buffer <<
"Death test: " << statement() <<
"\n";
7381 switch (outcome()) {
7383 buffer <<
" Result: failed to die.\n"
7384 <<
" Error msg:\n" << FormatDeathTestOutput(error_message);
7387 buffer <<
" Result: threw an exception.\n"
7388 <<
" Error msg:\n" << FormatDeathTestOutput(error_message);
7391 buffer <<
" Result: illegal return in test statement.\n"
7392 <<
" Error msg:\n" << FormatDeathTestOutput(error_message);
7396 const bool matched = RE::PartialMatch(error_message.c_str(), *regex());
7400 buffer <<
" Result: died but not with expected error.\n"
7401 <<
" Expected: " << regex()->pattern() <<
"\n"
7402 <<
"Actual msg:\n" << FormatDeathTestOutput(error_message);
7405 buffer <<
" Result: died but not with expected exit code:\n"
7406 <<
" " << ExitSummary(
status()) <<
"\n"
7407 <<
"Actual msg:\n" << FormatDeathTestOutput(error_message);
7413 <<
"DeathTest::Passed somehow called before conclusion of test";
7416 DeathTest::set_last_death_test_message(
buffer.GetString());
7420 # if GTEST_OS_WINDOWS
7449 class WindowsDeathTest :
public DeathTestImpl {
7451 WindowsDeathTest(
const char* a_statement,
7459 virtual TestRole AssumeRole();
7463 const char*
const file_;
7467 AutoHandle write_handle_;
7469 AutoHandle child_handle_;
7474 AutoHandle event_handle_;
7480 int WindowsDeathTest::Wait() {
7486 const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() };
7487 switch (::WaitForMultipleObjects(2,
7492 case WAIT_OBJECT_0 + 1:
7495 GTEST_DEATH_TEST_CHECK_(
false);
7500 write_handle_.Reset();
7501 event_handle_.Reset();
7503 ReadAndInterpretStatusByte();
7509 GTEST_DEATH_TEST_CHECK_(
7510 WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(),
7513 GTEST_DEATH_TEST_CHECK_(
7514 ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE);
7515 child_handle_.Reset();
7516 set_status(
static_cast<int>(status_code));
7525 DeathTest::TestRole WindowsDeathTest::AssumeRole() {
7527 const InternalRunDeathTestFlag*
const flag =
7528 impl->internal_run_death_test_flag();
7529 const TestInfo*
const info = impl->current_test_info();
7530 const int death_test_index = info->result()->death_test_count();
7535 set_write_fd(
flag->write_fd());
7536 return EXECUTE_TEST;
7541 SECURITY_ATTRIBUTES handles_are_inheritable = {
7542 sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };
7543 HANDLE read_handle, write_handle;
7544 GTEST_DEATH_TEST_CHECK_(
7545 ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable,
7548 set_read_fd(::_open_osfhandle(
reinterpret_cast<intptr_t>(read_handle),
7550 write_handle_.Reset(write_handle);
7551 event_handle_.Reset(::CreateEvent(
7552 &handles_are_inheritable,
7556 GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL);
7559 info->test_case_name() +
"." + info->name();
7572 GTEST_DEATH_TEST_CHECK_(
7573 _MAX_PATH + 1 != ::GetModuleFileNameA(NULL,
7578 std::string(::GetCommandLineA()) +
" " + filter_flag +
" \"" +
7579 internal_flag +
"\"";
7581 DeathTest::set_last_death_test_message(
"");
7588 STARTUPINFOA startup_info;
7589 memset(&startup_info, 0,
sizeof(STARTUPINFO));
7590 startup_info.dwFlags = STARTF_USESTDHANDLES;
7591 startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE);
7592 startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE);
7593 startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE);
7595 PROCESS_INFORMATION process_info;
7596 GTEST_DEATH_TEST_CHECK_(::CreateProcessA(
7598 const_cast<char*
>(command_line.c_str()),
7604 UnitTest::GetInstance()->original_working_dir(),
7606 &process_info) != FALSE);
7607 child_handle_.Reset(process_info.hProcess);
7608 ::CloseHandle(process_info.hThread);
7610 return OVERSEE_TEST;
7612 # else // We are not on Windows.
7617 class ForkingDeathTest :
public DeathTestImpl {
7619 ForkingDeathTest(
const char* statement,
const RE* regex);
7625 void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; }
7633 ForkingDeathTest::ForkingDeathTest(
const char* a_statement,
const RE* a_regex)
7634 : DeathTestImpl(a_statement, a_regex),
7640 int ForkingDeathTest::Wait() {
7644 ReadAndInterpretStatusByte();
7647 GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0));
7648 set_status(status_value);
7649 return status_value;
7654 class NoExecDeathTest :
public ForkingDeathTest {
7656 NoExecDeathTest(
const char* a_statement,
const RE* a_regex) :
7657 ForkingDeathTest(a_statement, a_regex) { }
7658 virtual TestRole AssumeRole();
7663 DeathTest::TestRole NoExecDeathTest::AssumeRole() {
7665 if (thread_count != 1) {
7670 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
7672 DeathTest::set_last_death_test_message(
"");
7683 const pid_t child_pid = fork();
7684 GTEST_DEATH_TEST_CHECK_(child_pid != -1);
7685 set_child_pid(child_pid);
7686 if (child_pid == 0) {
7687 GTEST_DEATH_TEST_CHECK_SYSCALL_(
close(pipe_fd[0]));
7688 set_write_fd(pipe_fd[1]);
7696 g_in_fast_death_test_child =
true;
7697 return EXECUTE_TEST;
7699 GTEST_DEATH_TEST_CHECK_SYSCALL_(
close(pipe_fd[1]));
7700 set_read_fd(pipe_fd[0]);
7702 return OVERSEE_TEST;
7709 class ExecDeathTest :
public ForkingDeathTest {
7711 ExecDeathTest(
const char* a_statement,
const RE* a_regex,
7714 virtual TestRole AssumeRole();
7716 static ::std::vector<testing::internal::string>
7717 GetArgvsForDeathTestChildProcess() {
7718 ::std::vector<testing::internal::string>
args = GetInjectableArgvs();
7719 # if defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)
7720 ::std::vector<testing::internal::string>
extra_args =
7721 GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_();
7723 # endif // defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)
7727 const char*
const file_;
7736 args_.push_back(NULL);
7745 void AddArgument(
const char*
argument) {
7749 template <
typename Str>
7750 void AddArguments(const ::std::vector<Str>& arguments) {
7751 for (typename ::std::vector<Str>::const_iterator
i = arguments.begin();
7752 i != arguments.end();
7757 char*
const* Argv() {
7762 std::vector<char*>
args_;
7767 struct ExecDeathTestArgs {
7773 inline char** GetEnviron() {
7777 return *_NSGetEnviron();
7783 inline char** GetEnviron() {
return environ; }
7784 # endif // GTEST_OS_MAC
7790 static int ExecDeathTestChildMain(
void* child_arg) {
7791 ExecDeathTestArgs*
const args =
static_cast<ExecDeathTestArgs*
>(child_arg);
7792 GTEST_DEATH_TEST_CHECK_SYSCALL_(
close(
args->close_fd));
7797 const char*
const original_dir =
7798 UnitTest::GetInstance()->original_working_dir();
7800 if (chdir(original_dir) != 0) {
7801 DeathTestAbort(
std::string(
"chdir(\"") + original_dir +
"\") failed: " +
7802 GetLastErrnoDescription());
7803 return EXIT_FAILURE;
7811 execve(
args->argv[0],
args->argv, GetEnviron());
7812 DeathTestAbort(
std::string(
"execve(") +
args->argv[0] +
", ...) in " +
7813 original_dir +
" failed: " +
7814 GetLastErrnoDescription());
7815 return EXIT_FAILURE;
7817 # endif // !GTEST_OS_QNX
7829 void StackLowerThanAddress(
const void*
ptr,
bool*
result) {
7836 bool StackGrowsDown() {
7850 static pid_t ExecDeathTestSpawnChild(
char*
const* argv,
int close_fd) {
7851 ExecDeathTestArgs
args = { argv, close_fd };
7852 pid_t child_pid = -1;
7857 const int cwd_fd =
open(
".", O_RDONLY);
7858 GTEST_DEATH_TEST_CHECK_(cwd_fd != -1);
7859 GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC));
7863 const char*
const original_dir =
7864 UnitTest::GetInstance()->original_working_dir();
7866 if (chdir(original_dir) != 0) {
7867 DeathTestAbort(
std::string(
"chdir(\"") + original_dir +
"\") failed: " +
7868 GetLastErrnoDescription());
7869 return EXIT_FAILURE;
7874 GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD));
7875 GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD,
7876 fd_flags | FD_CLOEXEC));
7877 struct inheritance inherit = {0};
7879 child_pid =
spawn(
args.argv[0], 0, NULL, &inherit,
args.argv, GetEnviron());
7881 GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1);
7882 GTEST_DEATH_TEST_CHECK_SYSCALL_(
close(cwd_fd));
7884 # else // GTEST_OS_QNX
7889 struct sigaction saved_sigprof_action;
7890 struct sigaction ignore_sigprof_action;
7891 memset(&ignore_sigprof_action, 0,
sizeof(ignore_sigprof_action));
7892 sigemptyset(&ignore_sigprof_action.sa_mask);
7893 ignore_sigprof_action.sa_handler = SIG_IGN;
7894 GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction(
7895 SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));
7896 # endif // GTEST_OS_LINUX
7898 # if GTEST_HAS_CLONE
7899 const bool use_fork =
GTEST_FLAG(death_test_use_fork);
7902 static const bool stack_grows_down = StackGrowsDown();
7903 const size_t stack_size = getpagesize();
7905 void*
const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE,
7906 MAP_ANON | MAP_PRIVATE, -1, 0);
7907 GTEST_DEATH_TEST_CHECK_(
stack != MAP_FAILED);
7915 const size_t kMaxStackAlignment = 64;
7916 void*
const stack_top =
7917 static_cast<char*
>(
stack) +
7918 (stack_grows_down ? stack_size - kMaxStackAlignment : 0);
7919 GTEST_DEATH_TEST_CHECK_(stack_size > kMaxStackAlignment &&
7920 reinterpret_cast<intptr_t>(stack_top) % kMaxStackAlignment == 0);
7922 child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &
args);
7924 GTEST_DEATH_TEST_CHECK_(munmap(
stack, stack_size) != -1);
7927 const bool use_fork =
true;
7928 # endif // GTEST_HAS_CLONE
7930 if (use_fork && (child_pid = fork()) == 0) {
7931 ExecDeathTestChildMain(&
args);
7934 # endif // GTEST_OS_QNX
7936 GTEST_DEATH_TEST_CHECK_SYSCALL_(
7937 sigaction(SIGPROF, &saved_sigprof_action, NULL));
7938 # endif // GTEST_OS_LINUX
7940 GTEST_DEATH_TEST_CHECK_(child_pid != -1);
7948 DeathTest::TestRole ExecDeathTest::AssumeRole() {
7950 const InternalRunDeathTestFlag*
const flag =
7951 impl->internal_run_death_test_flag();
7952 const TestInfo*
const info = impl->current_test_info();
7953 const int death_test_index = info->result()->death_test_count();
7956 set_write_fd(
flag->write_fd());
7957 return EXECUTE_TEST;
7961 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
7964 GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
7968 + info->test_case_name() +
"." + info->name();
7975 args.AddArguments(GetArgvsForDeathTestChildProcess());
7976 args.AddArgument(filter_flag.c_str());
7977 args.AddArgument(internal_flag.c_str());
7979 DeathTest::set_last_death_test_message(
"");
7986 const pid_t child_pid = ExecDeathTestSpawnChild(
args.Argv(), pipe_fd[0]);
7987 GTEST_DEATH_TEST_CHECK_SYSCALL_(
close(pipe_fd[1]));
7988 set_child_pid(child_pid);
7989 set_read_fd(pipe_fd[0]);
7991 return OVERSEE_TEST;
7994 # endif // !GTEST_OS_WINDOWS
8001 bool DefaultDeathTestFactory::Create(
const char* statement,
const RE* regex,
8005 const InternalRunDeathTestFlag*
const flag =
8006 impl->internal_run_death_test_flag();
8007 const int death_test_index = impl->current_test_info()
8008 ->increment_death_test_count();
8011 if (death_test_index >
flag->index()) {
8012 DeathTest::set_last_death_test_message(
8014 +
") somehow exceeded expected maximum ("
8020 flag->index() == death_test_index)) {
8026 # if GTEST_OS_WINDOWS
8028 if (
GTEST_FLAG(death_test_style) ==
"threadsafe" ||
8030 *
test =
new WindowsDeathTest(statement, regex,
file,
line);
8035 if (
GTEST_FLAG(death_test_style) ==
"threadsafe") {
8036 *
test =
new ExecDeathTest(statement, regex,
file,
line);
8037 }
else if (
GTEST_FLAG(death_test_style) ==
"fast") {
8038 *
test =
new NoExecDeathTest(statement, regex);
8041 # endif // GTEST_OS_WINDOWS
8044 DeathTest::set_last_death_test_message(
8045 "Unknown death test style \"" +
GTEST_FLAG(death_test_style)
8046 +
"\" encountered");
8053 # if GTEST_OS_WINDOWS
8057 int GetStatusFileDescriptor(
unsigned int parent_process_id,
8058 size_t write_handle_as_size_t,
8059 size_t event_handle_as_size_t) {
8060 AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,
8062 parent_process_id));
8064 DeathTestAbort(
"Unable to open parent process " +
8072 const HANDLE write_handle =
8073 reinterpret_cast<HANDLE
>(write_handle_as_size_t);
8074 HANDLE dup_write_handle;
8079 if (!::DuplicateHandle(parent_process_handle.Get(), write_handle,
8080 ::GetCurrentProcess(), &dup_write_handle,
8084 DUPLICATE_SAME_ACCESS)) {
8085 DeathTestAbort(
"Unable to duplicate the pipe handle " +
8087 " from the parent process " +
8091 const HANDLE event_handle =
reinterpret_cast<HANDLE
>(event_handle_as_size_t);
8092 HANDLE dup_event_handle;
8094 if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,
8095 ::GetCurrentProcess(), &dup_event_handle,
8098 DUPLICATE_SAME_ACCESS)) {
8099 DeathTestAbort(
"Unable to duplicate the event handle " +
8101 " from the parent process " +
8105 const int write_fd =
8106 ::_open_osfhandle(
reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND);
8107 if (write_fd == -1) {
8108 DeathTestAbort(
"Unable to convert pipe handle " +
8110 " to a file descriptor");
8115 ::SetEvent(dup_event_handle);
8119 # endif // GTEST_OS_WINDOWS
8124 InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
8125 if (
GTEST_FLAG(internal_run_death_test) ==
"")
return NULL;
8131 ::std::vector< ::std::string>
fields;
8135 # if GTEST_OS_WINDOWS
8137 unsigned int parent_process_id = 0;
8138 size_t write_handle_as_size_t = 0;
8139 size_t event_handle_as_size_t = 0;
8144 || !ParseNaturalNumber(
fields[3], &parent_process_id)
8145 || !ParseNaturalNumber(
fields[4], &write_handle_as_size_t)
8146 || !ParseNaturalNumber(
fields[5], &event_handle_as_size_t)) {
8147 DeathTestAbort(
"Bad --gtest_internal_run_death_test flag: " +
8150 write_fd = GetStatusFileDescriptor(parent_process_id,
8151 write_handle_as_size_t,
8152 event_handle_as_size_t);
8158 || !ParseNaturalNumber(
fields[3], &write_fd)) {
8159 DeathTestAbort(
"Bad --gtest_internal_run_death_test flag: "
8163 # endif // GTEST_OS_WINDOWS
8165 return new InternalRunDeathTestFlag(
fields[0],
line,
index, write_fd);
8170 #endif // GTEST_HAS_DEATH_TEST
8207 #if GTEST_OS_WINDOWS_MOBILE
8208 # include <windows.h>
8209 #elif GTEST_OS_WINDOWS
8210 # include <direct.h>
8212 #elif GTEST_OS_SYMBIAN
8214 # include <sys/syslimits.h>
8216 # include <limits.h>
8218 #endif // GTEST_OS_WINDOWS_MOBILE
8220 #if GTEST_OS_WINDOWS
8221 # define GTEST_PATH_MAX_ _MAX_PATH
8222 #elif defined(PATH_MAX)
8223 # define GTEST_PATH_MAX_ PATH_MAX
8224 #elif defined(_XOPEN_PATH_MAX)
8225 # define GTEST_PATH_MAX_ _XOPEN_PATH_MAX
8227 # define GTEST_PATH_MAX_ _POSIX_PATH_MAX
8228 #endif // GTEST_OS_WINDOWS
8234 #if GTEST_OS_WINDOWS
8240 const char kAlternatePathSeparator =
'/';
8241 const char kAlternatePathSeparatorString[] =
"/";
8242 # if GTEST_OS_WINDOWS_MOBILE
8248 const DWORD kInvalidFileAttributes = 0xffffffff;
8251 # endif // GTEST_OS_WINDOWS_MOBILE
8255 #endif // GTEST_OS_WINDOWS
8259 #if GTEST_HAS_ALT_PATH_SEP_
8268 #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT
8272 #elif GTEST_OS_WINDOWS
8283 # endif // GTEST_OS_NACL
8285 #endif // GTEST_OS_WINDOWS_MOBILE
8296 0,
pathname_.length() - dot_extension.length()));
8306 #if GTEST_HAS_ALT_PATH_SEP_
8307 const char*
const last_alt_sep = strrchr(
c_str(), kAlternatePathSeparator);
8309 if (last_alt_sep != NULL &&
8310 (last_sep == NULL || last_alt_sep > last_sep)) {
8311 return last_alt_sep;
8325 return last_sep ?
FilePath(last_sep + 1) : *this;
8370 return relative_path;
8378 #if GTEST_OS_WINDOWS_MOBILE
8380 const DWORD attributes = GetFileAttributes(
unicode);
8382 return attributes != kInvalidFileAttributes;
8386 #endif // GTEST_OS_WINDOWS_MOBILE
8393 #if GTEST_OS_WINDOWS
8402 #if GTEST_OS_WINDOWS_MOBILE
8403 LPCWSTR
unicode = String::AnsiToUtf16(
path.c_str());
8404 const DWORD attributes = GetFileAttributes(
unicode);
8406 if ((attributes != kInvalidFileAttributes) &&
8407 (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
8414 #endif // GTEST_OS_WINDOWS_MOBILE
8422 #if GTEST_OS_WINDOWS
8435 #if GTEST_OS_WINDOWS
8437 ((
name[0] >=
'a' &&
name[0] <=
'z') ||
8438 (
name[0] >=
'A' &&
name[0] <=
'Z')) &&
8461 }
while (full_pathname.FileOrDirectoryExists());
8462 return full_pathname;
8481 if (
pathname_.length() == 0 || this->DirectoryExists()) {
8486 return parent.CreateDirectoriesRecursively() && this->
CreateFolder();
8494 #if GTEST_OS_WINDOWS_MOBILE
8496 LPCWSTR
unicode = String::AnsiToUtf16(removed_sep.c_str());
8499 #elif GTEST_OS_WINDOWS
8503 #endif // GTEST_OS_WINDOWS_MOBILE
8531 char* dest_ptr =
dest;
8534 while (*src !=
'\0') {
8539 #if GTEST_HAS_ALT_PATH_SEP_
8540 if (*dest_ptr == kAlternatePathSeparator) {
8594 #if GTEST_OS_WINDOWS
8595 # include <windows.h>
8597 # include <sys/stat.h>
8600 # include <unistd.h>
8601 #endif // GTEST_OS_WINDOWS
8604 # include <mach/mach_init.h>
8605 # include <mach/task.h>
8606 # include <mach/vm_map.h>
8607 #endif // GTEST_OS_MAC
8610 # include <devctl.h>
8612 # include <sys/procfs.h>
8613 #endif // GTEST_OS_QNX
8616 # include <procinfo.h>
8617 # include <sys/types.h>
8618 #endif // GTEST_OS_AIX
8626 #define GTEST_IMPLEMENTATION_ 1
8627 #undef GTEST_IMPLEMENTATION_
8632 #if defined(_MSC_VER) || defined(__BORLANDC__)
8644 template <
typename T>
8648 while (
field-- > 0) {
8661 return ReadProcFileField<int>(
filename, 19);
8667 const task_t task = mach_task_self();
8668 mach_msg_type_number_t thread_count;
8669 thread_act_array_t thread_list;
8670 const kern_return_t
status = task_threads(task, &thread_list, &thread_count);
8671 if (
status == KERN_SUCCESS) {
8675 reinterpret_cast<vm_address_t
>(thread_list),
8676 sizeof(thread_t) * thread_count);
8677 return static_cast<size_t>(thread_count);
8688 const int fd =
open(
"/proc/self/as", O_RDONLY);
8692 procfs_info process_info;
8694 devctl(fd, DCMD_PROC_INFO, &process_info,
sizeof(process_info), NULL);
8697 return static_cast<size_t>(process_info.num_threads);
8706 struct procentry64 entry;
8707 pid_t pid = getpid();
8708 int status = getprocs64(&entry,
sizeof(entry), NULL, 0, &pid, 1);
8710 return entry.pi_thcount;
8724 #endif // GTEST_OS_LINUX
8726 #if GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
8728 void SleepMilliseconds(
int n) {
8732 AutoHandle::AutoHandle()
8735 AutoHandle::AutoHandle(Handle
handle)
8738 AutoHandle::~AutoHandle() {
8753 if (IsCloseable()) {
8759 <<
"Resetting a valid handle to itself is likely a programmer error "
8760 "and thus not allowed.";
8764 bool AutoHandle::IsCloseable()
const {
8770 Notification::Notification()
8771 : event_(::CreateEvent(NULL,
8778 void Notification::Notify() {
8782 void Notification::WaitForNotification() {
8784 ::WaitForSingleObject(event_.Get(), INFINITE) == WAIT_OBJECT_0);
8788 : owner_thread_id_(0),
8790 critical_section_init_phase_(0),
8791 critical_section_(
new CRITICAL_SECTION) {
8792 ::InitializeCriticalSection(critical_section_);
8801 if (
type_ == kDynamic) {
8802 ::DeleteCriticalSection(critical_section_);
8803 delete critical_section_;
8804 critical_section_ = NULL;
8808 void Mutex::Lock() {
8809 ThreadSafeLazyInit();
8810 ::EnterCriticalSection(critical_section_);
8811 owner_thread_id_ = ::GetCurrentThreadId();
8814 void Mutex::Unlock() {
8815 ThreadSafeLazyInit();
8819 owner_thread_id_ = 0;
8820 ::LeaveCriticalSection(critical_section_);
8825 void Mutex::AssertHeld() {
8826 ThreadSafeLazyInit();
8827 GTEST_CHECK_(owner_thread_id_ == ::GetCurrentThreadId())
8828 <<
"The current thread is not holding the mutex @" <<
this;
8832 void Mutex::ThreadSafeLazyInit() {
8834 if (
type_ == kStatic) {
8836 ::InterlockedCompareExchange(&critical_section_init_phase_, 1
L, 0
L)) {
8840 owner_thread_id_ = 0;
8841 critical_section_ =
new CRITICAL_SECTION;
8842 ::InitializeCriticalSection(critical_section_);
8846 &critical_section_init_phase_, 2
L, 1
L) ==
8852 while (::InterlockedCompareExchange(&critical_section_init_phase_,
8866 <<
"Unexpected value of critical_section_init_phase_ "
8867 <<
"while initializing a static mutex.";
8874 class ThreadWithParamSupport :
public ThreadWithParamBase {
8876 static HANDLE CreateThread(Runnable* runnable,
8877 Notification* thread_can_start) {
8878 ThreadMainParam* param =
new ThreadMainParam(runnable, thread_can_start);
8881 HANDLE thread_handle = ::CreateThread(
8884 &ThreadWithParamSupport::ThreadMain,
8888 GTEST_CHECK_(thread_handle != NULL) <<
"CreateThread failed with error "
8889 << ::GetLastError() <<
".";
8890 if (thread_handle == NULL) {
8893 return thread_handle;
8897 struct ThreadMainParam {
8898 ThreadMainParam(Runnable* runnable, Notification* thread_can_start)
8899 : runnable_(runnable),
8900 thread_can_start_(thread_can_start) {
8902 scoped_ptr<Runnable> runnable_;
8904 Notification* thread_can_start_;
8907 static DWORD WINAPI ThreadMain(
void*
ptr) {
8909 scoped_ptr<ThreadMainParam> param(
static_cast<ThreadMainParam*
>(
ptr));
8910 if (param->thread_can_start_ != NULL)
8911 param->thread_can_start_->WaitForNotification();
8912 param->runnable_->Run();
8917 ThreadWithParamSupport();
8924 ThreadWithParamBase::ThreadWithParamBase(Runnable *runnable,
8925 Notification* thread_can_start)
8926 :
thread_(ThreadWithParamSupport::CreateThread(runnable,
8927 thread_can_start)) {
8930 ThreadWithParamBase::~ThreadWithParamBase() {
8936 <<
"Failed to join the thread with error " << ::GetLastError() <<
".";
8943 class ThreadLocalRegistryImpl {
8947 static ThreadLocalValueHolderBase* GetValueOnCurrentThread(
8948 const ThreadLocalBase* thread_local_instance) {
8949 DWORD current_thread = ::GetCurrentThreadId();
8951 ThreadIdToThreadLocals*
const thread_to_thread_locals =
8952 GetThreadLocalsMapLocked();
8954 thread_to_thread_locals->find(current_thread);
8955 if (thread_local_pos == thread_to_thread_locals->end()) {
8956 thread_local_pos = thread_to_thread_locals->insert(
8957 std::make_pair(current_thread, ThreadLocalValues())).first;
8958 StartWatcherThreadFor(current_thread);
8960 ThreadLocalValues& thread_local_values = thread_local_pos->second;
8962 thread_local_values.find(thread_local_instance);
8963 if (value_pos == thread_local_values.end()) {
8966 .insert(std::make_pair(
8967 thread_local_instance,
8968 linked_ptr<ThreadLocalValueHolderBase>(
8969 thread_local_instance->NewValueForCurrentThread())))
8972 return value_pos->second.get();
8975 static void OnThreadLocalDestroyed(
8976 const ThreadLocalBase* thread_local_instance) {
8977 std::vector<linked_ptr<ThreadLocalValueHolderBase> > value_holders;
8982 ThreadIdToThreadLocals*
const thread_to_thread_locals =
8983 GetThreadLocalsMapLocked();
8985 thread_to_thread_locals->begin();
8986 it != thread_to_thread_locals->end();
8988 ThreadLocalValues& thread_local_values =
it->second;
8990 thread_local_values.find(thread_local_instance);
8991 if (value_pos != thread_local_values.end()) {
8992 value_holders.push_back(value_pos->second);
8993 thread_local_values.erase(value_pos);
9003 static void OnThreadExit(DWORD
thread_id) {
9005 std::vector<linked_ptr<ThreadLocalValueHolderBase> > value_holders;
9010 ThreadIdToThreadLocals*
const thread_to_thread_locals =
9011 GetThreadLocalsMapLocked();
9013 thread_to_thread_locals->find(
thread_id);
9014 if (thread_local_pos != thread_to_thread_locals->end()) {
9015 ThreadLocalValues& thread_local_values = thread_local_pos->second;
9017 thread_local_values.begin();
9018 value_pos != thread_local_values.end();
9020 value_holders.push_back(value_pos->second);
9022 thread_to_thread_locals->erase(thread_local_pos);
9031 typedef std::map<
const ThreadLocalBase*,
9032 linked_ptr<ThreadLocalValueHolderBase> > ThreadLocalValues;
9035 typedef std::map<DWORD, ThreadLocalValues> ThreadIdToThreadLocals;
9039 typedef std::pair<DWORD, HANDLE> ThreadIdAndHandle;
9041 static void StartWatcherThreadFor(DWORD
thread_id) {
9044 HANDLE
thread = ::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION,
9050 DWORD watcher_thread_id;
9051 HANDLE watcher_thread = ::CreateThread(
9054 &ThreadLocalRegistryImpl::WatcherThreadFunc,
9057 &watcher_thread_id);
9061 ::SetThreadPriority(watcher_thread,
9062 ::GetThreadPriority(::GetCurrentThread()));
9063 ::ResumeThread(watcher_thread);
9064 ::CloseHandle(watcher_thread);
9069 static DWORD WINAPI WatcherThreadFunc(LPVOID param) {
9070 const ThreadIdAndHandle* tah =
9071 reinterpret_cast<const ThreadIdAndHandle*
>(param);
9073 ::WaitForSingleObject(tah->second, INFINITE) == WAIT_OBJECT_0);
9074 OnThreadExit(tah->first);
9075 ::CloseHandle(tah->second);
9081 static ThreadIdToThreadLocals* GetThreadLocalsMapLocked() {
9083 static ThreadIdToThreadLocals*
map =
new ThreadIdToThreadLocals;
9090 static Mutex thread_map_mutex_;
9094 Mutex ThreadLocalRegistryImpl::thread_map_mutex_(Mutex::kStaticMutex);
9096 ThreadLocalValueHolderBase* ThreadLocalRegistry::GetValueOnCurrentThread(
9097 const ThreadLocalBase* thread_local_instance) {
9098 return ThreadLocalRegistryImpl::GetValueOnCurrentThread(
9099 thread_local_instance);
9102 void ThreadLocalRegistry::OnThreadLocalDestroyed(
9103 const ThreadLocalBase* thread_local_instance) {
9104 ThreadLocalRegistryImpl::OnThreadLocalDestroyed(thread_local_instance);
9107 #endif // GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
9109 #if GTEST_USES_POSIX_RE
9119 regfree(&partial_regex_);
9120 regfree(&full_regex_);
9122 free(
const_cast<char*
>(pattern_));
9126 bool RE::FullMatch(
const char*
str,
const RE& re) {
9135 bool RE::PartialMatch(
const char*
str,
const RE& re) {
9148 const size_t full_regex_len = strlen(regex) + 10;
9149 char*
const full_pattern =
new char[full_regex_len];
9151 snprintf(full_pattern, full_regex_len,
"^(%s)$", regex);
9152 is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0;
9162 const char*
const partial_regex = (*regex ==
'\0') ?
"()" : regex;
9163 is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0;
9166 <<
"Regular expression \"" << regex
9167 <<
"\" is not a valid POSIX Extended regular expression.";
9169 delete[] full_pattern;
9172 #elif GTEST_USES_SIMPLE_RE
9176 bool IsInSet(
char ch,
const char*
str) {
9177 return ch !=
'\0' && strchr(
str,
ch) != NULL;
9183 bool IsAsciiDigit(
char ch) {
return '0' <=
ch &&
ch <=
'9'; }
9184 bool IsAsciiPunct(
char ch) {
9185 return IsInSet(
ch,
"^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
9187 bool IsRepeat(
char ch) {
return IsInSet(
ch,
"?*+"); }
9188 bool IsAsciiWhiteSpace(
char ch) {
return IsInSet(
ch,
" \f\n\r\t\v"); }
9189 bool IsAsciiWordChar(
char ch) {
9190 return (
'a' <=
ch &&
ch <=
'z') || (
'A' <=
ch &&
ch <=
'Z') ||
9191 (
'0' <=
ch &&
ch <=
'9') ||
ch ==
'_';
9195 bool IsValidEscape(
char c) {
9196 return (IsAsciiPunct(c) || IsInSet(c,
"dDfnrsStvwW"));
9201 bool AtomMatchesChar(
bool escaped,
char pattern_char,
char ch) {
9203 switch (pattern_char) {
9204 case 'd':
return IsAsciiDigit(
ch);
9205 case 'D':
return !IsAsciiDigit(
ch);
9206 case 'f':
return ch ==
'\f';
9207 case 'n':
return ch ==
'\n';
9208 case 'r':
return ch ==
'\r';
9209 case 's':
return IsAsciiWhiteSpace(
ch);
9210 case 'S':
return !IsAsciiWhiteSpace(
ch);
9211 case 't':
return ch ==
'\t';
9212 case 'v':
return ch ==
'\v';
9213 case 'w':
return IsAsciiWordChar(
ch);
9214 case 'W':
return !IsAsciiWordChar(
ch);
9216 return IsAsciiPunct(pattern_char) && pattern_char ==
ch;
9219 return (pattern_char ==
'.' &&
ch !=
'\n') || pattern_char ==
ch;
9225 <<
" in simple regular expression \"" << regex <<
"\": ").GetString();
9230 bool ValidateRegex(
const char* regex) {
9231 if (regex == NULL) {
9235 ADD_FAILURE() <<
"NULL is not a valid simple regular expression.";
9239 bool is_valid =
true;
9242 bool prev_repeatable =
false;
9243 for (
int i = 0; regex[
i];
i++) {
9244 if (regex[i] ==
'\\') {
9246 if (regex[i] ==
'\0') {
9247 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
9248 <<
"'\\' cannot appear at the end.";
9252 if (!IsValidEscape(regex[i])) {
9253 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
9254 <<
"invalid escape sequence \"\\" << regex[
i] <<
"\".";
9257 prev_repeatable =
true;
9259 const char ch = regex[
i];
9261 if (
ch ==
'^' && i > 0) {
9263 <<
"'^' can only appear at the beginning.";
9265 }
else if (
ch ==
'$' && regex[i + 1] !=
'\0') {
9267 <<
"'$' can only appear at the end.";
9269 }
else if (IsInSet(
ch,
"()[]{}|")) {
9271 <<
"'" <<
ch <<
"' is unsupported.";
9273 }
else if (IsRepeat(
ch) && !prev_repeatable) {
9275 <<
"'" <<
ch <<
"' can only follow a repeatable token.";
9279 prev_repeatable = !IsInSet(
ch,
"^$?*+");
9293 bool MatchRepetitionAndRegexAtHead(
9294 bool escaped,
char c,
char repeat,
const char* regex,
9296 const size_t min_count = (repeat ==
'+') ? 1 : 0;
9297 const size_t max_count = (repeat ==
'?') ? 1 :
9298 static_cast<size_t>(-1) - 1;
9302 for (
size_t i = 0;
i <= max_count; ++
i) {
9304 if (i >= min_count && MatchRegexAtHead(regex,
str + i)) {
9311 if (
str[i] ==
'\0' || !AtomMatchesChar(escaped, c,
str[i]))
9320 bool MatchRegexAtHead(
const char* regex,
const char*
str) {
9327 return *
str ==
'\0';
9330 const bool escaped = *regex ==
'\\';
9333 if (IsRepeat(regex[1])) {
9337 return MatchRepetitionAndRegexAtHead(
9338 escaped, regex[0], regex[1], regex + 2,
str);
9343 return (*
str !=
'\0') && AtomMatchesChar(escaped, *regex, *
str) &&
9344 MatchRegexAtHead(regex + 1,
str + 1);
9356 bool MatchRegexAnywhere(
const char* regex,
const char*
str) {
9357 if (regex == NULL ||
str == NULL)
9361 return MatchRegexAtHead(regex + 1,
str);
9365 if (MatchRegexAtHead(regex,
str))
9367 }
while (*
str++ !=
'\0');
9374 free(
const_cast<char*
>(pattern_));
9375 free(
const_cast<char*
>(full_pattern_));
9379 bool RE::FullMatch(
const char*
str,
const RE& re) {
9380 return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_,
str);
9385 bool RE::PartialMatch(
const char*
str,
const RE& re) {
9386 return re.is_valid_ && MatchRegexAnywhere(re.pattern_,
str);
9391 pattern_ = full_pattern_ = NULL;
9392 if (regex != NULL) {
9396 is_valid_ = ValidateRegex(regex);
9402 const size_t len = strlen(regex);
9406 char*
buffer =
static_cast<char*
>(malloc(
len + 3));
9417 if (
len == 0 || regex[
len - 1] !=
'$')
9423 #endif // GTEST_USES_POSIX_RE
9433 return file_name +
":";
9459 const char*
const marker =
9463 GetStream() << ::std::endl << marker <<
" "
9479 #if GTEST_HAS_STREAM_REDIRECTION
9486 # if GTEST_OS_WINDOWS
9487 char temp_dir_path[MAX_PATH + 1] = {
'\0' };
9488 char temp_file_path[MAX_PATH + 1] = {
'\0' };
9490 ::GetTempPathA(
sizeof(temp_dir_path), temp_dir_path);
9491 const UINT success = ::GetTempFileNameA(temp_dir_path,
9496 <<
"Unable to create a temporary file in " << temp_dir_path;
9497 const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
9498 GTEST_CHECK_(captured_fd != -1) <<
"Unable to open temporary file "
9506 # if GTEST_OS_LINUX_ANDROID
9521 char name_template[] =
"/sdcard/gtest_captured_stream.XXXXXX";
9523 char name_template[] =
"/tmp/captured_stream.XXXXXX";
9524 # endif // GTEST_OS_LINUX_ANDROID
9525 const int captured_fd = mkstemp(name_template);
9527 # endif // GTEST_OS_WINDOWS
9529 dup2(captured_fd,
fd_);
9570 <<
" capturer can exist at a time.";
9579 delete *captured_stream;
9580 *captured_stream = NULL;
9605 #endif // GTEST_HAS_STREAM_REDIRECTION
9608 #if GTEST_OS_WINDOWS_MOBILE
9610 #elif GTEST_OS_WINDOWS
9612 if (temp_dir == NULL || temp_dir[0] ==
'\0')
9614 else if (temp_dir[strlen(temp_dir) - 1] ==
'\\')
9618 #elif GTEST_OS_LINUX_ANDROID
9622 #endif // GTEST_OS_WINDOWS_MOBILE
9627 return static_cast<size_t>(ftell(
file));
9632 char*
const buffer =
new char[file_size];
9634 size_t bytes_last_read = 0;
9644 }
while (bytes_last_read > 0 &&
bytes_read < file_size);
9652 #if GTEST_HAS_DEATH_TEST
9654 static const ::std::vector<testing::internal::string>* g_injected_test_argvs =
9657 void SetInjectableArgvs(const ::std::vector<testing::internal::string>* argvs) {
9658 if (g_injected_test_argvs != argvs)
9659 delete g_injected_test_argvs;
9660 g_injected_test_argvs = argvs;
9663 const ::std::vector<testing::internal::string>& GetInjectableArgvs() {
9664 if (g_injected_test_argvs != NULL) {
9665 return *g_injected_test_argvs;
9669 #endif // GTEST_HAS_DEATH_TEST
9671 #if GTEST_OS_WINDOWS_MOBILE
9675 TerminateProcess(GetCurrentProcess(), 1);
9678 #endif // GTEST_OS_WINDOWS_MOBILE
9688 for (
size_t i = 0;
i != full_flag.length();
i++) {
9701 const long long_value = strtol(
str, &
end, 10);
9707 msg <<
"WARNING: " << src_text
9708 <<
" is expected to be a 32-bit integer, but actually"
9709 <<
" has value \"" <<
str <<
"\".\n";
9717 if (long_value == LONG_MAX || long_value == LONG_MIN ||
9724 msg <<
"WARNING: " << src_text
9725 <<
" is expected to be a 32-bit integer, but actually"
9726 <<
" has value " <<
str <<
", which overflows.\n";
9741 #if defined(GTEST_GET_BOOL_FROM_ENV_)
9742 return GTEST_GET_BOOL_FROM_ENV_(
flag, default_value);
9743 #endif // defined(GTEST_GET_BOOL_FROM_ENV_)
9746 return string_value == NULL ?
9747 default_value : strcmp(string_value,
"0") != 0;
9754 #if defined(GTEST_GET_INT32_FROM_ENV_)
9755 return GTEST_GET_INT32_FROM_ENV_(
flag, default_value);
9756 #endif // defined(GTEST_GET_INT32_FROM_ENV_)
9759 if (string_value == NULL) {
9761 return default_value;
9766 string_value, &
result)) {
9767 printf(
"The default value %s is used.\n",
9770 return default_value;
9779 #if defined(GTEST_GET_STRING_FROM_ENV_)
9780 return GTEST_GET_STRING_FROM_ENV_(
flag, default_value);
9781 #endif // defined(GTEST_GET_STRING_FROM_ENV_)
9784 if (
value != NULL) {
9798 if (strcmp(
flag,
"output") == 0) {
9800 if (
value != NULL) {
9804 return default_value;
9863 using ::std::ostream;
9869 void PrintByteSegmentInObjectTo(
const unsigned char* obj_bytes,
size_t start,
9870 size_t count, ostream* os) {
9872 for (
size_t i = 0;
i !=
count;
i++) {
9888 void PrintBytesInObjectToImpl(
const unsigned char* obj_bytes,
size_t count,
9891 *os <<
count <<
"-byte object <";
9893 const size_t kThreshold = 132;
9899 if (
count < kThreshold) {
9900 PrintByteSegmentInObjectTo(obj_bytes, 0,
count, os);
9902 PrintByteSegmentInObjectTo(obj_bytes, 0,
kChunkSize, os);
9906 PrintByteSegmentInObjectTo(obj_bytes, resume_pos,
count - resume_pos, os);
9913 namespace internal2 {
9922 PrintBytesInObjectToImpl(obj_bytes,
count, os);
9944 return 0x20 <= c && c <= 0x7E;
9951 template <
typename Un
signedChar,
typename Char>
9953 switch (
static_cast<wchar_t>(c)) {
9986 *os << static_cast<char>(c);
10007 return PrintAsCharLiteralTo<wchar_t>(c, os);
10015 static_cast<wchar_t>(
static_cast<unsigned char>(c)), os);
10022 template <
typename Un
signedChar,
typename Char>
10025 *os << ((
sizeof(c) > 1) ?
"L'" :
"'");
10034 *os <<
" (" <<
static_cast<int>(c);
10047 void PrintTo(
unsigned char c, ::std::ostream* os) {
10048 PrintCharAndCodeTo<unsigned char>(c, os);
10050 void PrintTo(
signed char c, ::std::ostream* os) {
10051 PrintCharAndCodeTo<unsigned char>(c, os);
10056 void PrintTo(
wchar_t wc, ostream* os) {
10057 PrintCharAndCodeTo<wchar_t>(wc, os);
10064 template <
typename CharType>
10069 const CharType*
begin,
size_t len, ostream* os) {
10070 const char*
const kQuoteBegin =
sizeof(CharType) == 1 ?
"\"" :
"L\"";
10071 *os << kQuoteBegin;
10072 bool is_previous_hex =
false;
10079 *os <<
"\" " << kQuoteBegin;
10088 template <
typename CharType>
10093 const CharType*
begin,
size_t len, ostream* os) {
10111 *os <<
" (no terminating NUL)";
10126 void PrintTo(
const char* s, ostream* os) {
10130 *os << ImplicitCast_<const void*>(s) <<
" pointing to ";
10141 #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
10143 void PrintTo(
const wchar_t* s, ostream* os) {
10147 *os << ImplicitCast_<const void*>(s) <<
" pointing to ";
10151 #endif // wchar_t is native
10154 #if GTEST_HAS_GLOBAL_STRING
10158 #endif // GTEST_HAS_GLOBAL_STRING
10165 #if GTEST_HAS_GLOBAL_WSTRING
10169 #endif // GTEST_HAS_GLOBAL_WSTRING
10171 #if GTEST_HAS_STD_WSTRING
10175 #endif // GTEST_HAS_STD_WSTRING
10219 #define GTEST_IMPLEMENTATION_ 1
10220 #undef GTEST_IMPLEMENTATION_
10230 return stack_trace == NULL ?
message :
10235 std::ostream&
operator<<(std::ostream& os,
const TestPartResult&
result) {
10237 <<
result.file_name() <<
":" <<
result.line_number() <<
": "
10240 "Non-fatal failure") <<
":\n"
10241 <<
result.message() << std::endl;
10251 if (index < 0 || index >=
size()) {
10252 printf(
"\nInvalid index (%d) into TestPartResultArray.\n",
index);
10261 return static_cast<int>(
array_.size());
10267 : has_new_fatal_failure_(
false),
10269 GetTestPartResultReporterForCurrentThread()) {
10279 const TestPartResult&
result) {
10280 if (
result.fatally_failed())
10323 #if GTEST_HAS_TYPED_TEST_P
10334 std::vector<std::string> name_vec;
10336 for (; src != NULL; src = SkipComma(src)) {
10345 const char* TypedTestCasePState::VerifyRegisteredTestNames(
10346 const char*
file,
int line,
const char* registered_tests) {
10347 typedef RegisteredTestsMap::const_iterator RegisteredTestIter;
10348 registered_ =
true;
10354 std::set<std::string>
tests;
10355 for (std::vector<std::string>::const_iterator name_it = name_vec.begin();
10356 name_it != name_vec.end(); ++name_it) {
10359 errors <<
"Test " <<
name <<
" is listed more than once.\n";
10363 bool found =
false;
10364 for (RegisteredTestIter
it = registered_tests_.begin();
10365 it != registered_tests_.end();
10367 if (
name ==
it->first) {
10377 <<
" can be found in this test case.\n";
10381 for (RegisteredTestIter
it = registered_tests_.begin();
10382 it != registered_tests_.end();
10384 if (
tests.count(
it->first) == 0) {
10385 errors <<
"You forgot to list test " <<
it->first <<
".\n";
10390 if (errors_str !=
"") {
10392 errors_str.c_str());
10397 return registered_tests;
10400 #endif // GTEST_HAS_TYPED_TEST_P
10443 #include "gmock/gmock.h"
10482 #include <limits.h>
10492 class BetweenCardinalityImpl :
public CardinalityInterface {
10494 BetweenCardinalityImpl(
int min,
int max)
10497 std::stringstream ss;
10499 ss <<
"The invocation lower bound must be >= 0, "
10500 <<
"but is actually " <<
min <<
".";
10502 }
else if (
max < 0) {
10503 ss <<
"The invocation upper bound must be >= 0, "
10504 <<
"but is actually " <<
max <<
".";
10507 ss <<
"The invocation upper bound (" <<
max
10508 <<
") must be >= the invocation lower bound (" <<
min
10516 virtual int ConservativeLowerBound()
const {
return min_; }
10517 virtual int ConservativeUpperBound()
const {
return max_; }
10519 virtual bool IsSatisfiedByCallCount(
int call_count)
const {
10520 return min_ <= call_count && call_count <=
max_;
10523 virtual bool IsSaturatedByCallCount(
int call_count)
const {
10524 return call_count >=
max_;
10527 virtual void DescribeTo(::std::ostream* os)
const;
10540 }
else if (n == 2) {
10543 std::stringstream ss;
10544 ss <<
n <<
" times";
10550 void BetweenCardinalityImpl::DescribeTo(::std::ostream* os)
const {
10553 *os <<
"never called";
10554 }
else if (
max_ == INT_MAX) {
10555 *os <<
"called any number of times";
10557 *os <<
"called at most " << FormatTimes(
max_);
10560 *os <<
"called " << FormatTimes(
min_);
10561 }
else if (
max_ == INT_MAX) {
10562 *os <<
"called at least " << FormatTimes(
min_);
10565 *os <<
"called between " <<
min_ <<
" and " <<
max_ <<
" times";
10573 ::std::ostream* os) {
10574 if (actual_call_count > 0) {
10575 *os <<
"called " << FormatTimes(actual_call_count);
10577 *os <<
"never called";
10650 char prev_char =
'\0';
10651 for (
const char* p = id_name; *
p !=
'\0'; prev_char = *(
p++)) {
10654 const bool starts_new_word =
IsUpper(*p) ||
10659 if (starts_new_word &&
result !=
"")
10670 class GoogleTestFailureReporter :
public FailureReporterInterface {
10694 static FailureReporterInterface*
const failure_reporter =
10695 new GoogleTestFailureReporter();
10696 return failure_reporter;
10727 int stack_frames_to_skip) {
10739 std::cout <<
"\nGMOCK WARNING:";
10746 if (stack_frames_to_skip >= 0) {
10749 const int actual_to_skip = 0;
10753 const int actual_to_skip = stack_frames_to_skip + 1;
10760 std::cout <<
"Stack trace:\n"
10764 std::cout << ::std::flush;
10832 #if GTEST_HAS_STRING_PIECE_
10848 *
this =
Eq(
s.ToString());
10863 *
this =
Eq(
s.ToString());
10865 #endif // GTEST_HAS_STRING_PIECE_
10872 switch (
fields.size()) {
10879 for (
size_t i = 1;
i <
fields.size();
i++) {
10894 const char* matcher_name,
10895 const Strings& param_values) {
10897 if (param_values.size() >= 1)
10964 class MaxBipartiteMatchState {
10975 ::std::vector<char>
seen;
10992 <<
"ilhs: " << ilhs <<
", left_[ilhs]: " <<
left_[ilhs];
10998 for (
size_t ilhs = 0; ilhs <
left_.size(); ++ilhs) {
10999 size_t irhs =
left_[ilhs];
11000 if (irhs ==
kUnused)
continue;
11007 static const size_t kUnused =
static_cast<size_t>(-1);
11045 left_[ilhs] = irhs;
11065 ::std::vector<size_t>
left_;
11066 ::std::vector<size_t>
right_;
11075 return MaxBipartiteMatchState(g).Compute();
11079 ::std::ostream*
stream) {
11080 typedef ElementMatcherPairs::const_iterator
Iter;
11081 ::std::ostream& os = *
stream;
11083 const char *
sep =
"";
11084 for (
Iter it = pairs.begin();
it != pairs.end(); ++
it) {
11085 os <<
sep <<
"\n ("
11086 <<
"element #" <<
it->first <<
", "
11087 <<
"matcher #" <<
it->second <<
")";
11098 size_t max_flow = matches.size();
11103 *listener <<
"where no permutation of the elements can "
11104 "satisfy all matchers, and the closest match is "
11105 << max_flow <<
" of " << matrix.
RhsSize()
11106 <<
" matchers with the pairings:\n";
11112 if (matches.size() > 1) {
11114 const char *
sep =
"where:\n";
11115 for (
size_t mi = 0; mi < matches.size(); ++mi) {
11116 *listener <<
sep <<
" - element #" << matches[mi].first
11117 <<
" is matched by matcher #" << matches[mi].second;
11126 for (
size_t ilhs = 0; ilhs <
LhsSize(); ++ilhs) {
11127 for (
size_t irhs = 0; irhs <
RhsSize(); ++irhs) {
11140 for (
size_t ilhs = 0; ilhs <
LhsSize(); ++ilhs) {
11141 for (
size_t irhs = 0; irhs <
RhsSize(); ++irhs) {
11143 b =
static_cast<char>(rand() & 1);
11149 ::std::stringstream ss;
11150 const char *
sep =
"";
11151 for (
size_t i = 0;
i <
LhsSize(); ++
i) {
11153 for (
size_t j = 0;
j <
RhsSize(); ++
j) {
11162 ::std::ostream* os)
const {
11168 *os <<
"has " <<
Elements(1) <<
" and that element ";
11173 <<
" and there exists some permutation of elements such that:\n";
11174 const char*
sep =
"";
11176 *os <<
sep <<
" - element #" <<
i <<
" ";
11183 ::std::ostream* os)
const {
11185 *os <<
"isn't empty";
11189 *os <<
"doesn't have " <<
Elements(1)
11190 <<
", or has " <<
Elements(1) <<
" that ";
11195 <<
", or there exists no permutation of elements such that:\n";
11196 const char*
sep =
"";
11198 *os <<
sep <<
" - element #" <<
i <<
" ";
11211 const ::std::vector<string>& element_printouts,
11215 ::std::vector<char> element_matched(matrix.
LhsSize(), 0);
11216 ::std::vector<char> matcher_matched(matrix.
RhsSize(), 0);
11218 for (
size_t ilhs = 0; ilhs < matrix.
LhsSize(); ilhs++) {
11219 for (
size_t irhs = 0; irhs < matrix.
RhsSize(); irhs++) {
11220 char matched = matrix.
HasEdge(ilhs, irhs);
11221 element_matched[ilhs] |= matched;
11222 matcher_matched[irhs] |= matched;
11228 "where the following matchers don't match any elements:\n";
11229 for (
size_t mi = 0; mi < matcher_matched.size(); ++mi) {
11230 if (matcher_matched[mi])
11234 *listener <<
sep <<
"matcher #" << mi <<
": ";
11243 "where the following elements don't match any matchers:\n";
11244 const char* outer_sep =
"";
11246 outer_sep =
"\nand ";
11248 for (
size_t ei = 0; ei < element_matched.size(); ++ei) {
11249 if (element_matched[ei])
11253 *listener << outer_sep <<
sep <<
"element #" << ei <<
": "
11254 << element_printouts[ei];
11302 #include <stdlib.h>
11303 #include <iostream>
11308 #if GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC
11309 # include <unistd.h>
11323 ::std::ostringstream s;
11331 const string& a_source_text)
11334 source_text_(a_source_text),
11335 cardinality_specified_(
false),
11339 extra_matcher_specified_(
false),
11340 repeated_action_specified_(
false),
11341 retires_on_saturation_(
false),
11342 last_clause_(kNone),
11343 action_count_checked_(
false) {}
11346 ExpectationBase::~ExpectationBase() {}
11350 void ExpectationBase::SpecifyCardinality(
const Cardinality& a_cardinality) {
11351 cardinality_specified_ =
true;
11352 cardinality_ = a_cardinality;
11356 void ExpectationBase::RetireAllPreRequisites()
11358 if (is_retired()) {
11365 it != immediate_prerequisites_.end(); ++
it) {
11366 ExpectationBase*
const prerequisite =
it->expectation_base().get();
11367 if (!prerequisite->is_retired()) {
11368 prerequisite->RetireAllPreRequisites();
11369 prerequisite->Retire();
11376 bool ExpectationBase::AllPrerequisitesAreSatisfied()
const
11378 g_gmock_mutex.AssertHeld();
11380 it != immediate_prerequisites_.end(); ++
it) {
11381 if (!(
it->expectation_base()->IsSatisfied()) ||
11382 !(
it->expectation_base()->AllPrerequisitesAreSatisfied()))
11389 void ExpectationBase::FindUnsatisfiedPrerequisites(ExpectationSet*
result)
const
11391 g_gmock_mutex.AssertHeld();
11393 it != immediate_prerequisites_.end(); ++
it) {
11394 if (
it->expectation_base()->IsSatisfied()) {
11397 if (
it->expectation_base()->call_count_ == 0) {
11398 it->expectation_base()->FindUnsatisfiedPrerequisites(
result);
11411 void ExpectationBase::DescribeCallCountTo(::std::ostream* os)
const
11413 g_gmock_mutex.AssertHeld();
11416 *os <<
" Expected: to be ";
11417 cardinality().DescribeTo(os);
11418 *os <<
"\n Actual: ";
11423 *os <<
" - " << (IsOverSaturated() ?
"over-saturated" :
11424 IsSaturated() ?
"saturated" :
11425 IsSatisfied() ?
"satisfied" :
"unsatisfied")
11427 << (is_retired() ?
"retired" :
"active");
11434 void ExpectationBase::CheckActionCountIfNotDone()
const
11436 bool should_check =
false;
11439 if (!action_count_checked_) {
11440 action_count_checked_ =
true;
11441 should_check =
true;
11445 if (should_check) {
11446 if (!cardinality_specified_) {
11453 const int action_count =
static_cast<int>(untyped_actions_.size());
11454 const int upper_bound = cardinality().ConservativeUpperBound();
11455 const int lower_bound = cardinality().ConservativeLowerBound();
11458 if (action_count > upper_bound ||
11459 (action_count == upper_bound && repeated_action_specified_)) {
11461 }
else if (0 < action_count && action_count < lower_bound &&
11462 !repeated_action_specified_) {
11468 ::std::stringstream ss;
11469 DescribeLocationTo(&ss);
11470 ss <<
"Too " << (too_many ?
"many" :
"few")
11471 <<
" actions specified in " << source_text() <<
"...\n"
11472 <<
"Expected to be ";
11473 cardinality().DescribeTo(&ss);
11474 ss <<
", but has " << (too_many ?
"" :
"only ")
11475 << action_count <<
" WillOnce()"
11476 << (action_count == 1 ?
"" :
"s");
11477 if (repeated_action_specified_) {
11478 ss <<
" and a WillRepeatedly()";
11481 Log(kWarning, ss.str(), -1);
11486 void ExpectationBase::UntypedTimes(
const Cardinality& a_cardinality) {
11487 if (last_clause_ == kTimes) {
11488 ExpectSpecProperty(
false,
11489 ".Times() cannot appear "
11490 "more than once in an EXPECT_CALL().");
11492 ExpectSpecProperty(last_clause_ < kTimes,
11493 ".Times() cannot appear after "
11494 ".InSequence(), .WillOnce(), .WillRepeatedly(), "
11495 "or .RetiresOnSaturation().");
11497 last_clause_ = kTimes;
11499 SpecifyCardinality(a_cardinality);
11510 const int stack_frames_to_skip =
11512 switch (reaction) {
11519 "\nNOTE: You can safely ignore the above warning unless this "
11520 "call should not happen. Do not suppress it by blindly adding "
11521 "an EXPECT_CALL() if you don't mean to enforce the call. "
11522 "See https://github.com/google/googletest/blob/master/googlemock/docs/CookBook.md#"
11523 "knowing-when-to-expect for details.\n",
11524 stack_frames_to_skip);
11531 UntypedFunctionMockerBase::UntypedFunctionMockerBase()
11532 : mock_obj_(NULL),
name_(
"") {}
11534 UntypedFunctionMockerBase::~UntypedFunctionMockerBase() {}
11540 void UntypedFunctionMockerBase::RegisterOwner(
const void* mock_obj)
11544 mock_obj_ = mock_obj;
11546 Mock::Register(mock_obj,
this);
11552 void UntypedFunctionMockerBase::SetOwnerAndName(
const void* mock_obj,
11558 mock_obj_ = mock_obj;
11564 const void* UntypedFunctionMockerBase::MockObject()
const
11566 const void* mock_obj;
11571 Assert(mock_obj_ != NULL, __FILE__, __LINE__,
11572 "MockObject() must not be called before RegisterOwner() or "
11573 "SetOwnerAndName() has been called.");
11574 mock_obj = mock_obj_;
11581 const char* UntypedFunctionMockerBase::Name()
const
11589 "Name() must not be called before SetOwnerAndName() has "
11599 UntypedActionResultHolderBase*
11600 UntypedFunctionMockerBase::UntypedInvokeWith(
const void*
const untyped_args)
11602 if (untyped_expectations_.size() == 0) {
11611 Mock::GetReactionOnUninterestingCalls(MockObject());
11616 const bool need_to_report_uninteresting_call =
11627 if (!need_to_report_uninteresting_call) {
11629 return this->UntypedPerformDefaultAction(untyped_args,
"");
11633 ::std::stringstream ss;
11634 this->UntypedDescribeUninterestingCall(untyped_args, &ss);
11637 UntypedActionResultHolderBase*
const result =
11638 this->UntypedPerformDefaultAction(untyped_args, ss.str());
11642 result->PrintAsActionResult(&ss);
11648 bool is_excessive =
false;
11649 ::std::stringstream ss;
11650 ::std::stringstream why;
11651 ::std::stringstream
loc;
11652 const void* untyped_action = NULL;
11656 const ExpectationBase*
const untyped_expectation =
11657 this->UntypedFindMatchingExpectation(
11658 untyped_args, &untyped_action, &is_excessive,
11660 const bool found = untyped_expectation != NULL;
11665 const bool need_to_report_call =
11667 if (!need_to_report_call) {
11670 untyped_action == NULL ?
11671 this->UntypedPerformDefaultAction(untyped_args,
"") :
11672 this->UntypedPerformAction(untyped_action, untyped_args);
11675 ss <<
" Function call: " << Name();
11676 this->UntypedPrintArgs(untyped_args, &ss);
11680 if (
found && !is_excessive) {
11681 untyped_expectation->DescribeLocationTo(&
loc);
11684 UntypedActionResultHolderBase*
const result =
11685 untyped_action == NULL ?
11686 this->UntypedPerformDefaultAction(untyped_args, ss.str()) :
11687 this->UntypedPerformAction(untyped_action, untyped_args);
11689 result->PrintAsActionResult(&ss);
11690 ss <<
"\n" << why.str();
11694 Expect(
false, NULL, -1, ss.str());
11695 }
else if (is_excessive) {
11697 Expect(
false, untyped_expectation->file(),
11698 untyped_expectation->line(), ss.str());
11702 Log(kInfo,
loc.str() + ss.str(), 2);
11710 Expectation UntypedFunctionMockerBase::GetHandleOf(ExpectationBase* exp) {
11711 for (UntypedExpectations::const_iterator
it =
11712 untyped_expectations_.begin();
11713 it != untyped_expectations_.end(); ++
it) {
11714 if (
it->get() == exp) {
11719 Assert(
false, __FILE__, __LINE__,
"Cannot find expectation.");
11728 bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked()
11730 g_gmock_mutex.AssertHeld();
11731 bool expectations_met =
true;
11732 for (UntypedExpectations::const_iterator
it =
11733 untyped_expectations_.begin();
11734 it != untyped_expectations_.end(); ++
it) {
11735 ExpectationBase*
const untyped_expectation =
it->get();
11736 if (untyped_expectation->IsOverSaturated()) {
11740 expectations_met =
false;
11741 }
else if (!untyped_expectation->IsSatisfied()) {
11742 expectations_met =
false;
11743 ::std::stringstream ss;
11744 ss <<
"Actual function call count doesn't match "
11745 << untyped_expectation->source_text() <<
"...\n";
11749 untyped_expectation->MaybeDescribeExtraMatcherTo(&ss);
11750 untyped_expectation->DescribeCallCountTo(&ss);
11751 Expect(
false, untyped_expectation->file(),
11752 untyped_expectation->line(), ss.str());
11763 UntypedExpectations expectations_to_delete;
11764 untyped_expectations_.swap(expectations_to_delete);
11766 g_gmock_mutex.Unlock();
11767 expectations_to_delete.clear();
11768 g_gmock_mutex.Lock();
11770 return expectations_met;
11779 typedef std::set<internal::UntypedFunctionMockerBase*> FunctionMockers;
11784 struct MockObjectState {
11802 class MockObjectRegistry {
11805 typedef std::map<const void*, MockObjectState> StateMap;
11811 ~MockObjectRegistry() {
11818 int leaked_count = 0;
11821 if (
it->second.leakable)
11827 const MockObjectState&
state =
it->second;
11829 state.first_used_line);
11830 std::cout <<
" ERROR: this mock object";
11831 if (
state.first_used_test !=
"") {
11832 std::cout <<
" (used in test " <<
state.first_used_test_case <<
"."
11833 <<
state.first_used_test <<
")";
11835 std::cout <<
" should be deleted but never is. Its address is @"
11836 <<
it->first <<
".";
11839 if (leaked_count > 0) {
11840 std::cout <<
"\nERROR: " << leaked_count
11841 <<
" leaked mock " << (leaked_count == 1 ?
"object" :
"objects")
11842 <<
" found at program exit.\n";
11844 ::std::cerr.flush();
11853 StateMap& states() {
return states_; }
11860 MockObjectRegistry g_mock_object_registry;
11864 std::map<const void*, internal::CallReaction> g_uninteresting_call_reaction;
11868 void SetReactionOnUninterestingCalls(
const void* mock_obj,
11872 g_uninteresting_call_reaction[mock_obj] = reaction;
11879 void Mock::AllowUninterestingCalls(
const void* mock_obj)
11886 void Mock::WarnUninterestingCalls(
const void* mock_obj)
11893 void Mock::FailUninterestingCalls(
const void* mock_obj)
11900 void Mock::UnregisterCallReaction(
const void* mock_obj)
11903 g_uninteresting_call_reaction.erase(mock_obj);
11909 const void* mock_obj)
11912 return (g_uninteresting_call_reaction.count(mock_obj) == 0) ?
11913 internal::kDefault : g_uninteresting_call_reaction[mock_obj];
11918 void Mock::AllowLeak(
const void* mock_obj)
11921 g_mock_object_registry.states()[mock_obj].leakable =
true;
11927 bool Mock::VerifyAndClearExpectations(
void* mock_obj)
11930 return VerifyAndClearExpectationsLocked(mock_obj);
11936 bool Mock::VerifyAndClear(
void* mock_obj)
11939 ClearDefaultActionsLocked(mock_obj);
11940 return VerifyAndClearExpectationsLocked(mock_obj);
11946 bool Mock::VerifyAndClearExpectationsLocked(
void* mock_obj)
11948 internal::g_gmock_mutex.AssertHeld();
11949 if (g_mock_object_registry.states().count(mock_obj) == 0) {
11956 bool expectations_met =
true;
11957 FunctionMockers& mockers =
11958 g_mock_object_registry.states()[mock_obj].function_mockers;
11959 for (FunctionMockers::const_iterator
it = mockers.begin();
11960 it != mockers.end(); ++
it) {
11961 if (!(*it)->VerifyAndClearExpectationsLocked()) {
11962 expectations_met =
false;
11968 return expectations_met;
11972 void Mock::Register(
const void* mock_obj,
11973 internal::UntypedFunctionMockerBase* mocker)
11976 g_mock_object_registry.states()[mock_obj].function_mockers.insert(mocker);
11982 void Mock::RegisterUseByOnCallOrExpectCall(
const void* mock_obj,
11986 MockObjectState&
state = g_mock_object_registry.states()[mock_obj];
11987 if (
state.first_used_file == NULL) {
11990 const TestInfo*
const test_info =
11991 UnitTest::GetInstance()->current_test_info();
11992 if (test_info != NULL) {
11996 state.first_used_test_case = test_info->test_case_name();
11997 state.first_used_test = test_info->name();
12006 void Mock::UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
12008 internal::g_gmock_mutex.AssertHeld();
12010 g_mock_object_registry.states().begin();
12011 it != g_mock_object_registry.states().end(); ++
it) {
12012 FunctionMockers& mockers =
it->second.function_mockers;
12013 if (mockers.erase(mocker) > 0) {
12015 if (mockers.empty()) {
12016 g_mock_object_registry.states().erase(
it);
12024 void Mock::ClearDefaultActionsLocked(
void* mock_obj)
12026 internal::g_gmock_mutex.AssertHeld();
12028 if (g_mock_object_registry.states().count(mock_obj) == 0) {
12035 FunctionMockers& mockers =
12036 g_mock_object_registry.states()[mock_obj].function_mockers;
12037 for (FunctionMockers::const_iterator
it = mockers.begin();
12038 it != mockers.end(); ++
it) {
12039 (*it)->ClearDefaultActionsLocked();
12050 : expectation_base_(an_expectation_base) {}
12058 expectation.expectation_base()->immediate_prerequisites_
12123 "true iff Google Mock should report leaked mock objects "
12127 "Controls how verbose Google Mock's output is."
12129 " info - prints all messages.\n"
12130 " warning - prints warnings and errors.\n"
12131 " error - prints errors only.");
12142 bool def_optional) {
12144 if (
str == NULL ||
flag == NULL)
return NULL;
12148 const size_t flag_len = flag_str.length();
12149 if (strncmp(
str, flag_str.c_str(), flag_len) != 0)
return NULL;
12152 const char* flag_end =
str + flag_len;
12155 if (def_optional && (flag_end[0] ==
'\0')) {
12162 if (flag_end[0] !=
'=')
return NULL;
12165 return flag_end + 1;
12179 if (value_str == NULL)
return false;
12182 *
value = !(*value_str ==
'0' || *value_str ==
'f' || *value_str ==
'F');
12191 template <
typename String>
12198 if (value_str == NULL)
return false;
12201 *
value = value_str;
12209 template <
typename CharType>
12214 if (*argc <= 0)
return;
12216 for (
int i = 1;
i != *argc;
i++) {
12218 const char*
const arg = arg_string.c_str();
12228 for (
int j = i; j != *argc; j++) {
12229 argv[j] = argv[j + 1];