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_ 327 # define GTEST_HAS_GETTIMEOFDAY_ 1 334 # include <sys/mman.h> 335 # include <sys/time.h> 339 #elif GTEST_OS_SYMBIAN 340 # define GTEST_HAS_GETTIMEOFDAY_ 1 341 # include <sys/time.h> 344 # define GTEST_HAS_GETTIMEOFDAY_ 1 345 # include <sys/time.h> 350 #elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE. 352 # include <windows.h> 354 #elif GTEST_OS_WINDOWS // We are on Windows proper. 357 # include <sys/timeb.h> 358 # include <sys/types.h> 359 # include <sys/stat.h> 361 # if GTEST_OS_WINDOWS_MINGW 368 # define GTEST_HAS_GETTIMEOFDAY_ 1 369 # include <sys/time.h> 370 # endif // GTEST_OS_WINDOWS_MINGW 374 # include <windows.h> 381 # define GTEST_HAS_GETTIMEOFDAY_ 1 385 # include <sys/time.h> 388 #endif // GTEST_OS_LINUX 390 #if GTEST_HAS_EXCEPTIONS 391 # include <stdexcept> 394 #if GTEST_CAN_STREAM_RESULTS_ 395 # include <arpa/inet.h> 404 #define GTEST_IMPLEMENTATION_ 1 441 #ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_ 442 #define GTEST_SRC_GTEST_INTERNAL_INL_H_ 446 #if !GTEST_IMPLEMENTATION_ 448 # error "gtest-internal-inl.h is part of Google Test's internal implementation." 449 # error "It must not be included except by Google Test itself." 450 #endif // GTEST_IMPLEMENTATION_ 454 #endif // !_WIN32_WCE 464 #if GTEST_CAN_STREAM_RESULTS_ 465 # include <arpa/inet.h> 470 # include <windows.h> 471 #endif // GTEST_OS_WINDOWS 532 const char* str,
const char* flag,
Int32* value);
537 const unsigned int raw_seed = (random_seed_flag == 0) ?
539 static_cast<unsigned int>(random_seed_flag);
543 const int normalized_seed =
544 static_cast<int>((raw_seed - 1U) %
545 static_cast<unsigned int>(kMaxRandomSeed)) + 1;
546 return normalized_seed;
554 <<
"Invalid random seed " << seed <<
" - must be in [1, " 555 << kMaxRandomSeed <<
"].";
556 const int next_seed = seed + 1;
557 return (next_seed > kMaxRandomSeed) ? 1 : next_seed;
566 also_run_disabled_tests_ =
GTEST_FLAG(also_run_disabled_tests);
567 break_on_failure_ =
GTEST_FLAG(break_on_failure);
568 catch_exceptions_ =
GTEST_FLAG(catch_exceptions);
570 death_test_style_ =
GTEST_FLAG(death_test_style);
571 death_test_use_fork_ =
GTEST_FLAG(death_test_use_fork);
573 internal_run_death_test_ =
GTEST_FLAG(internal_run_death_test);
580 stack_trace_depth_ =
GTEST_FLAG(stack_trace_depth);
581 stream_result_to_ =
GTEST_FLAG(stream_result_to);
582 throw_on_failure_ =
GTEST_FLAG(throw_on_failure);
587 GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_;
588 GTEST_FLAG(break_on_failure) = break_on_failure_;
589 GTEST_FLAG(catch_exceptions) = catch_exceptions_;
591 GTEST_FLAG(death_test_style) = death_test_style_;
592 GTEST_FLAG(death_test_use_fork) = death_test_use_fork_;
594 GTEST_FLAG(internal_run_death_test) = internal_run_death_test_;
601 GTEST_FLAG(stack_trace_depth) = stack_trace_depth_;
602 GTEST_FLAG(stream_result_to) = stream_result_to_;
603 GTEST_FLAG(throw_on_failure) = throw_on_failure_;
663 const char* shard_index_str,
664 bool in_subprocess_for_death_test);
676 int total_shards,
int shard_index,
int test_id);
682 template <
class Container,
typename Predicate>
683 inline int CountIf(
const Container&
c, Predicate predicate) {
687 for (
typename Container::const_iterator it = c.begin(); it != c.end(); ++it) {
695 template <
class Container,
typename Functor>
696 void ForEach(
const Container&
c, Functor functor) {
697 std::for_each(c.begin(), c.end(), functor);
702 template <
typename E>
703 inline E
GetElementOr(
const std::vector<E>& v,
int i, E default_value) {
704 return (i < 0 || i >= static_cast<int>(v.size())) ? default_value : v[i];
711 template <
typename E>
714 const int size =
static_cast<int>(v->size());
716 <<
"Invalid shuffle range start " << begin <<
": must be in range [0, " 719 <<
"Invalid shuffle range finish " << end <<
": must be in range [" 720 << begin <<
", " << size <<
"].";
724 for (
int range_width = end - begin; range_width >= 2; range_width--) {
725 const int last_in_range = begin + range_width - 1;
726 const int selected = begin + random->
Generate(range_width);
727 std::swap((*v)[selected], (*v)[last_in_range]);
732 template <
typename E>
734 ShuffleRange(random, 0, static_cast<int>(v->size()), v);
739 template <
typename T>
756 return test_property.
key() == key_;
792 static bool PatternMatchesString(
const char *pattern,
const char *str);
796 static bool FilterMatchesTest(
const std::string &test_case_name,
805 static int GTestShouldProcessSEH(DWORD exception_code);
806 #endif // GTEST_OS_WINDOWS 810 static bool MatchesFilter(
const std::string&
name,
const char* filter);
829 virtual string CurrentStackTrace(
int max_depth,
int skip_count) = 0;
834 virtual void UponLeavingGTest() = 0;
845 virtual string CurrentStackTrace(
int max_depth,
int skip_count)
925 void SetGlobalTestPartResultReporter(
932 void SetTestPartResultReporterForCurrentThread(
936 int successful_test_case_count()
const;
939 int failed_test_case_count()
const;
942 int total_test_case_count()
const;
946 int test_case_to_run_count()
const;
949 int successful_test_count()
const;
952 int failed_test_count()
const;
955 int reportable_disabled_test_count()
const;
958 int disabled_test_count()
const;
961 int reportable_test_count()
const;
964 int total_test_count()
const;
967 int test_to_run_count()
const;
977 bool Passed()
const {
return !Failed(); }
982 return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed();
988 const int index =
GetElementOr(test_case_indices_, i, -1);
989 return index < 0 ? NULL : test_cases_[i];
995 const int index =
GetElementOr(test_case_indices_, i, -1);
996 return index < 0 ? NULL : test_cases_[index];
1043 TestCase* GetTestCase(
const char* test_case_name,
1044 const char* type_param,
1068 <<
"Failed to get the current working directory.";
1074 tear_down_tc)->AddTestInfo(test_info);
1077 #if GTEST_HAS_PARAM_TEST 1081 return parameterized_test_registry_;
1083 #endif // GTEST_HAS_PARAM_TEST 1087 current_test_case_ = a_current_test_case;
1094 current_test_info_ = a_current_test_info;
1103 void RegisterParameterizedTests();
1118 ad_hoc_test_result_.Clear();
1125 void RecordProperty(
const TestProperty& test_property);
1129 IGNORE_SHARDING_PROTOCOL
1141 void ListTestsMatchingFilter();
1153 return *(gtest_trace_stack_.pointer());
1156 return gtest_trace_stack_.get();
1159 #if GTEST_HAS_DEATH_TEST 1160 void InitDeathTestSubprocessControlInfo() {
1161 internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());
1167 const InternalRunDeathTestFlag* internal_run_death_test_flag()
const {
1168 return internal_run_death_test_flag_.get();
1172 internal::DeathTestFactory* death_test_factory() {
1173 return death_test_factory_.get();
1176 void SuppressTestEventsIfInSubprocess();
1178 friend class ReplaceDeathTestFactory;
1179 #endif // GTEST_HAS_DEATH_TEST 1183 void ConfigureXmlOutput();
1185 #if GTEST_CAN_STREAM_RESULTS_ 1188 void ConfigureStreamingOutput();
1196 void PostFlagParsingInit();
1206 void ShuffleTests();
1209 void UnshuffleTests();
1216 friend class ::testing::UnitTest;
1258 #if GTEST_HAS_PARAM_TEST 1265 #endif // GTEST_HAS_PARAM_TEST 1318 #if GTEST_HAS_DEATH_TEST 1323 #endif // GTEST_HAS_DEATH_TEST 1341 #if GTEST_USES_SIMPLE_RE 1345 GTEST_API_ bool IsInSet(
char ch,
const char* str);
1352 GTEST_API_ bool AtomMatchesChar(
bool escaped,
char pattern,
char ch);
1353 GTEST_API_ bool ValidateRegex(
const char* regex);
1354 GTEST_API_ bool MatchRegexAtHead(
const char* regex,
const char* str);
1355 GTEST_API_ bool MatchRepetitionAndRegexAtHead(
1356 bool escaped,
char ch,
char repeat,
const char* regex,
const char* str);
1357 GTEST_API_ bool MatchRegexAnywhere(
const char* regex,
const char* str);
1359 #endif // GTEST_USES_SIMPLE_RE 1366 #if GTEST_HAS_DEATH_TEST 1372 # if GTEST_OS_WINDOWS 1376 AutoHandle() : handle_(INVALID_HANDLE_VALUE) {}
1377 explicit AutoHandle(HANDLE
handle) : handle_(handle) {}
1379 ~AutoHandle() { Reset(); }
1381 HANDLE Get()
const {
return handle_; }
1382 void Reset() { Reset(INVALID_HANDLE_VALUE); }
1383 void Reset(HANDLE handle) {
1384 if (handle != handle_) {
1385 if (handle_ != INVALID_HANDLE_VALUE)
1386 ::CloseHandle(handle_);
1396 # endif // GTEST_OS_WINDOWS 1402 template <
typename Integer>
1407 if (str.empty() || !
IsDigit(str[0])) {
1416 # if GTEST_OS_WINDOWS && !defined(__GNUC__) 1419 typedef unsigned __int64 BiggestConvertible;
1420 const BiggestConvertible parsed = _strtoui64(str.c_str(), &
end, 10);
1424 typedef unsigned long long BiggestConvertible;
1425 const BiggestConvertible parsed = strtoull(str.c_str(), &
end, 10);
1427 # endif // GTEST_OS_WINDOWS && !defined(__GNUC__) 1429 const bool parse_success = *end ==
'\0' && errno == 0;
1435 const Integer result =
static_cast<Integer
>(parsed);
1436 if (parse_success && static_cast<BiggestConvertible>(result) == parsed) {
1442 #endif // GTEST_HAS_DEATH_TEST 1468 #if GTEST_CAN_STREAM_RESULTS_ 1474 class AbstractSocketWriter {
1476 virtual ~AbstractSocketWriter() {}
1479 virtual void Send(
const string&
message) = 0;
1482 virtual void CloseConnection() {}
1485 void SendLn(
const string& message) {
1486 Send(message +
"\n");
1491 class SocketWriter :
public AbstractSocketWriter {
1493 SocketWriter(
const string& host,
const string& port)
1494 : sockfd_(-1), host_name_(host), port_num_(port) {
1498 virtual ~SocketWriter() {
1504 virtual void Send(
const string&
message) {
1506 <<
"Send() can be called only when there is a connection.";
1508 const int len =
static_cast<int>(message.length());
1509 if (
write(sockfd_, message.c_str(), len) != len) {
1511 <<
"stream_result_to: failed to stream to " 1512 << host_name_ <<
":" << port_num_;
1518 void MakeConnection();
1521 void CloseConnection() {
1523 <<
"CloseConnection() can be called only when there is a connection.";
1530 const string host_name_;
1531 const string port_num_;
1537 static string UrlEncode(
const char* str);
1539 StreamingListener(
const string& host,
const string& port)
1540 : socket_writer_(
new SocketWriter(host, port)) { Start(); }
1542 explicit StreamingListener(AbstractSocketWriter* socket_writer)
1543 : socket_writer_(socket_writer) { Start(); }
1545 void OnTestProgramStart(
const UnitTest& ) {
1546 SendLn(
"event=TestProgramStart");
1549 void OnTestProgramEnd(
const UnitTest& unit_test) {
1552 SendLn(
"event=TestProgramEnd&passed=" + FormatBool(unit_test.
Passed()));
1555 socket_writer_->CloseConnection();
1558 void OnTestIterationStart(
const UnitTest& ,
int iteration) {
1559 SendLn(
"event=TestIterationStart&iteration=" +
1563 void OnTestIterationEnd(
const UnitTest& unit_test,
int ) {
1564 SendLn(
"event=TestIterationEnd&passed=" +
1565 FormatBool(unit_test.
Passed()) +
"&elapsed_time=" +
1569 void OnTestCaseStart(
const TestCase& test_case) {
1573 void OnTestCaseEnd(
const TestCase& test_case) {
1574 SendLn(
"event=TestCaseEnd&passed=" + FormatBool(test_case.
Passed())
1579 void OnTestStart(
const TestInfo& test_info) {
1583 void OnTestEnd(
const TestInfo& test_info) {
1584 SendLn(
"event=TestEnd&passed=" +
1585 FormatBool((test_info.
result())->Passed()) +
1591 const char* file_name = test_part_result.
file_name();
1592 if (file_name == NULL)
1594 SendLn(
"event=TestPartResult&file=" + UrlEncode(file_name) +
1596 "&message=" + UrlEncode(test_part_result.
message()));
1601 void SendLn(
const string&
message) { socket_writer_->SendLn(message); }
1605 void Start() { SendLn(
"gtest_streaming_protocol_version=1.0"); }
1607 string FormatBool(
bool value) {
return value ?
"1" :
"0"; }
1614 #endif // GTEST_CAN_STREAM_RESULTS_ 1619 #endif // GTEST_SRC_GTEST_INTERNAL_INL_H_ 1620 #undef GTEST_IMPLEMENTATION_ 1622 #if GTEST_OS_WINDOWS 1623 # define vsnprintf _vsnprintf 1624 #endif // GTEST_OS_WINDOWS 1657 namespace internal {
1674 also_run_disabled_tests,
1676 "Run disabled tests too, in addition to the tests normally being run.");
1681 "True iff a failed assertion should be a debugger break-point.");
1687 " should catch exceptions and treat them as test failures.");
1692 "Whether to use colors in the output. Valid values: yes, no, " 1693 "and auto. 'auto' means to use colors if the output is " 1694 "being sent to a terminal and the TERM environment variable " 1695 "is set to a terminal type that supports colors.");
1700 "A colon-separated list of glob (not regex) patterns " 1701 "for filtering the tests to run, optionally followed by a " 1702 "'-' and a : separated list of negative patterns (tests to " 1703 "exclude). A test is run if it matches one of the positive " 1704 "patterns and does not match any of the negative patterns.");
1707 "List all tests without running them.");
1712 "A format (currently must be \"xml\"), optionally followed " 1713 "by a colon and an output file name or directory. A directory " 1714 "is indicated by a trailing pathname separator. " 1715 "Examples: \"xml:filename.xml\", \"xml::directoryname/\". " 1716 "If a directory is specified, output files will be created " 1717 "within that directory, with file-names based on the test " 1718 "executable's name and, if necessary, made unique by adding " 1725 " should display elapsed time in text output.");
1730 "Random number seed to use when shuffling test orders. Must be in range " 1731 "[1, 99999], or 0 to use a seed based on the current time.");
1736 "How many times to repeat each test. Specify a negative number " 1737 "for repeating forever. Useful for shaking out flaky tests.");
1740 show_internal_stack_frames,
false,
1741 "True iff " GTEST_NAME_ " should include internal stack frames when " 1742 "printing test failure stack traces.");
1748 " should randomize tests' order on every run.");
1753 "The maximum number of stack frames to print when an " 1754 "assertion fails. The valid range is 0 through 100, inclusive.");
1759 "This flag specifies the host name and the port number on which to stream " 1760 "test results. Example: \"localhost:555\". The flag is effective only on " 1766 "When this flag is specified, a failed assertion will throw an exception " 1767 "if exceptions are enabled or exit the program with a non-zero code " 1770 namespace internal {
1777 state_ = (1103515245U*state_ + 12345U) % kMaxRange;
1780 <<
"Cannot generate a number in the range [0, 0).";
1782 <<
"Generation of a number in [0, " << range <<
") was requested, " 1783 <<
"but this can only generate numbers in [0, " << kMaxRange <<
").";
1788 return state_ % range;
1808 for (
size_t i = 0; i < case_list.size(); i++) {
1809 sum += (case_list[i]->*method)();
1864 #if GTEST_OS_WINDOWS 1865 result.
Set(
FilePath(g_executable_path).RemoveExtension(
"exe"));
1868 #endif // GTEST_OS_WINDOWS 1878 if (gtest_output_flag == NULL)
return std::string(
"");
1880 const char*
const colon = strchr(gtest_output_flag,
':');
1881 return (colon == NULL) ?
1883 std::string(gtest_output_flag, colon - gtest_output_flag);
1890 if (gtest_output_flag == NULL)
1893 const char*
const colon = strchr(gtest_output_flag,
':');
1911 return output_name.
string();
1915 GetOutputFormat().c_str()));
1929 return *str ==
'\0';
1931 return *str !=
'\0' && PatternMatchesString(pattern + 1, str + 1);
1933 return (*str !=
'\0' && PatternMatchesString(pattern, str + 1)) ||
1934 PatternMatchesString(pattern + 1, str);
1936 return *pattern == *str &&
1937 PatternMatchesString(pattern + 1, str + 1);
1943 const char *cur_pattern = filter;
1945 if (PatternMatchesString(cur_pattern, name.c_str())) {
1950 cur_pattern = strchr(cur_pattern,
':');
1953 if (cur_pattern == NULL) {
1966 const std::string& full_name = test_case_name +
"." + test_name.c_str();
1970 const char*
const p =
GTEST_FLAG(filter).c_str();
1971 const char*
const dash = strchr(p,
'-');
1980 if (positive.empty()) {
1988 return (MatchesFilter(full_name, positive.c_str()) &&
1989 !MatchesFilter(full_name, negative.c_str()));
1996 int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
2005 const DWORD kCxxExceptionCode = 0xe06d7363;
2007 bool should_handle =
true;
2010 should_handle =
false;
2011 else if (exception_code == EXCEPTION_BREAKPOINT)
2012 should_handle =
false;
2013 else if (exception_code == kCxxExceptionCode)
2014 should_handle =
false;
2016 return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
2018 #endif // GTEST_HAS_SEH 2027 : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
2071 namespace internal {
2083 return GetTypeId<Test>();
2098 const string& substr) {
2101 "1 non-fatal failure");
2103 if (results.
size() != 1) {
2104 msg <<
"Expected: " << expected <<
"\n" 2105 <<
" Actual: " << results.
size() <<
" failures";
2106 for (
int i = 0; i < results.
size(); i++) {
2113 if (r.
type() != type) {
2119 if (strstr(r.
message(), substr.c_str()) == NULL) {
2132 SingleFailureChecker:: SingleFailureChecker(
2135 const string& substr)
2136 : results_(results),
2169 return global_test_part_result_repoter_;
2176 global_test_part_result_repoter_ = reporter;
2182 return per_thread_test_part_result_reporter_.get();
2188 per_thread_test_part_result_reporter_.set(reporter);
2203 return static_cast<int>(test_cases_.size());
2265 #if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__) 2270 const DWORD kTenthMicrosInMilliSecond = 10000;
2272 SYSTEMTIME now_systime;
2273 FILETIME now_filetime;
2274 ULARGE_INTEGER now_int64;
2277 GetSystemTime(&now_systime);
2278 if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
2279 now_int64.LowPart = now_filetime.dwLowDateTime;
2280 now_int64.HighPart = now_filetime.dwHighDateTime;
2281 now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
2282 kJavaEpochToWinFileTimeDelta;
2283 return now_int64.QuadPart;
2286 #elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_ 2295 # pragma warning(push) // Saves the current warning state. 2296 # pragma warning(disable:4996) // Temporarily disables warning 4996. 2298 # pragma warning(pop) // Restores the warning state. 2305 return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
2308 gettimeofday(&now, NULL);
2309 return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
2311 # error
"Don't know how to get the current time on your system." 2319 #if GTEST_OS_WINDOWS_MOBILE 2324 LPCWSTR String::AnsiToUtf16(
const char* ansi) {
2325 if (!ansi)
return NULL;
2326 const int length = strlen(ansi);
2327 const int unicode_length =
2328 MultiByteToWideChar(CP_ACP, 0, ansi, length,
2330 WCHAR* unicode =
new WCHAR[unicode_length + 1];
2331 MultiByteToWideChar(CP_ACP, 0, ansi, length,
2332 unicode, unicode_length);
2333 unicode[unicode_length] = 0;
2341 const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
2342 if (!utf16_str)
return NULL;
2343 const int ansi_length =
2344 WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
2345 NULL, 0, NULL, NULL);
2346 char* ansi =
new char[ansi_length + 1];
2347 WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
2348 ansi, ansi_length, NULL, NULL);
2349 ansi[ansi_length] = 0;
2353 #endif // GTEST_OS_WINDOWS_MOBILE 2361 if ( lhs == NULL )
return rhs == NULL;
2363 if ( rhs == NULL )
return false;
2365 return strcmp(lhs, rhs) == 0;
2368 #if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING 2374 for (
size_t i = 0; i != length; ) {
2375 if (wstr[i] != L
'\0') {
2376 *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
2377 while (i != length && wstr[i] != L
'\0')
2386 #endif // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING 2398 *ss_ << std::setprecision(std::numeric_limits<double>::digits10 + 2);
2410 #if GTEST_HAS_STD_WSTRING 2417 #endif // GTEST_HAS_STD_WSTRING 2419 #if GTEST_HAS_GLOBAL_WSTRING 2426 #endif // GTEST_HAS_GLOBAL_WSTRING 2437 : success_(other.success_),
2438 message_(other.message_.
get() != NULL ?
2467 namespace internal {
2485 const char* actual_expression,
2488 bool ignoring_case) {
2490 msg <<
"Value of: " << actual_expression;
2491 if (actual_value != actual_expression) {
2492 msg <<
"\n Actual: " << actual_value;
2495 msg <<
"\nExpected: " << expected_expression;
2496 if (ignoring_case) {
2497 msg <<
" (ignoring case)";
2499 if (expected_value != expected_expression) {
2500 msg <<
"\nWhich is: " << expected_value;
2509 const char* expression_text,
2510 const char* actual_predicate_value,
2511 const char* expected_predicate_value) {
2512 const char* actual_message = assertion_result.
message();
2514 msg <<
"Value of: " << expression_text
2515 <<
"\n Actual: " << actual_predicate_value;
2516 if (actual_message[0] !=
'\0')
2517 msg <<
" (" << actual_message <<
")";
2518 msg <<
"\nExpected: " << expected_predicate_value;
2525 const char* abs_error_expr,
2529 const double diff = fabs(val1 - val2);
2535 <<
"The difference between " << expr1 <<
" and " << expr2
2536 <<
" is " << diff <<
", which exceeds " << abs_error_expr <<
", where\n" 2537 << expr1 <<
" evaluates to " << val1 <<
",\n" 2538 << expr2 <<
" evaluates to " << val2 <<
", and\n" 2539 << abs_error_expr <<
" evaluates to " << abs_error <<
".";
2544 template <
typename RawType>
2556 if (lhs.AlmostEquals(rhs)) {
2564 ::std::stringstream val1_ss;
2565 val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
2568 ::std::stringstream val2_ss;
2569 val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
2573 <<
"Expected: (" << expr1 <<
") <= (" << expr2 <<
")\n" 2583 float val1,
float val2) {
2584 return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
2590 double val1,
double val2) {
2591 return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
2594 namespace internal {
2599 const char* actual_expression,
2602 if (expected == actual) {
2616 #define GTEST_IMPL_CMP_HELPER_(op_name, op)\ 2617 AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \ 2618 BiggestInt val1, BiggestInt val2) {\ 2619 if (val1 op val2) {\ 2620 return AssertionSuccess();\ 2622 return AssertionFailure() \ 2623 << "Expected: (" << expr1 << ") " #op " (" << expr2\ 2624 << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\ 2625 << " vs " << FormatForComparisonFailureMessage(val2, val1);\ 2645 #undef GTEST_IMPL_CMP_HELPER_ 2649 const char* actual_expression,
2650 const char* expected,
2651 const char* actual) {
2652 if (String::CStringEquals(expected, actual)) {
2665 const char* actual_expression,
2666 const char* expected,
2667 const char* actual) {
2681 const char* s2_expression,
2684 if (!String::CStringEquals(s1, s2)) {
2688 << s2_expression <<
"), actual: \"" 2689 << s1 <<
"\" vs \"" << s2 <<
"\"";
2695 const char* s2_expression,
2702 <<
"Expected: (" << s1_expression <<
") != (" 2703 << s2_expression <<
") (ignoring case), actual: \"" 2704 << s1 <<
"\" vs \"" << s2 <<
"\"";
2718 bool IsSubstringPred(
const char* needle,
const char* haystack) {
2719 if (needle == NULL || haystack == NULL)
2720 return needle == haystack;
2722 return strstr(haystack, needle) != NULL;
2725 bool IsSubstringPred(
const wchar_t* needle,
const wchar_t* haystack) {
2726 if (needle == NULL || haystack == NULL)
2727 return needle == haystack;
2729 return wcsstr(haystack, needle) != NULL;
2733 template <
typename StringType>
2734 bool IsSubstringPred(
const StringType& needle,
2735 const StringType& haystack) {
2736 return haystack.find(needle) != StringType::npos;
2743 template <
typename StringType>
2745 bool expected_to_be_substring,
2746 const char* needle_expr,
const char* haystack_expr,
2747 const StringType& needle,
const StringType& haystack) {
2748 if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
2751 const bool is_wide_string =
sizeof(needle[0]) > 1;
2752 const char*
const begin_string_quote = is_wide_string ?
"L\"" :
"\"";
2754 <<
"Value of: " << needle_expr <<
"\n" 2755 <<
" Actual: " << begin_string_quote << needle <<
"\"\n" 2756 <<
"Expected: " << (expected_to_be_substring ?
"" :
"not ")
2757 <<
"a substring of " << haystack_expr <<
"\n" 2758 <<
"Which is: " << begin_string_quote << haystack <<
"\"";
2768 const char* needle_expr,
const char* haystack_expr,
2769 const char* needle,
const char* haystack) {
2770 return IsSubstringImpl(
true, needle_expr, haystack_expr, needle, haystack);
2774 const char* needle_expr,
const char* haystack_expr,
2775 const wchar_t* needle,
const wchar_t* haystack) {
2776 return IsSubstringImpl(
true, needle_expr, haystack_expr, needle, haystack);
2780 const char* needle_expr,
const char* haystack_expr,
2781 const char* needle,
const char* haystack) {
2782 return IsSubstringImpl(
false, needle_expr, haystack_expr, needle, haystack);
2786 const char* needle_expr,
const char* haystack_expr,
2787 const wchar_t* needle,
const wchar_t* haystack) {
2788 return IsSubstringImpl(
false, needle_expr, haystack_expr, needle, haystack);
2792 const char* needle_expr,
const char* haystack_expr,
2794 return IsSubstringImpl(
true, needle_expr, haystack_expr, needle, haystack);
2798 const char* needle_expr,
const char* haystack_expr,
2800 return IsSubstringImpl(
false, needle_expr, haystack_expr, needle, haystack);
2803 #if GTEST_HAS_STD_WSTRING 2805 const char* needle_expr,
const char* haystack_expr,
2807 return IsSubstringImpl(
true, needle_expr, haystack_expr, needle, haystack);
2811 const char* needle_expr,
const char* haystack_expr,
2813 return IsSubstringImpl(
false, needle_expr, haystack_expr, needle, haystack);
2815 #endif // GTEST_HAS_STD_WSTRING 2817 namespace internal {
2819 #if GTEST_OS_WINDOWS 2825 const char* expected,
2827 # if GTEST_OS_WINDOWS_MOBILE 2830 const char error_text[] =
"";
2837 const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
2838 FORMAT_MESSAGE_IGNORE_INSERTS;
2839 const DWORD kBufSize = 4096;
2841 char error_text[kBufSize] = {
'\0' };
2842 DWORD message_length = ::FormatMessageA(kFlags,
2850 for (; message_length &&
IsSpace(error_text[message_length - 1]);
2852 error_text[message_length - 1] =
'\0';
2855 # endif // GTEST_OS_WINDOWS_MOBILE 2857 const std::string error_hex(
"0x" + String::FormatHexInt(hr));
2859 <<
"Expected: " << expr <<
" " << expected <<
".\n" 2860 <<
" Actual: " << error_hex <<
" " << error_text <<
"\n";
2866 if (SUCCEEDED(hr)) {
2869 return HRESULTFailureHelper(expr,
"succeeds", hr);
2876 return HRESULTFailureHelper(expr,
"fails", hr);
2879 #endif // GTEST_OS_WINDOWS 2909 const UInt32 low_bits = *bits & ((
static_cast<UInt32>(1) << n) - 1);
2921 if (code_point > kMaxCodePoint4) {
2922 return "(Invalid Unicode 0x" + String::FormatHexInt(code_point) +
")";
2926 if (code_point <= kMaxCodePoint1) {
2928 str[0] =
static_cast<char>(code_point);
2929 }
else if (code_point <= kMaxCodePoint2) {
2931 str[1] =
static_cast<char>(0x80 |
ChopLowBits(&code_point, 6));
2932 str[0] =
static_cast<char>(0xC0 | code_point);
2933 }
else if (code_point <= kMaxCodePoint3) {
2935 str[2] =
static_cast<char>(0x80 |
ChopLowBits(&code_point, 6));
2936 str[1] =
static_cast<char>(0x80 |
ChopLowBits(&code_point, 6));
2937 str[0] =
static_cast<char>(0xE0 | code_point);
2940 str[3] =
static_cast<char>(0x80 |
ChopLowBits(&code_point, 6));
2941 str[2] =
static_cast<char>(0x80 |
ChopLowBits(&code_point, 6));
2942 str[1] =
static_cast<char>(0x80 |
ChopLowBits(&code_point, 6));
2943 str[0] =
static_cast<char>(0xF0 | code_point);
2956 return sizeof(wchar_t) == 2 &&
2957 (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;
2963 const UInt32 mask = (1 << 10) - 1;
2964 return (
sizeof(
wchar_t) == 2) ?
2965 (((first & mask) << 10) | (second & mask)) + 0x10000 :
2968 static_cast<UInt32>(first);
2985 if (num_chars == -1)
2986 num_chars =
static_cast<int>(wcslen(str));
2988 ::std::stringstream stream;
2989 for (
int i = 0; i < num_chars; ++i) {
2990 UInt32 unicode_code_point;
2992 if (str[i] == L
'\0') {
2999 unicode_code_point =
static_cast<UInt32>(str[i]);
3010 if (wide_c_str == NULL)
return "(null)";
3021 bool String::WideCStringEquals(
const wchar_t * lhs,
const wchar_t * rhs) {
3022 if (lhs == NULL)
return rhs == NULL;
3024 if (rhs == NULL)
return false;
3026 return wcscmp(lhs, rhs) == 0;
3031 const char* actual_expression,
3032 const wchar_t* expected,
3033 const wchar_t* actual) {
3034 if (String::WideCStringEquals(expected, actual)) {
3047 const char* s2_expression,
3049 const wchar_t* s2) {
3050 if (!String::WideCStringEquals(s1, s2)) {
3055 << s2_expression <<
"), actual: " 3086 bool String::CaseInsensitiveWideCStringEquals(
const wchar_t* lhs,
3087 const wchar_t* rhs) {
3088 if (lhs == NULL)
return rhs == NULL;
3090 if (rhs == NULL)
return false;
3092 #if GTEST_OS_WINDOWS 3093 return _wcsicmp(lhs, rhs) == 0;
3094 #elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID 3095 return wcscasecmp(lhs, rhs) == 0;
3101 left = towlower(*lhs++);
3102 right = towlower(*rhs++);
3103 }
while (left && left == right);
3104 return left == right;
3105 #endif // OS selector 3110 bool String::EndsWithCaseInsensitive(
3112 const size_t str_len = str.length();
3113 const size_t suffix_len = suffix.length();
3114 return (str_len >= suffix_len) &&
3121 std::stringstream ss;
3122 ss << std::setfill(
'0') << std::setw(2) << value;
3128 std::stringstream ss;
3129 ss <<
std::hex << std::uppercase << value;
3135 std::stringstream ss;
3136 ss << std::setfill(
'0') << std::setw(2) <<
std::hex << std::uppercase
3137 <<
static_cast<unsigned int>(value);
3145 const char*
const start = str.c_str();
3146 const char*
const end = start + str.length();
3149 result.reserve(2 * (end - start));
3150 for (
const char* ch = start; ch !=
end; ++ch) {
3166 if (user_msg_string.empty()) {
3170 return gtest_msg +
"\n" + user_msg_string;
3179 : death_test_count_(0),
3224 const std::vector<TestProperty>::iterator property_with_matching_key =
3231 property_with_matching_key->SetValue(test_property.
value());
3268 template <
int kSize>
3270 return std::vector<std::string>(array, array + kSize);
3275 if (xml_element ==
"testsuites") {
3277 }
else if (xml_element ==
"testsuite") {
3279 }
else if (xml_element ==
"testcase") {
3282 GTEST_CHECK_(
false) <<
"Unrecognized xml_element provided: " << xml_element;
3285 return std::vector<std::string>();
3290 for (
size_t i = 0; i < words.size(); ++i) {
3291 if (i > 0 && words.size() > 2) {
3294 if (i == words.size() - 1) {
3295 word_list <<
"and ";
3297 word_list <<
"'" << words[i] <<
"'";
3303 const std::vector<std::string>& reserved_names) {
3304 if (std::find(reserved_names.begin(), reserved_names.end(), property_name) !=
3305 reserved_names.end()) {
3306 ADD_FAILURE() <<
"Reserved key used in RecordProperty(): " << property_name
3376 : gtest_flag_saver_(new internal::GTestFlagSaver) {
3404 value_message << value;
3408 namespace internal {
3436 const char*
const first_test_name = first_test_info->
name();
3441 const char*
const this_test_name = this_test_info->
name();
3443 if (this_fixture_id != first_fixture_id) {
3449 if (first_is_TEST || this_is_TEST) {
3456 const char*
const TEST_name =
3457 first_is_TEST ? first_test_name : this_test_name;
3458 const char*
const TEST_F_name =
3459 first_is_TEST ? this_test_name : first_test_name;
3462 <<
"All tests in the same test case must use the same test fixture\n" 3463 <<
"class, so mixing TEST_F and TEST in the same test case is\n" 3466 <<
"test " << TEST_F_name <<
" is defined using TEST_F but\n" 3467 <<
"test " << TEST_name <<
" is defined using TEST. You probably\n" 3468 <<
"want to change the TEST to TEST_F or move it to another test\n" 3474 <<
"All tests in the same test case must use the same test fixture\n" 3475 <<
"class. However, in test case " 3477 <<
"you defined test " << first_test_name
3478 <<
" and test " << this_test_name <<
"\n" 3479 <<
"using two different test fixture classes. This can happen if\n" 3480 <<
"the two classes are from different namespaces or translation\n" 3481 <<
"units and have the same name. You should probably rename one\n" 3482 <<
"of the classes to put the tests into different test cases.";
3496 static std::string* FormatSehExceptionMessage(DWORD exception_code,
3497 const char* location) {
3499 message <<
"SEH exception with code 0x" << std::setbase(16) <<
3500 exception_code << std::setbase(10) <<
" thrown in " << location <<
".";
3505 #endif // GTEST_HAS_SEH 3507 namespace internal {
3509 #if GTEST_HAS_EXCEPTIONS 3513 const char* location) {
3515 if (description != NULL) {
3516 message <<
"C++ exception with description \"" << description <<
"\"";
3518 message <<
"Unknown C++ exception";
3520 message <<
" thrown in " << location <<
".";
3528 GoogleTestFailureException::GoogleTestFailureException(
3532 #endif // GTEST_HAS_EXCEPTIONS 3542 template <
class T,
typename Result>
3544 T*
object, Result (T::*method)(),
const char* location) {
3547 return (object->*method)();
3548 } __except (internal::UnitTestOptions::GTestShouldProcessSEH(
3549 GetExceptionCode())) {
3553 std::string* exception_message = FormatSehExceptionMessage(
3554 GetExceptionCode(), location);
3556 *exception_message);
3557 delete exception_message;
3558 return static_cast<Result
>(0);
3562 return (object->*method)();
3563 #endif // GTEST_HAS_SEH 3569 template <
class T,
typename Result>
3571 T*
object, Result (T::*method)(),
const char* location) {
3596 #if GTEST_HAS_EXCEPTIONS 3599 }
catch (
const internal::GoogleTestFailureException&) {
3604 }
catch (
const std::exception& e) {
3607 FormatCxxExceptionMessage(e.what(), location));
3611 FormatCxxExceptionMessage(NULL, location));
3613 return static_cast<Result
>(0);
3616 #endif // GTEST_HAS_EXCEPTIONS 3618 return (object->*method)();
3663 const char* a_type_param,
3664 const char* a_value_param,
3667 : test_case_name_(a_test_case_name),
3669 type_param_(a_type_param ? new
std::
string(a_type_param) : NULL),
3670 value_param_(a_value_param ? new
std::
string(a_value_param) : NULL),
3671 fixture_class_id_(fixture_class_id),
3673 is_disabled_(false),
3674 matches_filter_(false),
3681 namespace internal {
3710 new TestInfo(test_case_name, name, type_param, value_param,
3711 fixture_class_id, factory);
3716 #if GTEST_HAS_PARAM_TEST 3718 const char* file,
int line) {
3721 <<
"Attempted redefinition of test case " << test_case_name <<
".\n" 3722 <<
"All tests in the same test case must use the same test fixture\n" 3723 <<
"class. However, in test case " << test_case_name <<
", you tried\n" 3724 <<
"to define a test using a fixture class different from the one\n" 3725 <<
"used earlier. This can happen if the two fixture classes are\n" 3726 <<
"from different namespaces and have the same name. You should\n" 3727 <<
"probably rename one of the classes to put the tests into different\n" 3733 #endif // GTEST_HAS_PARAM_TEST 3752 explicit TestNameIs(
const char*
name)
3756 bool operator()(
const TestInfo * test_info)
const {
3757 return test_info && test_info->
name() ==
name_;
3766 namespace internal {
3771 void UnitTestImpl::RegisterParameterizedTests() {
3772 #if GTEST_HAS_PARAM_TEST 3773 if (!parameterized_tests_registered_) {
3774 parameterized_test_registry_.RegisterTests();
3775 parameterized_tests_registered_ =
true;
3803 "the test fixture's constructor");
3832 return CountIf(test_info_list_, TestPassed);
3837 return CountIf(test_info_list_, TestFailed);
3842 return CountIf(test_info_list_, TestReportableDisabled);
3847 return CountIf(test_info_list_, TestDisabled);
3852 return CountIf(test_info_list_, TestReportable);
3857 return CountIf(test_info_list_, ShouldRunTest);
3862 return static_cast<int>(test_info_list_.size());
3879 set_up_tc_(set_up_tc),
3880 tear_down_tc_(tear_down_tc),
3964 const char * singular_form,
3965 const char * plural_form) {
3967 (count == 1 ? singular_form : plural_form);
3997 return "Unknown result type";
4001 namespace internal {
4010 << test_part_result.
message()).GetString();
4017 printf(
"%s\n", result.c_str());
4023 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE 4027 ::OutputDebugStringA(result.c_str());
4028 ::OutputDebugStringA(
"\n");
4041 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE 4048 case COLOR_YELLOW:
return FOREGROUND_RED | FOREGROUND_GREEN;
4062 default:
return NULL;
4066 #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE 4070 const char*
const gtest_color =
GTEST_FLAG(color).c_str();
4073 #if GTEST_OS_WINDOWS 4076 return stdout_is_tty;
4080 const bool term_supports_color =
4081 String::CStringEquals(term,
"xterm") ||
4082 String::CStringEquals(term,
"xterm-color") ||
4083 String::CStringEquals(term,
"xterm-256color") ||
4084 String::CStringEquals(term,
"screen") ||
4085 String::CStringEquals(term,
"screen-256color") ||
4086 String::CStringEquals(term,
"linux") ||
4087 String::CStringEquals(term,
"cygwin");
4088 return stdout_is_tty && term_supports_color;
4089 #endif // GTEST_OS_WINDOWS 4095 String::CStringEquals(gtest_color,
"1");
4107 va_start(args, fmt);
4109 #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS || GTEST_OS_IOS 4110 const bool use_color =
false;
4112 static const bool in_color_mode =
4114 const bool use_color = in_color_mode && (color !=
COLOR_DEFAULT);
4115 #endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS 4124 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE 4125 const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
4128 CONSOLE_SCREEN_BUFFER_INFO buffer_info;
4129 GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
4130 const WORD old_color_attrs = buffer_info.wAttributes;
4136 SetConsoleTextAttribute(stdout_handle,
4137 GetColorAttribute(color) | FOREGROUND_INTENSITY);
4142 SetConsoleTextAttribute(stdout_handle, old_color_attrs);
4147 #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE 4158 const char*
const value_param = test_info.
value_param();
4160 if (type_param != NULL || value_param != NULL) {
4162 if (type_param != NULL) {
4163 printf(
"%s = %s", kTypeParamLabel, type_param);
4164 if (value_param != NULL)
4167 if (value_param != NULL) {
4168 printf(
"%s = %s", kValueParamLabel, value_param);
4180 printf(
"%s.%s", test_case, test);
4185 virtual void OnTestIterationStart(
const UnitTest& unit_test,
int iteration);
4186 virtual void OnEnvironmentsSetUpStart(
const UnitTest& unit_test);
4188 virtual void OnTestCaseStart(
const TestCase& test_case);
4189 virtual void OnTestStart(
const TestInfo& test_info);
4191 virtual void OnTestEnd(
const TestInfo& test_info);
4192 virtual void OnTestCaseEnd(
const TestCase& test_case);
4193 virtual void OnEnvironmentsTearDownStart(
const UnitTest& unit_test);
4195 virtual void OnTestIterationEnd(
const UnitTest& unit_test,
int iteration);
4199 static void PrintFailedTests(
const UnitTest& unit_test);
4203 void PrettyUnitTestResultPrinter::OnTestIterationStart(
4204 const UnitTest& unit_test,
int iteration) {
4206 printf(
"\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
4208 const char*
const filter =
GTEST_FLAG(filter).c_str();
4212 if (!String::CStringEquals(filter, kUniversalFilter)) {
4220 "Note: This is test shard %d of %s.\n",
4221 static_cast<int>(shard_index) + 1,
4227 "Note: Randomizing tests' orders with a seed of %d .\n",
4232 printf(
"Running %s from %s.\n",
4238 void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
4241 printf(
"Global test environment set-up.\n");
4245 void PrettyUnitTestResultPrinter::OnTestCaseStart(
const TestCase& test_case) {
4249 printf(
"%s from %s", counts.c_str(), test_case.
name());
4258 void PrettyUnitTestResultPrinter::OnTestStart(
const TestInfo& test_info) {
4266 void PrettyUnitTestResultPrinter::OnTestPartResult(
4277 void PrettyUnitTestResultPrinter::OnTestEnd(
const TestInfo& test_info) {
4296 void PrettyUnitTestResultPrinter::OnTestCaseEnd(
const TestCase& test_case) {
4302 printf(
"%s from %s (%s ms total)\n\n",
4303 counts.c_str(), test_case.
name(),
4308 void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
4311 printf(
"Global test environment tear-down\n");
4316 void PrettyUnitTestResultPrinter::PrintFailedTests(
const UnitTest& unit_test) {
4318 if (failed_test_count == 0) {
4340 void PrettyUnitTestResultPrinter::OnTestIterationEnd(
const UnitTest& unit_test,
4343 printf(
"%s from %s ran.",
4355 if (!unit_test.
Passed()) {
4359 PrintFailedTests(unit_test);
4360 printf(
"\n%2d FAILED %s\n", num_failures,
4361 num_failures == 1 ?
"TEST" :
"TESTS");
4365 if (num_disabled && !
GTEST_FLAG(also_run_disabled_tests)) {
4366 if (!num_failures) {
4370 " YOU HAVE %d DISABLED %s\n\n",
4372 num_disabled == 1 ?
"TEST" :
"TESTS");
4395 virtual void OnTestProgramStart(
const UnitTest& unit_test);
4396 virtual void OnTestIterationStart(
const UnitTest& unit_test,
int iteration);
4397 virtual void OnEnvironmentsSetUpStart(
const UnitTest& unit_test);
4398 virtual void OnEnvironmentsSetUpEnd(
const UnitTest& unit_test);
4399 virtual void OnTestCaseStart(
const TestCase& test_case);
4400 virtual void OnTestStart(
const TestInfo& test_info);
4402 virtual void OnTestEnd(
const TestInfo& test_info);
4403 virtual void OnTestCaseEnd(
const TestCase& test_case);
4404 virtual void OnEnvironmentsTearDownStart(
const UnitTest& unit_test);
4405 virtual void OnEnvironmentsTearDownEnd(
const UnitTest& unit_test);
4406 virtual void OnTestIterationEnd(
const UnitTest& unit_test,
int iteration);
4407 virtual void OnTestProgramEnd(
const UnitTest& unit_test);
4419 TestEventRepeater::~TestEventRepeater() {
4420 ForEach(listeners_, Delete<TestEventListener>);
4424 listeners_.push_back(listener);
4429 for (
size_t i = 0; i < listeners_.size(); ++i) {
4430 if (listeners_[i] == listener) {
4431 listeners_.erase(listeners_.begin() + i);
4441 #define GTEST_REPEATER_METHOD_(Name, Type) \ 4442 void TestEventRepeater::Name(const Type& parameter) { \ 4443 if (forwarding_enabled_) { \ 4444 for (size_t i = 0; i < listeners_.size(); i++) { \ 4445 listeners_[i]->Name(parameter); \ 4451 #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \ 4452 void TestEventRepeater::Name(const Type& parameter) { \ 4453 if (forwarding_enabled_) { \ 4454 for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \ 4455 listeners_[i]->Name(parameter); \ 4472 #undef GTEST_REPEATER_METHOD_ 4473 #undef GTEST_REVERSE_REPEATER_METHOD_ 4475 void TestEventRepeater::OnTestIterationStart(
const UnitTest& unit_test,
4477 if (forwarding_enabled_) {
4478 for (
size_t i = 0; i < listeners_.size(); i++) {
4479 listeners_[i]->OnTestIterationStart(unit_test, iteration);
4484 void TestEventRepeater::OnTestIterationEnd(
const UnitTest& unit_test,
4486 if (forwarding_enabled_) {
4487 for (
int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) {
4488 listeners_[i]->OnTestIterationEnd(unit_test, iteration);
4500 virtual void OnTestIterationEnd(
const UnitTest& unit_test,
int iteration);
4506 return c == 0x9 || c == 0xA || c == 0xD;
4511 return IsNormalizableWhitespace(c) || c >= 0x20;
4525 return EscapeXml(str,
true);
4530 return EscapeXml(str,
false);
4535 static void OutputXmlAttribute(std::ostream* stream,
4541 static void OutputXmlCDataSection(::std::ostream* stream,
const char* data);
4544 static void OutputXmlTestInfo(::std::ostream* stream,
4545 const char* test_case_name,
4549 static void PrintXmlTestCase(::std::ostream* stream,
4553 static void PrintXmlUnitTest(::std::ostream* stream,
4569 XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(
const char* output_file)
4570 : output_file_(output_file) {
4572 fprintf(stderr,
"XML output file may not be null\n");
4581 FILE* xmlout = NULL;
4585 if (
output_dir.CreateDirectoriesRecursively()) {
4588 if (xmlout == NULL) {
4600 "Unable to open file \"%s\"\n",
4605 std::stringstream stream;
4627 for (
size_t i = 0; i < str.size(); ++i) {
4628 const char ch = str[i];
4672 output.reserve(str.size());
4673 for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
4675 output.push_back(*it);
4698 ::std::stringstream ss;
4707 time_t seconds =
static_cast<time_t
>(ms / 1000);
4709 # pragma warning(push) // Saves the current warning state. 4710 # pragma warning(disable:4996) // Temporarily disables warning 4996 4712 const struct tm*
const time_struct =
localtime(&seconds);
4713 # pragma warning(pop) // Restores the warning state again. 4715 const struct tm*
const time_struct =
localtime(&seconds);
4717 if (time_struct == NULL)
4732 const char* segment = data;
4733 *stream <<
"<![CDATA[";
4735 const char*
const next_segment = strstr(segment,
"]]>");
4736 if (next_segment != NULL) {
4738 segment, static_cast<std::streamsize>(next_segment - segment));
4739 *stream <<
"]]>]]><![CDATA[";
4740 segment = next_segment + strlen(
"]]>");
4750 std::ostream* stream,
4754 const std::vector<std::string>& allowed_names =
4757 GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(),
name) !=
4758 allowed_names.end())
4759 <<
"Attribute " << name <<
" is not allowed for element <" << element_name
4768 const char* test_case_name,
4773 *stream <<
" <testcase";
4795 if (++failures == 1) {
4800 const string summary = location +
"\n" + part.
summary();
4801 *stream <<
" <failure message=\"" 4804 const string detail = location +
"\n" + part.
message();
4806 *stream <<
"</failure>\n";
4813 *stream <<
" </testcase>\n";
4820 *stream <<
" <" << kTestsuite;
4827 stream, kTestsuite,
"disabled",
4839 *stream <<
" </" << kTestsuite <<
">\n";
4847 *stream <<
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
4848 *stream <<
"<" << kTestsuites;
4855 stream, kTestsuites,
"disabled",
4859 stream, kTestsuites,
"timestamp",
4878 *stream <<
"</" << kTestsuites <<
">\n";
4888 attributes <<
" " <<
property.key() <<
"=" 4896 #if GTEST_CAN_STREAM_RESULTS_ 4903 string StreamingListener::UrlEncode(
const char* str) {
4905 result.reserve(strlen(str) + 1);
4906 for (
char ch = *str; ch !=
'\0'; ch = *++str) {
4915 result.push_back(ch);
4922 void StreamingListener::SocketWriter::MakeConnection() {
4924 <<
"MakeConnection() can't be called when there is already a connection.";
4927 memset(&hints, 0,
sizeof(hints));
4928 hints.ai_family = AF_UNSPEC;
4929 hints.ai_socktype = SOCK_STREAM;
4930 addrinfo* servinfo = NULL;
4934 const int error_num = getaddrinfo(
4935 host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
4936 if (error_num != 0) {
4937 GTEST_LOG_(WARNING) <<
"stream_result_to: getaddrinfo() failed: " 4938 << gai_strerror(error_num);
4942 for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != NULL;
4943 cur_addr = cur_addr->ai_next) {
4945 cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol);
4946 if (sockfd_ != -1) {
4948 if (
connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
4955 freeaddrinfo(servinfo);
4957 if (sockfd_ == -1) {
4958 GTEST_LOG_(WARNING) <<
"stream_result_to: failed to connect to " 4959 << host_name_ <<
":" << port_num_;
4964 #endif // GTEST_CAN_STREAM_RESULTS__ 5015 : premature_exit_filepath_(premature_exit_filepath) {
5017 if (premature_exit_filepath != NULL && *premature_exit_filepath !=
'\0') {
5021 FILE* pfile =
posix::FOpen(premature_exit_filepath,
"w");
5022 fwrite(
"0", 1, 1, pfile);
5028 if (premature_exit_filepath_ != NULL && *premature_exit_filepath_ !=
'\0') {
5029 remove(premature_exit_filepath_);
5044 : repeater_(new internal::TestEventRepeater()),
5045 default_result_printer_(NULL),
5046 default_xml_generator_(NULL) {
5085 if (listener != NULL)
5101 if (listener != NULL)
5137 #if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__) 5143 #endif // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__) 5148 return impl()->successful_test_case_count();
5153 return impl()->failed_test_case_count();
5158 return impl()->total_test_case_count();
5164 return impl()->test_case_to_run_count();
5169 return impl()->successful_test_count();
5177 return impl()->reportable_disabled_test_count();
5182 return impl()->disabled_test_count();
5187 return impl()->reportable_test_count();
5199 return impl()->start_timestamp();
5204 return impl()->elapsed_time();
5217 return impl()->GetTestCase(i);
5223 return *impl()->ad_hoc_test_result();
5229 return impl()->GetMutableTestCase(i);
5235 return *impl()->listeners();
5253 impl_->environments().push_back(env);
5263 const char* file_name,
5271 if (impl_->gtest_trace_stack().size() > 0) {
5274 for (
int i = static_cast<int>(impl_->gtest_trace_stack().size());
5282 if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) {
5289 impl_->GetTestPartResultReporterForCurrentThread()->
5290 ReportTestPartResult(result);
5299 #if GTEST_OS_WINDOWS 5309 *
static_cast<volatile int*
>(NULL) = 1;
5310 #endif // GTEST_OS_WINDOWS 5312 #if GTEST_HAS_EXCEPTIONS 5313 throw internal::GoogleTestFailureException(result);
5339 const bool in_death_test_child_process =
5364 in_death_test_child_process ?
5369 impl()->set_catch_exceptions(
GTEST_FLAG(catch_exceptions));
5376 if (impl()->catch_exceptions() || in_death_test_child_process) {
5377 # if !GTEST_OS_WINDOWS_MOBILE 5379 SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
5380 SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
5381 # endif // !GTEST_OS_WINDOWS_MOBILE 5383 # if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE 5387 _set_error_mode(_OUT_TO_STDERR);
5390 # if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE 5403 _set_abort_behavior(
5405 _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
5408 #endif // GTEST_HAS_SEH 5413 "auxiliary test code (environments or event listeners)") ? 0 : 1;
5419 return impl_->original_working_dir_.c_str();
5427 return impl_->current_test_case();
5435 return impl_->current_test_info();
5441 #if GTEST_HAS_PARAM_TEST 5447 return impl_->parameterized_test_registry();
5449 #endif // GTEST_HAS_PARAM_TEST 5466 impl_->gtest_trace_stack().push_back(
trace);
5473 impl_->gtest_trace_stack().pop_back();
5476 namespace internal {
5481 # pragma warning(push)
5482 # pragma warning(disable:4355)
5484 default_global_test_part_result_reporter_(this),
5485 default_per_thread_test_part_result_reporter_(this),
5486 # pragma warning(pop)
5488 default_global_test_part_result_reporter_(this),
5489 default_per_thread_test_part_result_reporter_(this),
5491 global_test_part_result_repoter_(
5492 &default_global_test_part_result_reporter_),
5493 per_thread_test_part_result_reporter_(
5494 &default_per_thread_test_part_result_reporter_),
5496 parameterized_test_registry_(),
5497 parameterized_tests_registered_(false),
5499 last_death_test_case_(-1),
5500 current_test_case_(NULL),
5501 current_test_info_(NULL),
5502 ad_hoc_test_result_(),
5503 os_stack_trace_getter_(NULL),
5504 post_flag_parse_init_performed_(false),
5507 start_timestamp_(0),
5509 #if GTEST_HAS_DEATH_TEST
5510 death_test_factory_(new DefaultDeathTestFactory),
5513 catch_exceptions_(false) {
5537 xml_element =
"testcase";
5540 xml_element =
"testsuite";
5543 xml_element =
"testsuites";
5549 #if GTEST_HAS_DEATH_TEST 5552 void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
5553 if (internal_run_death_test_flag_.get() != NULL)
5556 #endif // GTEST_HAS_DEATH_TEST 5562 if (output_format ==
"xml") {
5565 }
else if (output_format !=
"") {
5566 printf(
"WARNING: unrecognized output format \"%s\" ignored.\n",
5567 output_format.c_str());
5572 #if GTEST_CAN_STREAM_RESULTS_ 5575 void UnitTestImpl::ConfigureStreamingOutput() {
5577 if (!target.empty()) {
5578 const size_t pos = target.find(
':');
5579 if (pos != std::string::npos) {
5581 target.substr(pos+1)));
5583 printf(
"WARNING: unrecognized streaming target \"%s\" ignored.\n",
5589 #endif // GTEST_CAN_STREAM_RESULTS_ 5601 #if GTEST_HAS_DEATH_TEST 5602 InitDeathTestSubprocessControlInfo();
5603 SuppressTestEventsIfInSubprocess();
5604 #endif // GTEST_HAS_DEATH_TEST 5615 #if GTEST_CAN_STREAM_RESULTS_ 5617 ConfigureStreamingOutput();
5618 #endif // GTEST_CAN_STREAM_RESULTS_ 5638 return test_case != NULL && strcmp(test_case->
name(),
name_.c_str()) == 0;
5658 const char* type_param,
5662 const std::vector<TestCase*>::const_iterator test_case =
5671 new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc);
5675 kDeathTestCaseFilter)) {
5689 return new_test_case;
5710 "\nThis test program did NOT call ::testing::InitGoogleTest " 5711 "before calling RUN_ALL_TESTS(). Please fix it.\n");
5730 bool in_subprocess_for_death_test =
false;
5732 #if GTEST_HAS_DEATH_TEST 5733 in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL);
5734 #endif // GTEST_HAS_DEATH_TEST 5736 const bool should_shard =
ShouldShard(kTestTotalShards, kTestShardIndex,
5737 in_subprocess_for_death_test);
5741 const bool has_tests_to_run =
FilterTests(should_shard
5756 bool failed =
false;
5765 const int repeat = in_subprocess_for_death_test ? 1 :
GTEST_FLAG(repeat);
5767 const bool forever = repeat < 0;
5768 for (
int i = 0; forever || i != repeat; i++) {
5776 if (has_tests_to_run &&
GTEST_FLAG(shuffle)) {
5788 if (has_tests_to_run) {
5844 const char*
const test_shard_file =
posix::GetEnv(kTestShardStatusFile);
5845 if (test_shard_file != NULL) {
5849 "Could not write to the test shard status file \"%s\" " 5850 "specified by the %s environment variable.\n",
5851 test_shard_file, kTestShardStatusFile);
5866 const char* shard_index_env,
5867 bool in_subprocess_for_death_test) {
5868 if (in_subprocess_for_death_test) {
5875 if (total_shards == -1 && shard_index == -1) {
5877 }
else if (total_shards == -1 && shard_index != -1) {
5879 <<
"Invalid environment variables: you have " 5880 << kTestShardIndex <<
" = " << shard_index
5881 <<
", but have left " << kTestTotalShards <<
" unset.\n";
5885 }
else if (total_shards != -1 && shard_index == -1) {
5887 <<
"Invalid environment variables: you have " 5888 << kTestTotalShards <<
" = " << total_shards
5889 <<
", but have left " << kTestShardIndex <<
" unset.\n";
5893 }
else if (shard_index < 0 || shard_index >= total_shards) {
5895 <<
"Invalid environment variables: we require 0 <= " 5896 << kTestShardIndex <<
" < " << kTestTotalShards
5897 <<
", but you have " << kTestShardIndex <<
"=" << shard_index
5898 <<
", " << kTestTotalShards <<
"=" << total_shards <<
".\n";
5904 return total_shards > 1;
5912 if (str_val == NULL) {
5918 str_val, &result)) {
5929 return (test_id % total_shards) == shard_index;
5949 int num_runnable_tests = 0;
5950 int num_selected_tests = 0;
5956 for (
size_t j = 0; j < test_case->
test_info_list().size(); j++) {
5961 const bool is_disabled =
5963 kDisableTestFilter) ||
5965 kDisableTestFilter);
5968 const bool matches_filter =
5973 const bool is_runnable =
5974 (
GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
5977 const bool is_selected = is_runnable &&
5980 num_runnable_tests));
5982 num_runnable_tests += is_runnable;
5983 num_selected_tests += is_selected;
5989 return num_selected_tests;
5998 for (
int i = 0; *str !=
'\0'; ++str) {
5999 if (i >= max_length) {
6017 const int kMaxParamLength = 250;
6021 bool printed_test_case_name =
false;
6023 for (
size_t j = 0; j < test_case->
test_info_list().size(); j++) {
6027 if (!printed_test_case_name) {
6028 printed_test_case_name =
true;
6031 printf(
" # %s = ", kTypeParamLabel);
6040 printf(
" # %s = ", kValueParamLabel);
6129 class ClassUniqueToAlwaysTrue {};
6132 bool IsTrue(
bool condition) {
return condition; }
6135 #if GTEST_HAS_EXCEPTIONS 6139 throw ClassUniqueToAlwaysTrue();
6140 #endif // GTEST_HAS_EXCEPTIONS 6148 const size_t prefix_len = strlen(prefix);
6149 if (strncmp(*pstr, prefix, prefix_len) == 0) {
6150 *pstr += prefix_len;
6163 bool def_optional) {
6165 if (str == NULL || flag == NULL)
return NULL;
6169 const size_t flag_len = flag_str.length();
6170 if (strncmp(str, flag_str.c_str(), flag_len) != 0)
return NULL;
6173 const char* flag_end = str + flag_len;
6176 if (def_optional && (flag_end[0] ==
'\0')) {
6183 if (flag_end[0] !=
'=')
return NULL;
6186 return flag_end + 1;
6204 if (value_str == NULL)
return false;
6207 *value = !(*value_str ==
'0' || *value_str ==
'f' || *value_str ==
'F');
6221 if (value_str == NULL)
return false;
6238 if (value_str == NULL)
return false;
6279 const char* p = strchr(str,
'@');
6287 const char ch = p[1];
6291 }
else if (ch ==
'D') {
6293 }
else if (ch ==
'R') {
6295 }
else if (ch ==
'G') {
6297 }
else if (ch ==
'Y') {
6306 "This program contains tests written using " GTEST_NAME_ ". You can use the\n" 6307 "following command line flags to control its behavior:\n" 6311 " List the names of all tests instead of running them. The name of\n" 6312 " TEST(Foo, Bar) is \"Foo.Bar\".\n" 6314 "[@G-@YNEGATIVE_PATTERNS]@D\n" 6315 " Run only the tests whose name matches one of the positive patterns but\n" 6316 " none of the negative patterns. '?' matches any single character; '*'\n" 6317 " matches any substring; ':' separates two patterns.\n" 6319 " Run all disabled tests too.\n" 6323 " Run the tests repeatedly; use a negative count to repeat forever.\n" 6325 " Randomize tests' orders on every iteration.\n" 6327 " Random number seed to use for shuffling test orders (between 1 and\n" 6328 " 99999, or 0 to use a seed based on the current time).\n" 6332 " Enable/disable colored output. The default is @Gauto@D.\n" 6334 " Don't print the elapsed time of each test.\n" 6337 " Generate an XML report in the given directory or with the given file\n" 6338 " name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n" 6339 #if GTEST_CAN_STREAM_RESULTS_ 6341 " Stream test results to the given server.\n" 6342 #endif // GTEST_CAN_STREAM_RESULTS_ 6344 "Assertion Behavior:\n" 6345 #if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS 6347 " Set the default death test style.\n" 6348 #endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS 6350 " Turn assertion failures into debugger break-points.\n" 6352 " Turn assertion failures into C++ exceptions.\n" 6354 " Do not report exceptions as test failures. Instead, allow them\n" 6355 " to crash the program or throw a pop-up (on Windows).\n" 6358 "the corresponding\n" 6359 "environment variable of a flag (all letters in upper-case). For example, to\n" 6361 "color=no@D or set\n" 6364 "For more information, please read the " GTEST_NAME_ " documentation at\n" 6366 "(not one in your own code or tests), please report it to\n" 6372 template <
typename CharType>
6374 for (
int i = 1; i < *argc; i++) {
6376 const char*
const arg = arg_string.c_str();
6414 for (
int j = i; j != *argc; j++) {
6415 argv[j] = argv[j + 1];
6424 }
else if (arg_string ==
"--help" || arg_string ==
"-h" ||
6425 arg_string ==
"-?" || arg_string ==
"/?" ||
6454 template <
typename CharType>
6456 g_init_gtest_count++;
6459 if (g_init_gtest_count != 1)
return;
6461 if (*argc <= 0)
return;
6465 #if GTEST_HAS_DEATH_TEST 6468 for (
int i = 0; i != *argc; i++) {
6472 #endif // GTEST_HAS_DEATH_TEST 6534 #if GTEST_HAS_DEATH_TEST 6537 # include <crt_externs.h> 6538 # endif // GTEST_OS_MAC 6542 # include <limits.h> 6545 # include <signal.h> 6546 # endif // GTEST_OS_LINUX 6548 # include <stdarg.h> 6550 # if GTEST_OS_WINDOWS 6551 # include <windows.h> 6553 # include <sys/mman.h> 6554 # include <sys/wait.h> 6555 # endif // GTEST_OS_WINDOWS 6559 # endif // GTEST_OS_QNX 6561 #endif // GTEST_HAS_DEATH_TEST 6569 #define GTEST_IMPLEMENTATION_ 1 6570 #undef GTEST_IMPLEMENTATION_ 6582 "Indicates how to run a death test in a forked child process: " 6583 "\"threadsafe\" (child process re-executes the test binary " 6584 "from the beginning, running only the specific death test) or " 6585 "\"fast\" (child process runs the death test immediately " 6589 death_test_use_fork,
6591 "Instructs to use fork()/_exit() instead of clone() in death tests. " 6592 "Ignored and always uses fork() on POSIX systems where clone() is not " 6593 "implemented. Useful when running under valgrind or similar tools if " 6594 "those do not support clone(). Valgrind 3.3.1 will just fail if " 6595 "it sees an unsupported combination of clone() flags. " 6596 "It is not recommended to use this flag w/o valgrind though it will " 6597 "work in 99% of the cases. Once valgrind is fixed, this flag will " 6598 "most likely be removed.");
6600 namespace internal {
6602 internal_run_death_test,
"",
6603 "Indicates the file, line number, temporal index of " 6604 "the single death test to run, and a file descriptor to " 6605 "which a success code may be sent, all separated by " 6606 "the '|' characters. This flag is specified if and only if the current " 6607 "process is a sub-process launched for running a thread-safe " 6608 "death test. FOR INTERNAL USE ONLY.");
6611 #if GTEST_HAS_DEATH_TEST 6613 namespace internal {
6617 static bool g_in_fast_death_test_child =
false;
6624 bool InDeathTestChild() {
6625 # if GTEST_OS_WINDOWS 6629 return !
GTEST_FLAG(internal_run_death_test).empty();
6633 if (
GTEST_FLAG(death_test_style) ==
"threadsafe")
6634 return !
GTEST_FLAG(internal_run_death_test).empty();
6636 return g_in_fast_death_test_child;
6643 ExitedWithCode::ExitedWithCode(
int exit_code) : exit_code_(exit_code) {
6647 bool ExitedWithCode::operator()(
int exit_status)
const {
6648 # if GTEST_OS_WINDOWS 6650 return exit_status == exit_code_;
6654 return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;
6656 # endif // GTEST_OS_WINDOWS 6659 # if !GTEST_OS_WINDOWS 6661 KilledBySignal::KilledBySignal(
int signum) : signum_(signum) {
6665 bool KilledBySignal::operator()(
int exit_status)
const {
6666 return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;
6668 # endif // !GTEST_OS_WINDOWS 6670 namespace internal {
6679 # if GTEST_OS_WINDOWS 6681 m <<
"Exited with exit status " << exit_code;
6685 if (WIFEXITED(exit_code)) {
6686 m <<
"Exited with exit status " << WEXITSTATUS(exit_code);
6687 }
else if (WIFSIGNALED(exit_code)) {
6688 m <<
"Terminated by signal " << WTERMSIG(exit_code);
6691 if (WCOREDUMP(exit_code)) {
6692 m <<
" (core dumped)";
6695 # endif // GTEST_OS_WINDOWS 6702 bool ExitedUnsuccessfully(
int exit_status) {
6703 return !ExitedWithCode(0)(exit_status);
6706 # if !GTEST_OS_WINDOWS 6711 static std::string DeathTestThreadWarning(
size_t thread_count) {
6713 msg <<
"Death tests use fork(), which is unsafe particularly" 6714 <<
" in a threaded context. For this test, " <<
GTEST_NAME_ <<
" ";
6715 if (thread_count == 0)
6716 msg <<
"couldn't detect the number of threads.";
6718 msg <<
"detected " << thread_count <<
" threads.";
6721 # endif // !GTEST_OS_WINDOWS 6724 static const char kDeathTestLived =
'L';
6725 static const char kDeathTestReturned =
'R';
6726 static const char kDeathTestThrew =
'T';
6727 static const char kDeathTestInternalError =
'I';
6738 enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW };
6749 const InternalRunDeathTestFlag*
const flag =
6753 fputc(kDeathTestInternalError, parent);
6754 fprintf(parent,
"%s", message.c_str());
6758 fprintf(stderr,
"%s", message.c_str());
6766 # define GTEST_DEATH_TEST_CHECK_(expression) \ 6768 if (!::testing::internal::IsTrue(expression)) { \ 6770 ::std::string("CHECK failed: File ") + __FILE__ + ", line " \ 6771 + ::testing::internal::StreamableToString(__LINE__) + ": " \ 6774 } while (::testing::internal::AlwaysFalse()) 6783 # define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \ 6787 gtest_retval = (expression); \ 6788 } while (gtest_retval == -1 && errno == EINTR); \ 6789 if (gtest_retval == -1) { \ 6791 ::std::string("CHECK failed: File ") + __FILE__ + ", line " \ 6792 + ::testing::internal::StreamableToString(__LINE__) + ": " \ 6793 + #expression + " != -1"); \ 6795 } while (::testing::internal::AlwaysFalse()) 6806 static void FailFromInternalError(
int fd) {
6812 while ((num_read =
posix::Read(fd, buffer, 255)) > 0) {
6813 buffer[num_read] =
'\0';
6816 }
while (num_read == -1 && errno == EINTR);
6818 if (num_read == 0) {
6821 const int last_error = errno;
6822 GTEST_LOG_(FATAL) <<
"Error while reading death test internal: " 6823 << GetLastErrnoDescription() <<
" [" << last_error <<
"]";
6829 DeathTest::DeathTest() {
6832 DeathTestAbort(
"Cannot run a death test outside of a TEST or " 6833 "TEST_F construct");
6839 bool DeathTest::Create(
const char* statement,
const RE* regex,
6840 const char* file,
int line, DeathTest**
test) {
6842 statement, regex, file, line, test);
6845 const char* DeathTest::LastMessage() {
6846 return last_death_test_message_.c_str();
6849 void DeathTest::set_last_death_test_message(
const std::string& message) {
6850 last_death_test_message_ =
message;
6856 class DeathTestImpl :
public DeathTest {
6858 DeathTestImpl(
const char* a_statement,
const RE* a_regex)
6859 : statement_(a_statement),
6863 outcome_(IN_PROGRESS),
6868 ~DeathTestImpl() { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); }
6870 void Abort(AbortReason reason);
6871 virtual bool Passed(
bool status_ok);
6873 const char* statement()
const {
return statement_; }
6874 const RE* regex()
const {
return regex_; }
6875 bool spawned()
const {
return spawned_; }
6876 void set_spawned(
bool is_spawned) { spawned_ = is_spawned; }
6877 int status()
const {
return status_; }
6878 void set_status(
int a_status) { status_ = a_status; }
6879 DeathTestOutcome outcome()
const {
return outcome_; }
6880 void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; }
6881 int read_fd()
const {
return read_fd_; }
6882 void set_read_fd(
int fd) { read_fd_ = fd; }
6883 int write_fd()
const {
return write_fd_; }
6884 void set_write_fd(
int fd) { write_fd_ = fd; }
6890 void ReadAndInterpretStatusByte();
6895 const char*
const statement_;
6898 const RE*
const regex_;
6904 DeathTestOutcome outcome_;
6919 void DeathTestImpl::ReadAndInterpretStatusByte() {
6929 }
while (bytes_read == -1 && errno == EINTR);
6931 if (bytes_read == 0) {
6933 }
else if (bytes_read == 1) {
6935 case kDeathTestReturned:
6936 set_outcome(RETURNED);
6938 case kDeathTestThrew:
6941 case kDeathTestLived:
6944 case kDeathTestInternalError:
6945 FailFromInternalError(read_fd());
6948 GTEST_LOG_(FATAL) <<
"Death test child process reported " 6949 <<
"unexpected status byte (" 6950 <<
static_cast<unsigned int>(flag) <<
")";
6953 GTEST_LOG_(FATAL) <<
"Read from death test child process failed: " 6954 << GetLastErrnoDescription();
6956 GTEST_DEATH_TEST_CHECK_SYSCALL_(
posix::Close(read_fd()));
6968 const char status_ch =
6969 reason == TEST_DID_NOT_DIE ? kDeathTestLived :
6970 reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned;
6972 GTEST_DEATH_TEST_CHECK_SYSCALL_(
posix::Write(write_fd(), &status_ch, 1));
6989 for (
size_t at = 0; ; ) {
6990 const size_t line_end = output.find(
'\n', at);
6991 ret +=
"[ DEATH ] ";
6992 if (line_end == ::std::string::npos) {
6993 ret += output.substr(at);
6996 ret += output.substr(at, line_end + 1 - at);
7024 bool DeathTestImpl::Passed(
bool status_ok) {
7030 bool success =
false;
7033 buffer <<
"Death test: " << statement() <<
"\n";
7034 switch (outcome()) {
7036 buffer <<
" Result: failed to die.\n" 7037 <<
" Error msg:\n" << FormatDeathTestOutput(error_message);
7040 buffer <<
" Result: threw an exception.\n" 7041 <<
" Error msg:\n" << FormatDeathTestOutput(error_message);
7044 buffer <<
" Result: illegal return in test statement.\n" 7045 <<
" Error msg:\n" << FormatDeathTestOutput(error_message);
7053 buffer <<
" Result: died but not with expected error.\n" 7054 <<
" Expected: " << regex()->pattern() <<
"\n" 7055 <<
"Actual msg:\n" << FormatDeathTestOutput(error_message);
7058 buffer <<
" Result: died but not with expected exit code:\n" 7059 <<
" " << ExitSummary(status()) <<
"\n" 7060 <<
"Actual msg:\n" << FormatDeathTestOutput(error_message);
7066 <<
"DeathTest::Passed somehow called before conclusion of test";
7069 DeathTest::set_last_death_test_message(buffer.
GetString());
7073 # if GTEST_OS_WINDOWS 7102 class WindowsDeathTest :
public DeathTestImpl {
7104 WindowsDeathTest(
const char* a_statement,
7108 : DeathTestImpl(a_statement, a_regex), file_(file), line_(line) {}
7112 virtual TestRole AssumeRole();
7116 const char*
const file_;
7120 AutoHandle write_handle_;
7122 AutoHandle child_handle_;
7127 AutoHandle event_handle_;
7133 int WindowsDeathTest::Wait() {
7139 const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() };
7140 switch (::WaitForMultipleObjects(2,
7145 case WAIT_OBJECT_0 + 1:
7148 GTEST_DEATH_TEST_CHECK_(
false);
7153 write_handle_.Reset();
7154 event_handle_.Reset();
7156 ReadAndInterpretStatusByte();
7162 GTEST_DEATH_TEST_CHECK_(
7163 WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(),
7166 GTEST_DEATH_TEST_CHECK_(
7167 ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE);
7168 child_handle_.Reset();
7169 set_status(static_cast<int>(status_code));
7178 DeathTest::TestRole WindowsDeathTest::AssumeRole() {
7180 const InternalRunDeathTestFlag*
const flag =
7181 impl->internal_run_death_test_flag();
7182 const TestInfo*
const info = impl->current_test_info();
7188 set_write_fd(flag->write_fd());
7189 return EXECUTE_TEST;
7194 SECURITY_ATTRIBUTES handles_are_inheritable = {
7195 sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };
7196 HANDLE read_handle, write_handle;
7197 GTEST_DEATH_TEST_CHECK_(
7198 ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable,
7201 set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle),
7203 write_handle_.Reset(write_handle);
7204 event_handle_.Reset(::CreateEvent(
7205 &handles_are_inheritable,
7209 GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL);
7224 char executable_path[_MAX_PATH + 1];
7225 GTEST_DEATH_TEST_CHECK_(
7226 _MAX_PATH + 1 != ::GetModuleFileNameA(NULL,
7231 std::string(::GetCommandLineA()) +
" " + filter_flag +
" \"" +
7232 internal_flag +
"\"";
7234 DeathTest::set_last_death_test_message(
"");
7241 STARTUPINFOA startup_info;
7242 memset(&startup_info, 0,
sizeof(STARTUPINFO));
7243 startup_info.dwFlags = STARTF_USESTDHANDLES;
7244 startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE);
7245 startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE);
7246 startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE);
7248 PROCESS_INFORMATION process_info;
7249 GTEST_DEATH_TEST_CHECK_(::CreateProcessA(
7251 const_cast<char*>(command_line.c_str()),
7259 &process_info) != FALSE);
7260 child_handle_.Reset(process_info.hProcess);
7261 ::CloseHandle(process_info.hThread);
7263 return OVERSEE_TEST;
7265 # else // We are not on Windows. 7270 class ForkingDeathTest :
public DeathTestImpl {
7272 ForkingDeathTest(
const char* statement,
const RE* regex);
7278 void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; }
7286 ForkingDeathTest::ForkingDeathTest(
const char* a_statement,
const RE* a_regex)
7287 : DeathTestImpl(a_statement, a_regex),
7293 int ForkingDeathTest::Wait() {
7297 ReadAndInterpretStatusByte();
7300 GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0));
7301 set_status(status_value);
7302 return status_value;
7307 class NoExecDeathTest :
public ForkingDeathTest {
7309 NoExecDeathTest(
const char* a_statement,
const RE* a_regex) :
7310 ForkingDeathTest(a_statement, a_regex) { }
7311 virtual TestRole AssumeRole();
7316 DeathTest::TestRole NoExecDeathTest::AssumeRole() {
7318 if (thread_count != 1) {
7319 GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count);
7323 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
7325 DeathTest::set_last_death_test_message(
"");
7336 const pid_t child_pid = fork();
7337 GTEST_DEATH_TEST_CHECK_(child_pid != -1);
7338 set_child_pid(child_pid);
7339 if (child_pid == 0) {
7340 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0]));
7341 set_write_fd(pipe_fd[1]);
7349 g_in_fast_death_test_child =
true;
7350 return EXECUTE_TEST;
7352 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
7353 set_read_fd(pipe_fd[0]);
7355 return OVERSEE_TEST;
7362 class ExecDeathTest :
public ForkingDeathTest {
7364 ExecDeathTest(
const char* a_statement,
const RE* a_regex,
7365 const char* file,
int line) :
7366 ForkingDeathTest(a_statement, a_regex), file_(file), line_(line) { }
7367 virtual TestRole AssumeRole();
7369 static ::std::vector<testing::internal::string>
7370 GetArgvsForDeathTestChildProcess() {
7371 ::std::vector<testing::internal::string> args = GetInjectableArgvs();
7375 const char*
const file_;
7384 args_.push_back(NULL);
7388 for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
7393 void AddArgument(
const char* argument) {
7397 template <
typename Str>
7398 void AddArguments(const ::std::vector<Str>& arguments) {
7399 for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
7400 i != arguments.end();
7405 char*
const* Argv() {
7410 std::vector<char*> args_;
7415 struct ExecDeathTestArgs {
7421 inline char** GetEnviron() {
7425 return *_NSGetEnviron();
7431 inline char** GetEnviron() {
return environ; }
7432 # endif // GTEST_OS_MAC 7438 static int ExecDeathTestChildMain(
void* child_arg) {
7439 ExecDeathTestArgs*
const args =
static_cast<ExecDeathTestArgs*
>(child_arg);
7440 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd));
7445 const char*
const original_dir =
7448 if (chdir(original_dir) != 0) {
7449 DeathTestAbort(
std::string(
"chdir(\"") + original_dir +
"\") failed: " +
7450 GetLastErrnoDescription());
7451 return EXIT_FAILURE;
7459 execve(args->argv[0], args->argv, GetEnviron());
7460 DeathTestAbort(
std::string(
"execve(") + args->argv[0] +
", ...) in " +
7461 original_dir +
" failed: " +
7462 GetLastErrnoDescription());
7463 return EXIT_FAILURE;
7465 # endif // !GTEST_OS_QNX 7476 void StackLowerThanAddress(
const void* ptr,
bool* result)
GTEST_NO_INLINE_;
7477 void StackLowerThanAddress(
const void* ptr,
bool* result) {
7479 *result = (&dummy < ptr);
7482 bool StackGrowsDown() {
7485 StackLowerThanAddress(&dummy, &result);
7496 static pid_t ExecDeathTestSpawnChild(
char*
const* argv,
int close_fd) {
7497 ExecDeathTestArgs args = { argv, close_fd };
7498 pid_t child_pid = -1;
7503 const int cwd_fd = open(
".", O_RDONLY);
7504 GTEST_DEATH_TEST_CHECK_(cwd_fd != -1);
7505 GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC));
7509 const char*
const original_dir =
7512 if (chdir(original_dir) != 0) {
7513 DeathTestAbort(
std::string(
"chdir(\"") + original_dir +
"\") failed: " +
7514 GetLastErrnoDescription());
7515 return EXIT_FAILURE;
7520 GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD));
7521 GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD,
7522 fd_flags | FD_CLOEXEC));
7523 struct inheritance inherit = {0};
7525 child_pid = spawn(args.argv[0], 0, NULL, &inherit, args.argv, GetEnviron());
7527 GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1);
7528 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));
7530 # else // GTEST_OS_QNX 7535 struct sigaction saved_sigprof_action;
7536 struct sigaction ignore_sigprof_action;
7537 memset(&ignore_sigprof_action, 0,
sizeof(ignore_sigprof_action));
7538 sigemptyset(&ignore_sigprof_action.sa_mask);
7539 ignore_sigprof_action.sa_handler = SIG_IGN;
7540 GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction(
7541 SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));
7542 # endif // GTEST_OS_LINUX 7544 # if GTEST_HAS_CLONE 7545 const bool use_fork =
GTEST_FLAG(death_test_use_fork);
7548 static const bool stack_grows_down = StackGrowsDown();
7551 void*
const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE,
7552 MAP_ANON | MAP_PRIVATE, -1, 0);
7553 GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED);
7561 const size_t kMaxStackAlignment = 64;
7562 void*
const stack_top =
7563 static_cast<char*
>(stack) +
7564 (stack_grows_down ? stack_size - kMaxStackAlignment : 0);
7565 GTEST_DEATH_TEST_CHECK_(stack_size > kMaxStackAlignment &&
7566 reinterpret_cast<intptr_t>(stack_top) % kMaxStackAlignment == 0);
7568 child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args);
7570 GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);
7573 const bool use_fork =
true;
7574 # endif // GTEST_HAS_CLONE 7576 if (use_fork && (child_pid = fork()) == 0) {
7577 ExecDeathTestChildMain(&args);
7580 # endif // GTEST_OS_QNX 7582 GTEST_DEATH_TEST_CHECK_SYSCALL_(
7583 sigaction(SIGPROF, &saved_sigprof_action, NULL));
7584 # endif // GTEST_OS_LINUX 7586 GTEST_DEATH_TEST_CHECK_(child_pid != -1);
7594 DeathTest::TestRole ExecDeathTest::AssumeRole() {
7596 const InternalRunDeathTestFlag*
const flag =
7597 impl->internal_run_death_test_flag();
7598 const TestInfo*
const info = impl->current_test_info();
7602 set_write_fd(flag->write_fd());
7603 return EXECUTE_TEST;
7607 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
7610 GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
7621 args.AddArguments(GetArgvsForDeathTestChildProcess());
7622 args.AddArgument(filter_flag.c_str());
7623 args.AddArgument(internal_flag.c_str());
7625 DeathTest::set_last_death_test_message(
"");
7632 const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]);
7633 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
7634 set_child_pid(child_pid);
7635 set_read_fd(pipe_fd[0]);
7637 return OVERSEE_TEST;
7640 # endif // !GTEST_OS_WINDOWS 7647 bool DefaultDeathTestFactory::Create(
const char* statement,
const RE* regex,
7648 const char* file,
int line,
7651 const InternalRunDeathTestFlag*
const flag =
7652 impl->internal_run_death_test_flag();
7653 const int death_test_index = impl->current_test_info()
7654 ->increment_death_test_count();
7657 if (death_test_index > flag->index()) {
7658 DeathTest::set_last_death_test_message(
7660 +
") somehow exceeded expected maximum (" 7665 if (!(flag->file() == file && flag->line() == line &&
7666 flag->index() == death_test_index)) {
7672 # if GTEST_OS_WINDOWS 7674 if (
GTEST_FLAG(death_test_style) ==
"threadsafe" ||
7676 *test =
new WindowsDeathTest(statement, regex, file, line);
7681 if (
GTEST_FLAG(death_test_style) ==
"threadsafe") {
7682 *test =
new ExecDeathTest(statement, regex, file, line);
7683 }
else if (
GTEST_FLAG(death_test_style) ==
"fast") {
7684 *test =
new NoExecDeathTest(statement, regex);
7687 # endif // GTEST_OS_WINDOWS 7690 DeathTest::set_last_death_test_message(
7691 "Unknown death test style \"" +
GTEST_FLAG(death_test_style)
7692 +
"\" encountered");
7703 ::std::vector< ::std::string>* dest) {
7704 ::std::vector< ::std::string> parsed;
7705 ::std::string::size_type pos = 0;
7707 const ::std::string::size_type colon = str.find(delimiter, pos);
7708 if (colon == ::std::string::npos) {
7709 parsed.push_back(str.substr(pos));
7712 parsed.push_back(str.substr(pos, colon - pos));
7719 # if GTEST_OS_WINDOWS 7723 int GetStatusFileDescriptor(
unsigned int parent_process_id,
7724 size_t write_handle_as_size_t,
7725 size_t event_handle_as_size_t) {
7726 AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,
7728 parent_process_id));
7729 if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {
7730 DeathTestAbort(
"Unable to open parent process " +
7738 const HANDLE write_handle =
7739 reinterpret_cast<HANDLE
>(write_handle_as_size_t);
7740 HANDLE dup_write_handle;
7745 if (!::DuplicateHandle(parent_process_handle.Get(), write_handle,
7746 ::GetCurrentProcess(), &dup_write_handle,
7750 DUPLICATE_SAME_ACCESS)) {
7751 DeathTestAbort(
"Unable to duplicate the pipe handle " +
7753 " from the parent process " +
7757 const HANDLE event_handle =
reinterpret_cast<HANDLE
>(event_handle_as_size_t);
7758 HANDLE dup_event_handle;
7760 if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,
7761 ::GetCurrentProcess(), &dup_event_handle,
7764 DUPLICATE_SAME_ACCESS)) {
7765 DeathTestAbort(
"Unable to duplicate the event handle " +
7767 " from the parent process " +
7771 const int write_fd =
7772 ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND);
7773 if (write_fd == -1) {
7774 DeathTestAbort(
"Unable to convert pipe handle " +
7776 " to a file descriptor");
7781 ::SetEvent(dup_event_handle);
7785 # endif // GTEST_OS_WINDOWS 7790 InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
7791 if (
GTEST_FLAG(internal_run_death_test) ==
"")
return NULL;
7797 ::std::vector< ::std::string> fields;
7798 SplitString(
GTEST_FLAG(internal_run_death_test).c_str(),
'|', &fields);
7801 # if GTEST_OS_WINDOWS 7803 unsigned int parent_process_id = 0;
7804 size_t write_handle_as_size_t = 0;
7805 size_t event_handle_as_size_t = 0;
7807 if (fields.size() != 6
7808 || !ParseNaturalNumber(fields[1], &line)
7809 || !ParseNaturalNumber(fields[2], &index)
7810 || !ParseNaturalNumber(fields[3], &parent_process_id)
7811 || !ParseNaturalNumber(fields[4], &write_handle_as_size_t)
7812 || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
7813 DeathTestAbort(
"Bad --gtest_internal_run_death_test flag: " +
7816 write_fd = GetStatusFileDescriptor(parent_process_id,
7817 write_handle_as_size_t,
7818 event_handle_as_size_t);
7821 if (fields.size() != 4
7822 || !ParseNaturalNumber(fields[1], &line)
7823 || !ParseNaturalNumber(fields[2], &index)
7824 || !ParseNaturalNumber(fields[3], &write_fd)) {
7825 DeathTestAbort(
"Bad --gtest_internal_run_death_test flag: " 7829 # endif // GTEST_OS_WINDOWS 7831 return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);
7836 #endif // GTEST_HAS_DEATH_TEST 7873 #if GTEST_OS_WINDOWS_MOBILE 7874 # include <windows.h> 7875 #elif GTEST_OS_WINDOWS 7876 # include <direct.h> 7878 #elif GTEST_OS_SYMBIAN 7880 # include <sys/syslimits.h> 7882 # include <limits.h> 7884 #endif // GTEST_OS_WINDOWS_MOBILE 7886 #if GTEST_OS_WINDOWS 7887 # define GTEST_PATH_MAX_ _MAX_PATH 7888 #elif defined(PATH_MAX) 7889 # define GTEST_PATH_MAX_ PATH_MAX 7890 #elif defined(_XOPEN_PATH_MAX) 7891 # define GTEST_PATH_MAX_ _XOPEN_PATH_MAX 7893 # define GTEST_PATH_MAX_ _POSIX_PATH_MAX 7894 #endif // GTEST_OS_WINDOWS 7898 namespace internal {
7900 #if GTEST_OS_WINDOWS 7906 const char kAlternatePathSeparator =
'/';
7908 const char kAlternatePathSeparatorString[] =
"/";
7909 # if GTEST_OS_WINDOWS_MOBILE 7915 const DWORD kInvalidFileAttributes = 0xffffffff;
7917 const char kCurrentDirectoryString[] =
".\\";
7918 # endif // GTEST_OS_WINDOWS_MOBILE 7920 const char kPathSeparator =
'/';
7921 const char kPathSeparatorString[] =
"/";
7922 const char kCurrentDirectoryString[] =
"./";
7923 #endif // GTEST_OS_WINDOWS 7927 #if GTEST_HAS_ALT_PATH_SEP_ 7928 return (c == kPathSeparator) || (c == kAlternatePathSeparator);
7936 #if GTEST_OS_WINDOWS_MOBILE 7939 return FilePath(kCurrentDirectoryString);
7940 #elif GTEST_OS_WINDOWS 7942 return FilePath(_getcwd(cwd,
sizeof(cwd)) == NULL ?
"" : cwd);
7945 return FilePath(getcwd(cwd,
sizeof(cwd)) == NULL ?
"" : cwd);
7946 #endif // GTEST_OS_WINDOWS_MOBILE 7953 FilePath FilePath::RemoveExtension(
const char* extension)
const {
7955 if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) {
7957 0, pathname_.length() - dot_extension.length()));
7965 const char* FilePath::FindLastPathSeparator()
const {
7966 const char*
const last_sep = strrchr(c_str(), kPathSeparator);
7967 #if GTEST_HAS_ALT_PATH_SEP_ 7968 const char*
const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator);
7970 if (last_alt_sep != NULL &&
7971 (last_sep == NULL || last_alt_sep > last_sep)) {
7972 return last_alt_sep;
7985 const char*
const last_sep = FindLastPathSeparator();
7986 return last_sep ?
FilePath(last_sep + 1) : *
this;
7996 const char*
const last_sep = FindLastPathSeparator();
7999 dir =
std::string(c_str(), last_sep + 1 - c_str());
8015 const char* extension) {
8018 file = base_name.
string() +
"." + extension;
8023 return ConcatPaths(directory,
FilePath(file));
8031 return relative_path;
8033 return FilePath(dir.string() + kPathSeparator + relative_path.
string());
8038 bool FilePath::FileOrDirectoryExists()
const {
8039 #if GTEST_OS_WINDOWS_MOBILE 8040 LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());
8041 const DWORD attributes = GetFileAttributes(unicode);
8043 return attributes != kInvalidFileAttributes;
8046 return posix::Stat(pathname_.c_str(), &file_stat) == 0;
8047 #endif // GTEST_OS_WINDOWS_MOBILE 8052 bool FilePath::DirectoryExists()
const {
8053 bool result =
false;
8054 #if GTEST_OS_WINDOWS 8057 const FilePath& path(IsRootDirectory() ? *
this :
8058 RemoveTrailingPathSeparator());
8063 #if GTEST_OS_WINDOWS_MOBILE 8064 LPCWSTR unicode = String::AnsiToUtf16(path.
c_str());
8065 const DWORD attributes = GetFileAttributes(unicode);
8067 if ((attributes != kInvalidFileAttributes) &&
8068 (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
8075 #endif // GTEST_OS_WINDOWS_MOBILE 8082 bool FilePath::IsRootDirectory()
const {
8083 #if GTEST_OS_WINDOWS 8087 return pathname_.length() == 3 && IsAbsolutePath();
8089 return pathname_.length() == 1 &&
IsPathSeparator(pathname_.c_str()[0]);
8094 bool FilePath::IsAbsolutePath()
const {
8095 const char*
const name = pathname_.c_str();
8096 #if GTEST_OS_WINDOWS 8097 return pathname_.length() >= 3 &&
8098 ((name[0] >=
'a' && name[0] <=
'z') ||
8099 (name[0] >=
'A' && name[0] <=
'Z')) &&
8117 const char* extension) {
8121 full_pathname.
Set(MakeFileName(directory, base_name, number++, extension));
8123 return full_pathname;
8129 bool FilePath::IsDirectory()
const {
8130 return !pathname_.empty() &&
8137 bool FilePath::CreateDirectoriesRecursively()
const {
8138 if (!this->IsDirectory()) {
8142 if (pathname_.length() == 0 || this->DirectoryExists()) {
8146 const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName());
8154 bool FilePath::CreateFolder()
const {
8155 #if GTEST_OS_WINDOWS_MOBILE 8156 FilePath removed_sep(this->RemoveTrailingPathSeparator());
8157 LPCWSTR unicode = String::AnsiToUtf16(removed_sep.
c_str());
8158 int result = CreateDirectory(unicode, NULL) ? 0 : -1;
8160 #elif GTEST_OS_WINDOWS 8161 int result = _mkdir(pathname_.c_str());
8163 int result = mkdir(pathname_.c_str(), 0777);
8164 #endif // GTEST_OS_WINDOWS_MOBILE 8167 return this->DirectoryExists();
8175 FilePath FilePath::RemoveTrailingPathSeparator()
const {
8176 return IsDirectory()
8177 ?
FilePath(pathname_.substr(0, pathname_.length() - 1))
8185 void FilePath::Normalize() {
8186 if (pathname_.c_str() == NULL) {
8190 const char* src = pathname_.c_str();
8191 char*
const dest =
new char[pathname_.length() + 1];
8192 char* dest_ptr = dest;
8193 memset(dest_ptr, 0, pathname_.length() + 1);
8195 while (*src !=
'\0') {
8200 #if GTEST_HAS_ALT_PATH_SEP_ 8201 if (*dest_ptr == kAlternatePathSeparator) {
8254 #if GTEST_OS_WINDOWS_MOBILE 8255 # include <windows.h> 8256 #elif GTEST_OS_WINDOWS 8258 # include <sys/stat.h> 8260 # include <unistd.h> 8261 #endif // GTEST_OS_WINDOWS_MOBILE 8264 # include <mach/mach_init.h> 8265 # include <mach/task.h> 8266 # include <mach/vm_map.h> 8267 #endif // GTEST_OS_MAC 8270 # include <devctl.h> 8271 # include <sys/procfs.h> 8272 #endif // GTEST_OS_QNX 8280 #define GTEST_IMPLEMENTATION_ 1 8281 #undef GTEST_IMPLEMENTATION_ 8284 namespace internal {
8286 #if defined(_MSC_VER) || defined(__BORLANDC__) 8291 const int kStdOutFileno = STDOUT_FILENO;
8292 const int kStdErrFileno = STDERR_FILENO;
8300 const task_t task = mach_task_self();
8301 mach_msg_type_number_t thread_count;
8302 thread_act_array_t thread_list;
8303 const kern_return_t status = task_threads(task, &thread_list, &thread_count);
8304 if (status == KERN_SUCCESS) {
8308 reinterpret_cast<vm_address_t>(thread_list),
8309 sizeof(thread_t) * thread_count);
8310 return static_cast<size_t>(thread_count);
8321 const int fd = open(
"/proc/self/as", O_RDONLY);
8325 procfs_info process_info;
8327 devctl(fd, DCMD_PROC_INFO, &process_info,
sizeof(process_info), NULL);
8329 if (status == EOK) {
8330 return static_cast<size_t>(process_info.num_threads);
8344 #endif // GTEST_OS_MAC 8346 #if GTEST_USES_POSIX_RE 8356 regfree(&partial_regex_);
8357 regfree(&full_regex_);
8359 free(const_cast<char*>(pattern_));
8363 bool RE::FullMatch(
const char* str,
const RE& re) {
8367 return regexec(&re.
full_regex_, str, 1, &match, 0) == 0;
8372 bool RE::PartialMatch(
const char* str,
const RE& re) {
8380 void RE::Init(
const char* regex) {
8385 const size_t full_regex_len = strlen(regex) + 10;
8386 char*
const full_pattern =
new char[full_regex_len];
8388 snprintf(full_pattern, full_regex_len,
"^(%s)$", regex);
8389 is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0;
8399 const char*
const partial_regex = (*regex ==
'\0') ?
"()" : regex;
8400 is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0;
8403 <<
"Regular expression \"" << regex
8404 <<
"\" is not a valid POSIX Extended regular expression.";
8406 delete[] full_pattern;
8409 #elif GTEST_USES_SIMPLE_RE 8413 bool IsInSet(
char ch,
const char* str) {
8414 return ch !=
'\0' && strchr(str, ch) != NULL;
8420 bool IsAsciiDigit(
char ch) {
return '0' <= ch && ch <=
'9'; }
8421 bool IsAsciiPunct(
char ch) {
8422 return IsInSet(ch,
"^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
8424 bool IsRepeat(
char ch) {
return IsInSet(ch,
"?*+"); }
8425 bool IsAsciiWhiteSpace(
char ch) {
return IsInSet(ch,
" \f\n\r\t\v"); }
8426 bool IsAsciiWordChar(
char ch) {
8427 return (
'a' <= ch && ch <=
'z') || (
'A' <= ch && ch <=
'Z') ||
8428 (
'0' <= ch && ch <=
'9') || ch ==
'_';
8432 bool IsValidEscape(
char c) {
8433 return (IsAsciiPunct(c) || IsInSet(c,
"dDfnrsStvwW"));
8438 bool AtomMatchesChar(
bool escaped,
char pattern_char,
char ch) {
8440 switch (pattern_char) {
8441 case 'd':
return IsAsciiDigit(ch);
8442 case 'D':
return !IsAsciiDigit(ch);
8443 case 'f':
return ch ==
'\f';
8444 case 'n':
return ch ==
'\n';
8445 case 'r':
return ch ==
'\r';
8446 case 's':
return IsAsciiWhiteSpace(ch);
8447 case 'S':
return !IsAsciiWhiteSpace(ch);
8448 case 't':
return ch ==
'\t';
8449 case 'v':
return ch ==
'\v';
8450 case 'w':
return IsAsciiWordChar(ch);
8451 case 'W':
return !IsAsciiWordChar(ch);
8453 return IsAsciiPunct(pattern_char) && pattern_char == ch;
8456 return (pattern_char ==
'.' && ch !=
'\n') || pattern_char == ch;
8460 std::string FormatRegexSyntaxError(
const char* regex,
int index) {
8461 return (
Message() <<
"Syntax error at index " << index
8462 <<
" in simple regular expression \"" << regex <<
"\": ").GetString();
8467 bool ValidateRegex(
const char* regex) {
8468 if (regex == NULL) {
8472 ADD_FAILURE() <<
"NULL is not a valid simple regular expression.";
8476 bool is_valid =
true;
8479 bool prev_repeatable =
false;
8480 for (
int i = 0; regex[i]; i++) {
8481 if (regex[i] ==
'\\') {
8483 if (regex[i] ==
'\0') {
8484 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
8485 <<
"'\\' cannot appear at the end.";
8489 if (!IsValidEscape(regex[i])) {
8490 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
8491 <<
"invalid escape sequence \"\\" << regex[i] <<
"\".";
8494 prev_repeatable =
true;
8496 const char ch = regex[i];
8498 if (ch ==
'^' && i > 0) {
8500 <<
"'^' can only appear at the beginning.";
8502 }
else if (ch ==
'$' && regex[i + 1] !=
'\0') {
8504 <<
"'$' can only appear at the end.";
8506 }
else if (IsInSet(ch,
"()[]{}|")) {
8508 <<
"'" << ch <<
"' is unsupported.";
8510 }
else if (IsRepeat(ch) && !prev_repeatable) {
8512 <<
"'" << ch <<
"' can only follow a repeatable token.";
8516 prev_repeatable = !IsInSet(ch,
"^$?*+");
8530 bool MatchRepetitionAndRegexAtHead(
8531 bool escaped,
char c,
char repeat,
const char* regex,
8533 const size_t min_count = (repeat ==
'+') ? 1 : 0;
8534 const size_t max_count = (repeat ==
'?') ? 1 :
8535 static_cast<size_t>(-1) - 1;
8539 for (
size_t i = 0; i <= max_count; ++i) {
8541 if (i >= min_count && MatchRegexAtHead(regex, str + i)) {
8548 if (str[i] ==
'\0' || !AtomMatchesChar(escaped, c, str[i]))
8557 bool MatchRegexAtHead(
const char* regex,
const char* str) {
8564 return *str ==
'\0';
8567 const bool escaped = *regex ==
'\\';
8570 if (IsRepeat(regex[1])) {
8574 return MatchRepetitionAndRegexAtHead(
8575 escaped, regex[0], regex[1], regex + 2, str);
8580 return (*str !=
'\0') && AtomMatchesChar(escaped, *regex, *str) &&
8581 MatchRegexAtHead(regex + 1, str + 1);
8593 bool MatchRegexAnywhere(
const char* regex,
const char* str) {
8594 if (regex == NULL || str == NULL)
8598 return MatchRegexAtHead(regex + 1, str);
8602 if (MatchRegexAtHead(regex, str))
8604 }
while (*str++ !=
'\0');
8611 free(const_cast<char*>(pattern_));
8612 free(const_cast<char*>(full_pattern_));
8616 bool RE::FullMatch(
const char* str,
const RE& re) {
8617 return re.
is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);
8622 bool RE::PartialMatch(
const char* str,
const RE& re) {
8627 void RE::Init(
const char* regex) {
8628 pattern_ = full_pattern_ = NULL;
8629 if (regex != NULL) {
8633 is_valid_ = ValidateRegex(regex);
8639 const size_t len = strlen(regex);
8643 char* buffer =
static_cast<char*
>(malloc(len + 3));
8644 full_pattern_ = buffer;
8651 memcpy(buffer, regex, len);
8654 if (len == 0 || regex[len - 1] !=
'$')
8660 #endif // GTEST_USES_POSIX_RE 8667 const std::string file_name(file == NULL ? kUnknownFile : file);
8670 return file_name +
":";
8685 const char* file,
int line) {
8686 const std::string file_name(file == NULL ? kUnknownFile : file);
8696 : severity_(severity) {
8697 const char*
const marker =
8700 severity ==
GTEST_ERROR ?
"[ ERROR ]" :
"[ FATAL ]";
8701 GetStream() << ::std::endl << marker <<
" " 8716 # pragma warning(push) 8717 # pragma warning(disable: 4996) 8720 #if GTEST_HAS_STREAM_REDIRECTION 8727 # if GTEST_OS_WINDOWS 8728 char temp_dir_path[MAX_PATH + 1] = {
'\0' };
8729 char temp_file_path[MAX_PATH + 1] = {
'\0' };
8731 ::GetTempPathA(
sizeof(temp_dir_path), temp_dir_path);
8732 const UINT success = ::GetTempFileNameA(temp_dir_path,
8737 <<
"Unable to create a temporary file in " << temp_dir_path;
8738 const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
8739 GTEST_CHECK_(captured_fd != -1) <<
"Unable to open temporary file " 8741 filename_ = temp_file_path;
8747 # if GTEST_OS_LINUX_ANDROID 8762 char name_template[] =
"/sdcard/gtest_captured_stream.XXXXXX";
8764 char name_template[] =
"/tmp/captured_stream.XXXXXX";
8765 # endif // GTEST_OS_LINUX_ANDROID 8766 const int captured_fd = mkstemp(name_template);
8767 filename_ = name_template;
8768 # endif // GTEST_OS_WINDOWS 8770 dup2(captured_fd, fd_);
8775 remove(filename_.c_str());
8779 if (uncaptured_fd_ != -1) {
8782 dup2(uncaptured_fd_, fd_);
8783 close(uncaptured_fd_);
8784 uncaptured_fd_ = -1;
8787 FILE*
const file =
posix::FOpen(filename_.c_str(),
"r");
8798 static size_t GetFileSize(FILE* file);
8810 fseek(file, 0, SEEK_END);
8811 return static_cast<size_t>(ftell(file));
8816 const size_t file_size = GetFileSize(file);
8817 char*
const buffer =
new char[file_size];
8819 size_t bytes_last_read = 0;
8820 size_t bytes_read = 0;
8822 fseek(file, 0, SEEK_SET);
8827 bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
8828 bytes_read += bytes_last_read;
8829 }
while (bytes_last_read > 0 && bytes_read < file_size);
8838 # pragma warning(pop) 8846 if (*stream != NULL) {
8847 GTEST_LOG_(FATAL) <<
"Only one " << stream_name
8848 <<
" capturer can exist at a time.";
8855 const std::string content = (*captured_stream)->GetCapturedString();
8857 delete *captured_stream;
8858 *captured_stream = NULL;
8883 #endif // GTEST_HAS_STREAM_REDIRECTION 8885 #if GTEST_HAS_DEATH_TEST 8888 ::std::vector<testing::internal::string> g_argvs;
8890 static const ::std::vector<testing::internal::string>* g_injected_test_argvs =
8893 void SetInjectableArgvs(const ::std::vector<testing::internal::string>* argvs) {
8894 if (g_injected_test_argvs != argvs)
8895 delete g_injected_test_argvs;
8896 g_injected_test_argvs = argvs;
8899 const ::std::vector<testing::internal::string>& GetInjectableArgvs() {
8900 if (g_injected_test_argvs != NULL) {
8901 return *g_injected_test_argvs;
8905 #endif // GTEST_HAS_DEATH_TEST 8907 #if GTEST_OS_WINDOWS_MOBILE 8911 TerminateProcess(GetCurrentProcess(), 1);
8914 #endif // GTEST_OS_WINDOWS_MOBILE 8924 for (
size_t i = 0; i != full_flag.length(); i++) {
8925 env_var <<
ToUpper(full_flag.c_str()[i]);
8937 const long long_value = strtol(str, &end, 10);
8943 msg <<
"WARNING: " << src_text
8944 <<
" is expected to be a 32-bit integer, but actually" 8945 <<
" has value \"" << str <<
"\".\n";
8952 const Int32 result =
static_cast<Int32>(long_value);
8953 if (long_value == LONG_MAX || long_value == LONG_MIN ||
8956 result != long_value
8960 msg <<
"WARNING: " << src_text
8961 <<
" is expected to be a 32-bit integer, but actually" 8962 <<
" has value " << str <<
", which overflows.\n";
8978 const char*
const string_value =
posix::GetEnv(env_var.c_str());
8979 return string_value == NULL ?
8980 default_value : strcmp(string_value,
"0") != 0;
8988 const char*
const string_value =
posix::GetEnv(env_var.c_str());
8989 if (string_value == NULL) {
8991 return default_value;
8994 Int32 result = default_value;
8996 string_value, &result)) {
8997 printf(
"The default value %s is used.\n",
8998 (
Message() << default_value).GetString().c_str());
9000 return default_value;
9011 return value == NULL ? default_value : value;
9069 using ::std::ostream;
9072 void PrintByteSegmentInObjectTo(
const unsigned char* obj_bytes,
size_t start,
9073 size_t count, ostream* os) {
9075 for (
size_t i = 0; i !=
count; i++) {
9076 const size_t j = start + i;
9091 void PrintBytesInObjectToImpl(
const unsigned char* obj_bytes,
size_t count,
9094 *os << count <<
"-byte object <";
9096 const size_t kThreshold = 132;
9097 const size_t kChunkSize = 64;
9102 if (count < kThreshold) {
9103 PrintByteSegmentInObjectTo(obj_bytes, 0, count, os);
9105 PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os);
9108 const size_t resume_pos = (count - kChunkSize + 1)/2*2;
9109 PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os);
9116 namespace internal2 {
9125 PrintBytesInObjectToImpl(obj_bytes, count, os);
9130 namespace internal {
9147 return 0x20 <= c && c <= 0x7E;
9154 template <
typename Un
signedChar,
typename Char>
9156 switch (static_cast<wchar_t>(c)) {
9189 *os << static_cast<char>(
c);
9210 return PrintAsCharLiteralTo<wchar_t>(
c, os);
9218 static_cast<wchar_t>(static_cast<unsigned char>(c)), os);
9225 template <
typename Un
signedChar,
typename Char>
9228 *os << ((sizeof(c) > 1) ?
"L'" :
"'");
9237 *os <<
" (" <<
static_cast<int>(
c);
9242 if (format ==
kHexEscape || (1 <= c && c <= 9)) {
9251 PrintCharAndCodeTo<unsigned char>(
c, os);
9254 PrintCharAndCodeTo<unsigned char>(
c, os);
9260 PrintCharAndCodeTo<wchar_t>(wc, os);
9267 template <
typename CharType>
9269 const CharType* begin,
size_t len, ostream* os) {
9270 const char*
const kQuoteBegin =
sizeof(CharType) == 1 ?
"\"" :
"L\"";
9272 bool is_previous_hex =
false;
9273 for (
size_t index = 0; index < len; ++index) {
9274 const CharType cur = begin[index];
9275 if (is_previous_hex &&
IsXDigit(cur)) {
9279 *os <<
"\" " << kQuoteBegin;
9288 template <
typename CharType>
9290 const CharType* begin,
size_t len, ostream* os) {
9298 if (len > 0 && begin[len - 1] ==
'\0') {
9308 *os <<
" (no terminating NUL)";
9327 *os << ImplicitCast_<const void*>(s) <<
" pointing to ";
9338 #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED) 9344 *os << ImplicitCast_<const void*>(s) <<
" pointing to ";
9348 #endif // wchar_t is native 9351 #if GTEST_HAS_GLOBAL_STRING 9355 #endif // GTEST_HAS_GLOBAL_STRING 9362 #if GTEST_HAS_GLOBAL_WSTRING 9366 #endif // GTEST_HAS_GLOBAL_WSTRING 9368 #if GTEST_HAS_STD_WSTRING 9372 #endif // GTEST_HAS_STD_WSTRING 9416 #define GTEST_IMPLEMENTATION_ 1 9417 #undef GTEST_IMPLEMENTATION_ 9427 return stack_trace == NULL ? message :
9437 "Non-fatal failure") <<
":\n" 9438 << result.
message() << std::endl;
9443 array_.push_back(result);
9448 if (index < 0 || index >= size()) {
9449 printf(
"\nInvalid index (%d) into TestPartResultArray.\n", index);
9453 return array_[index];
9458 return static_cast<int>(array_.size());
9461 namespace internal {
9464 : has_new_fatal_failure_(false),
9466 GetTestPartResultReporterForCurrentThread()) {
9518 namespace internal {
9520 #if GTEST_HAS_TYPED_TEST_P 9524 static const char* SkipSpaces(
const char* str) {
9533 const char* TypedTestCasePState::VerifyRegisteredTestNames(
9534 const char* file,
int line,
const char* registered_tests) {
9535 typedef ::std::set<const char*>::const_iterator DefinedTestIter;
9540 registered_tests = SkipSpaces(registered_tests);
9543 ::std::set<std::string> tests;
9544 for (
const char* names = registered_tests; names != NULL;
9545 names = SkipComma(names)) {
9547 if (tests.count(name) != 0) {
9548 errors <<
"Test " << name <<
" is listed more than once.\n";
9553 for (DefinedTestIter it = defined_test_names_.begin();
9554 it != defined_test_names_.end();
9565 errors <<
"No test named " << name
9566 <<
" can be found in this test case.\n";
9570 for (DefinedTestIter it = defined_test_names_.begin();
9571 it != defined_test_names_.end();
9573 if (tests.count(*it) == 0) {
9574 errors <<
"You forgot to list test " << *it <<
".\n";
9579 if (errors_str !=
"") {
9581 errors_str.c_str());
9586 return registered_tests;
9589 #endif // GTEST_HAS_TYPED_TEST_P 9632 #include "gmock/gmock.h" 9683 BetweenCardinalityImpl(
int min,
int max)
9684 :
min_(min >= 0 ? min : 0),
9686 std::stringstream ss;
9688 ss <<
"The invocation lower bound must be >= 0, " 9689 <<
"but is actually " << min <<
".";
9691 }
else if (max < 0) {
9692 ss <<
"The invocation upper bound must be >= 0, " 9693 <<
"but is actually " << max <<
".";
9695 }
else if (min > max) {
9696 ss <<
"The invocation upper bound (" << max
9697 <<
") must be >= the invocation lower bound (" << min
9705 virtual int ConservativeLowerBound()
const {
return min_; }
9706 virtual int ConservativeUpperBound()
const {
return max_; }
9708 virtual bool IsSatisfiedByCallCount(
int call_count)
const {
9709 return min_ <= call_count && call_count <=
max_;
9712 virtual bool IsSaturatedByCallCount(
int call_count)
const {
9713 return call_count >=
max_;
9716 virtual void DescribeTo(::std::ostream* os)
const;
9729 }
else if (n == 2) {
9732 std::stringstream ss;
9733 ss << n <<
" times";
9739 void BetweenCardinalityImpl::DescribeTo(::std::ostream* os)
const {
9742 *os <<
"never called";
9743 }
else if (
max_ == INT_MAX) {
9744 *os <<
"called any number of times";
9746 *os <<
"called at most " << FormatTimes(
max_);
9749 *os <<
"called " << FormatTimes(
min_);
9750 }
else if (
max_ == INT_MAX) {
9751 *os <<
"called at least " << FormatTimes(
min_);
9754 *os <<
"called between " <<
min_ <<
" and " <<
max_ <<
" times";
9762 ::std::ostream* os) {
9763 if (actual_call_count > 0) {
9764 *os <<
"called " << FormatTimes(actual_call_count);
9766 *os <<
"never called";
9781 return Cardinality(
new BetweenCardinalityImpl(min, max));
9831 namespace internal {
9839 char prev_char =
'\0';
9840 for (
const char* p = id_name; *p !=
'\0'; prev_char = *(p++)) {
9843 const bool starts_new_word =
IsUpper(*p) ||
9848 if (starts_new_word && result !=
"")
9862 const string& message) {
9869 if (type == kFatal) {
9883 static FailureReporterInterface*
const failure_reporter =
9885 return failure_reporter;
9915 const string& message,
9916 int stack_frames_to_skip) {
9928 std::cout <<
"\nGMOCK WARNING:";
9931 if (message.empty() || message[0] !=
'\n') {
9935 if (stack_frames_to_skip >= 0) {
9938 const int actual_to_skip = 0;
9942 const int actual_to_skip = stack_frames_to_skip + 1;
9946 if (!message.empty() && *message.rbegin() !=
'\n') {
9949 std::cout <<
"Stack trace:\n" 10021 #if GTEST_HAS_STRING_PIECE_ 10037 *
this =
Eq(s.ToString());
10052 *
this =
Eq(s.ToString());
10054 #endif // GTEST_HAS_STRING_PIECE_ 10056 namespace internal {
10061 switch (fields.size()) {
10067 string result =
"(" + fields[0];
10068 for (
size_t i = 1; i < fields.size(); i++) {
10070 result += fields[i];
10083 const char* matcher_name,
10084 const Strings& param_values) {
10086 if (param_values.size() >= 1)
10088 return negation ?
"not (" + result +
")" : result;
10164 ::std::vector<char> seen;
10177 for (
size_t ilhs = 0; ilhs <
graph_->LhsSize(); ++ilhs) {
10181 <<
"ilhs: " << ilhs <<
", left_[ilhs]: " << left_[ilhs];
10183 seen.assign(
graph_->RhsSize(), 0);
10184 TryAugment(ilhs, &seen);
10187 for (
size_t ilhs = 0; ilhs < left_.size(); ++ilhs) {
10188 size_t irhs = left_[ilhs];
10189 if (irhs ==
kUnused)
continue;
10196 static const size_t kUnused =
static_cast<size_t>(-1);
10215 for (
size_t irhs = 0; irhs <
graph_->RhsSize(); ++irhs) {
10218 if (!
graph_->HasEdge(ilhs, irhs))
10232 if (right_[irhs] == kUnused || TryAugment(right_[irhs], seen)) {
10234 left_[ilhs] = irhs;
10235 right_[irhs] = ilhs;
10268 ::std::ostream* stream) {
10269 typedef ElementMatcherPairs::const_iterator
Iter;
10270 ::std::ostream& os = *stream;
10272 const char *sep =
"";
10273 for (Iter it = pairs.begin(); it != pairs.end(); ++it) {
10274 os << sep <<
"\n (" 10275 <<
"element #" << it->first <<
", " 10276 <<
"matcher #" << it->second <<
")";
10287 size_t max_flow = matches.size();
10288 bool result = (max_flow == matrix.
RhsSize());
10292 *listener <<
"where no permutation of the elements can " 10293 "satisfy all matchers, and the closest match is " 10294 << max_flow <<
" of " << matrix.
RhsSize()
10295 <<
" matchers with the pairings:\n";
10301 if (matches.size() > 1) {
10303 const char *sep =
"where:\n";
10304 for (
size_t mi = 0; mi < matches.size(); ++mi) {
10305 *listener << sep <<
" - element #" << matches[mi].first
10306 <<
" is matched by matcher #" << matches[mi].second;
10315 for (
size_t ilhs = 0; ilhs < LhsSize(); ++ilhs) {
10316 for (
size_t irhs = 0; irhs < RhsSize(); ++irhs) {
10317 char& b = matched_[SpaceIndex(ilhs, irhs)];
10329 for (
size_t ilhs = 0; ilhs < LhsSize(); ++ilhs) {
10330 for (
size_t irhs = 0; irhs < RhsSize(); ++irhs) {
10331 char& b = matched_[SpaceIndex(ilhs, irhs)];
10332 b =
static_cast<char>(rand() & 1);
10338 ::std::stringstream ss;
10339 const char *sep =
"";
10340 for (
size_t i = 0; i < LhsSize(); ++i) {
10342 for (
size_t j = 0; j < RhsSize(); ++j) {
10343 ss << HasEdge(i, j);
10351 ::std::ostream* os)
const {
10352 if (matcher_describers_.empty()) {
10356 if (matcher_describers_.size() == 1) {
10357 *os <<
"has " << Elements(1) <<
" and that element ";
10358 matcher_describers_[0]->DescribeTo(os);
10361 *os <<
"has " << Elements(matcher_describers_.size())
10362 <<
" and there exists some permutation of elements such that:\n";
10363 const char* sep =
"";
10364 for (
size_t i = 0; i != matcher_describers_.size(); ++i) {
10365 *os << sep <<
" - element #" << i <<
" ";
10366 matcher_describers_[i]->DescribeTo(os);
10372 ::std::ostream* os)
const {
10373 if (matcher_describers_.empty()) {
10374 *os <<
"isn't empty";
10377 if (matcher_describers_.size() == 1) {
10378 *os <<
"doesn't have " << Elements(1)
10379 <<
", or has " << Elements(1) <<
" that ";
10380 matcher_describers_[0]->DescribeNegationTo(os);
10383 *os <<
"doesn't have " << Elements(matcher_describers_.size())
10384 <<
", or there exists no permutation of elements such that:\n";
10385 const char* sep =
"";
10386 for (
size_t i = 0; i != matcher_describers_.size(); ++i) {
10387 *os << sep <<
" - element #" << i <<
" ";
10388 matcher_describers_[i]->DescribeTo(os);
10400 const ::std::vector<string>& element_printouts,
10403 bool result =
true;
10404 ::std::vector<char> element_matched(matrix.
LhsSize(), 0);
10405 ::std::vector<char> matcher_matched(matrix.
RhsSize(), 0);
10407 for (
size_t ilhs = 0; ilhs < matrix.
LhsSize(); ilhs++) {
10408 for (
size_t irhs = 0; irhs < matrix.
RhsSize(); irhs++) {
10409 char matched = matrix.
HasEdge(ilhs, irhs);
10410 element_matched[ilhs] |= matched;
10411 matcher_matched[irhs] |= matched;
10417 "where the following matchers don't match any elements:\n";
10418 for (
size_t mi = 0; mi < matcher_matched.size(); ++mi) {
10419 if (matcher_matched[mi])
10423 *listener << sep <<
"matcher #" << mi <<
": ";
10424 matcher_describers_[mi]->DescribeTo(listener->
stream());
10432 "where the following elements don't match any matchers:\n";
10433 const char* outer_sep =
"";
10435 outer_sep =
"\nand ";
10437 for (
size_t ei = 0; ei < element_matched.size(); ++ei) {
10438 if (element_matched[ei])
10442 *listener << outer_sep << sep <<
"element #" << ei <<
": " 10443 << element_printouts[ei];
10491 #include <stdlib.h> 10492 #include <iostream> 10497 #if GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC 10498 # include <unistd.h> 10502 namespace internal {
10510 const char* file,
int line,
10511 const string& message) {
10512 ::std::ostringstream
s;
10513 s << file <<
":" << line <<
": " << message << ::std::endl;
10514 Log(severity, s.str(), 0);
10520 const string& a_source_text)
10523 source_text_(a_source_text),
10524 cardinality_specified_(false),
10528 extra_matcher_specified_(false),
10529 repeated_action_specified_(false),
10530 retires_on_saturation_(false),
10531 last_clause_(kNone),
10532 action_count_checked_(false) {}
10567 g_gmock_mutex.AssertHeld();
10570 if (!(it->expectation_base()->IsSatisfied()) ||
10571 !(it->expectation_base()->AllPrerequisitesAreSatisfied()))
10580 g_gmock_mutex.AssertHeld();
10583 if (it->expectation_base()->IsSatisfied()) {
10586 if (it->expectation_base()->call_count_ == 0) {
10587 it->expectation_base()->FindUnsatisfiedPrerequisites(result);
10602 g_gmock_mutex.AssertHeld();
10605 *os <<
" Expected: to be ";
10607 *os <<
"\n Actual: ";
10625 bool should_check =
false;
10630 should_check =
true;
10634 if (should_check) {
10647 if (action_count > upper_bound ||
10650 }
else if (0 < action_count && action_count < lower_bound &&
10657 ::std::stringstream ss;
10659 ss <<
"Too " << (too_many ?
"many" :
"few")
10660 <<
" actions specified in " <<
source_text() <<
"...\n" 10661 <<
"Expected to be ";
10663 ss <<
", but has " << (too_many ?
"" :
"only ")
10664 << action_count <<
" WillOnce()" 10665 << (action_count == 1 ?
"" :
"s");
10667 ss <<
" and a WillRepeatedly()";
10678 ".Times() cannot appear " 10679 "more than once in an EXPECT_CALL().");
10682 ".Times() cannot appear after " 10683 ".InSequence(), .WillOnce(), .WillRepeatedly(), " 10684 "or .RetiresOnSaturation().");
10698 switch (reaction) {
10706 Expect(
false, NULL, -1, msg);
10711 : mock_obj_(NULL),
name_(
"") {}
10725 Mock::Register(mock_obj,
this);
10745 const void* mock_obj;
10751 "MockObject() must not be called before RegisterOwner() or " 10752 "SetOwnerAndName() has been called.");
10768 "Name() must not be called before SetOwnerAndName() has " 10790 Mock::GetReactionOnUninterestingCalls(
MockObject());
10795 const bool need_to_report_uninteresting_call =
10806 if (!need_to_report_uninteresting_call) {
10812 ::std::stringstream ss;
10820 if (result != NULL)
10827 bool is_excessive =
false;
10828 ::std::stringstream ss;
10829 ::std::stringstream why;
10830 ::std::stringstream loc;
10831 const void* untyped_action = NULL;
10837 untyped_args, &untyped_action, &is_excessive,
10839 const bool found = untyped_expectation != NULL;
10844 const bool need_to_report_call =
10846 if (!need_to_report_call) {
10849 untyped_action == NULL ?
10854 ss <<
" Function call: " <<
Name();
10859 if (found && !is_excessive) {
10864 untyped_action == NULL ?
10867 if (result != NULL)
10869 ss <<
"\n" << why.str();
10873 Expect(
false, NULL, -1, ss.str());
10874 }
else if (is_excessive) {
10877 untyped_expectation->
line(), ss.str());
10881 Log(
kInfo, loc.str() + ss.str(), 2);
10890 for (UntypedExpectations::const_iterator it =
10893 if (it->get() == exp) {
10898 Assert(
false, __FILE__, __LINE__,
"Cannot find expectation.");
10909 g_gmock_mutex.AssertHeld();
10910 bool expectations_met =
true;
10911 for (UntypedExpectations::const_iterator it =
10919 expectations_met =
false;
10920 }
else if (!untyped_expectation->
IsSatisfied()) {
10921 expectations_met =
false;
10922 ::std::stringstream ss;
10923 ss <<
"Actual function call count doesn't match " 10924 << untyped_expectation->
source_text() <<
"...\n";
10931 untyped_expectation->
line(), ss.str());
10945 g_gmock_mutex.Unlock();
10946 expectations_to_delete.clear();
10947 g_gmock_mutex.Lock();
10949 return expectations_met;
10958 typedef std::set<internal::UntypedFunctionMockerBase*> FunctionMockers;
10963 struct MockObjectState {
10981 class MockObjectRegistry {
10984 typedef std::map<const void*, MockObjectState> StateMap;
10990 ~MockObjectRegistry() {
10997 int leaked_count = 0;
10998 for (StateMap::const_iterator it =
states_.begin(); it !=
states_.end();
11000 if (it->second.leakable)
11006 const MockObjectState& state = it->second;
11008 state.first_used_line);
11009 std::cout <<
" ERROR: this mock object";
11010 if (state.first_used_test !=
"") {
11011 std::cout <<
" (used in test " << state.first_used_test_case <<
"." 11012 << state.first_used_test <<
")";
11014 std::cout <<
" should be deleted but never is. Its address is @" 11015 << it->first <<
".";
11018 if (leaked_count > 0) {
11019 std::cout <<
"\nERROR: " << leaked_count
11020 <<
" leaked mock " << (leaked_count == 1 ?
"object" :
"objects")
11021 <<
" found at program exit.\n";
11023 ::std::cerr.flush();
11032 StateMap& states() {
return states_; }
11039 MockObjectRegistry g_mock_object_registry;
11043 std::map<const void*, internal::CallReaction> g_uninteresting_call_reaction;
11047 void SetReactionOnUninterestingCalls(
const void* mock_obj,
11051 g_uninteresting_call_reaction[mock_obj] = reaction;
11058 void Mock::AllowUninterestingCalls(
const void* mock_obj)
11065 void Mock::WarnUninterestingCalls(
const void* mock_obj)
11072 void Mock::FailUninterestingCalls(
const void* mock_obj)
11079 void Mock::UnregisterCallReaction(
const void* mock_obj)
11082 g_uninteresting_call_reaction.erase(mock_obj);
11088 const void* mock_obj)
11091 return (g_uninteresting_call_reaction.count(mock_obj) == 0) ?
11097 void Mock::AllowLeak(
const void* mock_obj)
11100 g_mock_object_registry.states()[mock_obj].leakable =
true;
11106 bool Mock::VerifyAndClearExpectations(
void* mock_obj)
11115 bool Mock::VerifyAndClear(
void* mock_obj)
11125 bool Mock::VerifyAndClearExpectationsLocked(
void* mock_obj)
11127 internal::g_gmock_mutex.AssertHeld();
11128 if (g_mock_object_registry.states().count(mock_obj) == 0) {
11135 bool expectations_met =
true;
11136 FunctionMockers& mockers =
11137 g_mock_object_registry.states()[mock_obj].function_mockers;
11138 for (FunctionMockers::const_iterator it = mockers.begin();
11139 it != mockers.end(); ++it) {
11140 if (!(*it)->VerifyAndClearExpectationsLocked()) {
11141 expectations_met =
false;
11147 return expectations_met;
11151 void Mock::Register(
const void* mock_obj,
11152 internal::UntypedFunctionMockerBase* mocker)
11155 g_mock_object_registry.states()[mock_obj].function_mockers.insert(mocker);
11161 void Mock::RegisterUseByOnCallOrExpectCall(
const void* mock_obj,
11162 const char* file,
int line)
11165 MockObjectState& state = g_mock_object_registry.states()[mock_obj];
11166 if (state.first_used_file == NULL) {
11167 state.first_used_file = file;
11168 state.first_used_line = line;
11169 const TestInfo*
const test_info =
11171 if (test_info != NULL) {
11175 state.first_used_test_case = test_info->test_case_name();
11176 state.first_used_test = test_info->name();
11185 void Mock::UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
11187 internal::g_gmock_mutex.AssertHeld();
11188 for (MockObjectRegistry::StateMap::iterator it =
11189 g_mock_object_registry.states().begin();
11190 it != g_mock_object_registry.states().end(); ++it) {
11191 FunctionMockers& mockers = it->second.function_mockers;
11192 if (mockers.erase(mocker) > 0) {
11194 if (mockers.empty()) {
11195 g_mock_object_registry.states().erase(it);
11203 void Mock::ClearDefaultActionsLocked(
void* mock_obj)
11205 internal::g_gmock_mutex.AssertHeld();
11207 if (g_mock_object_registry.states().count(mock_obj) == 0) {
11214 FunctionMockers& mockers =
11215 g_mock_object_registry.states()[mock_obj].function_mockers;
11216 for (FunctionMockers::const_iterator it = mockers.begin();
11217 it != mockers.end(); ++it) {
11218 (*it)->ClearDefaultActionsLocked();
11229 : expectation_base_(an_expectation_base) {}
11235 if (*last_expectation_ != expectation) {
11236 if (last_expectation_->expectation_base() != NULL) {
11238 += *last_expectation_;
11240 *last_expectation_ = expectation;
11248 sequence_created_ =
true;
11250 sequence_created_ =
false;
11257 if (sequence_created_) {
11302 "true iff Google Mock should report leaked mock objects " 11306 "Controls how verbose Google Mock's output is." 11308 " info - prints all messages.\n" 11309 " warning - prints warnings and errors.\n" 11310 " error - prints errors only.");
11312 namespace internal {
11321 bool def_optional) {
11323 if (str == NULL || flag == NULL)
return NULL;
11327 const size_t flag_len = flag_str.length();
11328 if (strncmp(str, flag_str.c_str(), flag_len) != 0)
return NULL;
11331 const char* flag_end = str + flag_len;
11334 if (def_optional && (flag_end[0] ==
'\0')) {
11341 if (flag_end[0] !=
'=')
return NULL;
11344 return flag_end + 1;
11358 if (value_str == NULL)
return false;
11361 *value = !(*value_str ==
'0' || *value_str ==
'f' || *value_str ==
'F');
11376 if (value_str == NULL)
return false;
11379 *value = value_str;
11387 template <
typename CharType>
11392 if (*argc <= 0)
return;
11394 for (
int i = 1; i != *argc; i++) {
11396 const char*
const arg = arg_string.c_str();
11406 for (
int j = i; j != *argc; j++) {
11407 argv[j] = argv[j + 1];
const char kDeathTestUseFork[]
void ExpectSpecProperty(bool property, const string &failure_message) const
GTEST_API_ bool g_help_flag
void PrintCharAndCodeTo(Char c, ostream *os)
static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream *os)
int failed_test_count() const
void SetDefaultResultPrinter(TestEventListener *listener)
TestPartResultReporterInterface * GetTestPartResultReporterForCurrentThread()
UnitTestImpl * GetUnitTestImpl()
internal::SetUpTestCaseFunc SetUpTestCaseFunc
const char * type_param() const
const void * MockObject() const GTEST_LOCK_EXCLUDED_(g_gmock_mutex)
GTEST_API_ ThreadLocal< Sequence * > g_gmock_implicit_sequence
std::vector< Environment * > & environments()
~ScopedPrematureExitFile()
bool IsTrue(bool condition)
void RecordProperty(const std::string &xml_element, const TestProperty &test_property)
const char * original_working_dir() const
virtual void MaybeDescribeExtraMatcherTo(::std::ostream *os)=0
HasNewFatalFailureHelper()
static const std::vector< testing::TestPartResult > & test_part_results(const TestResult &test_result)
bool fatally_failed() const
void ReportFailureInUnknownLocation(TestPartResult::Type result_type, const std::string &message)
int disabled_test_count() const
ScopedPrematureExitFile(const char *premature_exit_filepath)
int GetRandomSeedFromFlag(Int32 random_seed_flag)
Result HandleExceptionsInMethodIfSupported(T *object, Result(T::*method)(), const char *location)
std::string GetCapturedStdout()
GTEST_DEFINE_int32_(random_seed, internal::Int32FromGTestEnv("random_seed", 0),"Random number seed to use when shuffling test orders. Must be in range ""[1, 99999], or 0 to use a seed based on the current time.")
std::string GetCapturedStderr()
static bool HasFatalFailure()
int successful_test_count() const
void DescribeNegationToImpl(::std::ostream *os) const
int death_test_count() const
int reportable_disabled_test_count() const
static std::string ReadEntireFile(FILE *file)
TimeInMillis elapsed_time() const
std::vector< TestCase * > test_cases_
static bool HasGoogleTestFlagPrefix(const char *str)
const internal::linked_ptr< internal::ExpectationBase > & expectation_base() const
#define GTEST_DISALLOW_COPY_AND_ASSIGN_(type)
static int SumOverTestCaseList(const std::vector< TestCase * > &case_list, int(TestCase::*method)() const)
char * StrDup(const char *src)
void(* TearDownTestCaseFunc)()
bool repeated_action_specified_
const char * summary() const
const TestResult * ad_hoc_test_result() const
std::string death_test_style_
void RetireAllPreRequisites() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex)
TestPropertyKeyIs(const std::string &key)
GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms)
AssertionResult CmpHelperSTREQ(const char *expected_expression, const char *actual_expression, const wchar_t *expected, const wchar_t *actual)
static const char kDisableTestFilter[]
internal::Int32 random_seed_
E GetElementOr(const std::vector< E > &v, int i, E default_value)
GTEST_API_ string ConvertIdentifierNameToWords(const char *id_name)
int failed_test_count() const
GTEST_API_ Cardinality AtLeast(int n)
AssertionResult AssertionFailure()
const char kAlsoRunDisabledTestsFlag[]
UInt32 ChopLowBits(UInt32 *bits, int n)
TimeInMillis elapsed_time_
virtual void OnEnvironmentsTearDownStart(const UnitTest &unit_test)=0
virtual void ReportTestPartResult(const TestPartResult &result)
const TestInfo * GetTestInfo(int i) const
static FilePath ConcatPaths(const FilePath &directory, const FilePath &relative_path)
static std::string ExtractSummary(const char *message)
static const char * TestPartResultTypeToString(TestPartResult::Type type)
static std::string EscapeXmlAttribute(const std::string &str)
static std::string EscapeXml(const std::string &str, bool is_attribute)
GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestLog)
const char kListTestsFlag[]
#define GTEST_HAS_GETTIMEOFDAY_
void PrintFullTestCommentIfPresent(const TestInfo &test_info)
bool death_test_use_fork_
GTEST_API_ Cardinality AtMost(int n)
void set_current_test_info(TestInfo *a_current_test_info)
TestPartResultReporterInterface * GetGlobalTestPartResultReporter()
IntFormatSpec< int, TypeSpec<'x'> > hex(int value)
::std::vector< size_t > right_
void RegisterParameterizedTests()
internal::EqMatcher< T > Eq(T x)
static void DescribeActualCallCountTo(int actual_call_count,::std::ostream *os)
::std::string PrintToString(const T &value)
static const char kDefaultDeathTestStyle[]
::std::ostream * stream()
const char kStreamResultToFlag[]
TypeWithSize< 4 >::Int Int32
const char kErrorVerbosity[]
static bool IsNormalizableWhitespace(char c)
FILE * FOpen(const char *path, const char *mode)
#define EXPECT_PRED_FORMAT3(pred_format, v1, v2, v3)
TestCase(const char *name, const char *a_type_param, Test::SetUpTestCaseFunc set_up_tc, Test::TearDownTestCaseFunc tear_down_tc)
const char * message() const
int GetNextRandomSeed(int seed)
static void ClearTestResult(TestInfo *test_info)
virtual Test * CreateTest()=0
bool IsSatisfied() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex)
internal::Mutex test_properites_mutex_
bool BoolFromGTestEnv(const char *flag, bool default_value)
GTEST_API_ void InitGoogleMock(int *argc, char **argv)
const std::vector< TestPartResult > & test_part_results() const
void DescribeLocationTo(::std::ostream *os) const
std::vector< internal::linked_ptr< ExpectationBase > > UntypedExpectations
virtual ~ExpectationBase()
GTEST_API_ int g_init_gtest_count
virtual void PrintAsActionResult(::std::ostream *os) const =0
GTEST_API_::std::string FormatFileLocation(const char *file, int line)
static CapturedStream * g_captured_stdout
virtual void ReportTestPartResult(const TestPartResult &result)
GTEST_API_ FailureReporterInterface * GetFailureReporter()
GTEST_API_ bool ShouldUseColor(bool stdout_is_tty)
UntypedExpectations untyped_expectations_
bool has_new_fatal_failure_
static void PrintXmlTestCase(::std::ostream *stream, const TestCase &test_case)
ScopedFakeTestPartResultReporter(TestPartResultArray *result)
AssertionResult CmpHelperSTRCASENE(const char *s1_expression, const char *s2_expression, const char *s1, const char *s2)
bool FileOrDirectoryExists() const
TypeWithSize< 4 >::UInt UInt32
TestEventListener * Release(TestEventListener *listener)
std::vector< TestEventListener * > listeners_
virtual ~HasNewFatalFailureHelper()
GTEST_API_ bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id)
GTEST_API_ bool FindPairing(const MatchMatrix &matrix, MatchResultListener *listener)
void ListTestsMatchingFilter()
void DescribeTo(::std::ostream *os) const
void FindUnsatisfiedPrerequisites(ExpectationSet *result) const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex)
static const char * GetDefaultFilter()
std::string format(CStringRef format_str, ArgList args)
bool operator()(const TestCase *test_case) const
static bool TestPartNonfatallyFailed(const TestPartResult &result)
TestEventListener * repeater()
TimeInMillis elapsed_time_
TimeInMillis start_timestamp() const
bool action_count_checked_
TestPartResult::Type const type
std::string internal_run_death_test_
bool ParseInt32(const Message &src_text, const char *str, Int32 *value)
const UntypedActionResultHolderBase * UntypedInvokeWith(const void *untyped_args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex)
void(* SetUpTestCaseFunc)()
void SuppressEventForwarding()
std::vector< TestInfo * > & test_info_list()
virtual void OnTestIterationStart(const UnitTest &unit_test, int iteration)=0
PrettyUnitTestResultPrinter()
internal::Mutex global_test_part_result_reporter_mutex_
void SetGlobalTestPartResultReporter(TestPartResultReporterInterface *reporter)
bool connect(ros_opcua_srvs::Connect::Request &req, ros_opcua_srvs::Connect::Response &res)
void RecordProperty(const std::string &key, const std::string &value)
std::string StringStreamToString(::std::stringstream *ss)
static void PrintXmlUnitTest(::std::ostream *stream, const UnitTest &unit_test)
std::vector< TestInfo * > test_info_list_
virtual UntypedActionResultHolderBase * UntypedPerformAction(const void *untyped_action, const void *untyped_args) const =0
bool HasEdge(size_t ilhs, size_t irhs) const
void ClearAdHocTestResult()
void ColoredPrintf(GTestColor color, const char *fmt,...)
int test_to_run_count() const
Result HandleSehExceptionsInMethodIfSupported(T *object, Result(T::*method)(), const char *location)
static const char *const kReservedTestSuiteAttributes[]
GTEST_DEFINE_bool_(also_run_disabled_tests, internal::BoolFromGTestEnv("also_run_disabled_tests", false),"Run disabled tests too, in addition to the tests normally being run.")
ExpectationBase(const char *file, int line, const string &source_text)
virtual void OnEnvironmentsSetUpStart(const UnitTest &unit_test)=0
virtual void OnTestCaseEnd(const TestCase &test_case)=0
const std::string output_file_
bool is_retired() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex)
void set_elapsed_time(TimeInMillis elapsed)
int Stat(const char *path, StatStruct *buf)
virtual void OnEnvironmentsSetUpEnd(const UnitTest &)
AssertionResult DoubleNearPredFormat(const char *expr1, const char *expr2, const char *abs_error_expr, double val1, double val2, double abs_error)
static std::string GetAbsolutePathToOutputFile()
bool IsInterested() const
virtual void UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_)
Message & operator<<(const T &val)
bool SkipPrefix(const char *prefix, const char **pstr)
GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms)
virtual void OnTestStart(const TestInfo &test_info)=0
void set_current_test_case(TestCase *a_current_test_case)
static bool ValidateTestProperty(const std::string &xml_element, const TestProperty &test_property)
void operator=(const Message &message) const
int reportable_disabled_test_count() const
bool CreateDirectoriesRecursively() const
const char *const premature_exit_filepath_
const TestPartResult & GetTestPartResult(int i) const
const TestProperty & GetTestProperty(int i) const
bool IsUtf16SurrogatePair(wchar_t first, wchar_t second)
internal::TearDownTestCaseFunc TearDownTestCaseFunc
internal::Int32 stack_trace_depth_
void Append(TestEventListener *listener)
const char * first_used_file
static void ClearTestPartResults(TestResult *test_result)
GTEST_API_ bool ShouldShard(const char *total_shards_str, const char *shard_index_str, bool in_subprocess_for_death_test)
static void SetUpEnvironment(Environment *env)
internal::ParameterizedTestCaseRegistry & parameterized_test_registry()
void PrintStringTo(const ::std::string &s, ostream *os)
void UntypedTimes(const Cardinality &a_cardinality)
int test_case_to_run_count() const
GTEST_API_ std::string CodePointToUtf8(UInt32 code_point)
bool catch_exceptions() const
const char kBreakOnFailureFlag[]
static const char kTestTotalShards[]
TestInfo * MakeAndRegisterTestInfo(const char *test_case_name, const char *name, const char *type_param, const char *value_param, TypeId fixture_class_id, SetUpTestCaseFunc set_up_tc, TearDownTestCaseFunc tear_down_tc, TestFactoryBase *factory)
static bool PatternMatchesString(const char *pattern, const char *str)
#define EXPECT_TRUE(condition)
#define GTEST_REVERSE_REPEATER_METHOD_(Name, Type)
std::string FormatForComparisonFailureMessage(const T1 &value, const T2 &)
const internal::scoped_ptr< ::std::stringstream > ss_
bool ParseBoolFlag(const char *str, const char *flag, bool *value)
MaxBipartiteMatchState(const MatchMatrix &graph)
internal::FilePath original_working_dir_
static std::string FormatByte(unsigned char value)
int reportable_test_count() const
static bool PartialMatch(const ::std::string &str, const RE &re)
spdlog::log_clock::time_point now()
int disabled_test_count() const
int total_test_count() const
AssertionResult HasOneFailure(const char *, const char *, const char *, const TestPartResultArray &results, TestPartResult::Type type, const string &substr)
TestCase * current_test_case_
const UInt32 kMaxCodePoint3
std::ostream & operator<<(std::ostream &os, const TestPartResult &result)
static std::vector< std::string > GetReservedAttributesForElement(const std::string &xml_element)
void ReportInvalidTestCaseType(const char *test_case_name, const char *file, int line)
OStream< ChannelType > & flush(OStream< ChannelType > &os)
virtual void OnTestProgramStart(const UnitTest &)
void PushGTestTrace(const internal::TraceInfo &trace) GTEST_LOCK_EXCLUDED_(mutex_)
void CheckActionCountIfNotDone() const GTEST_LOCK_EXCLUDED_(mutex_)
static std::string FormatHexInt(int value)
static std::string FlagToEnvVar(const char *flag)
GMOCK_DEFINE_bool_(catch_leaked_mocks, true,"true iff Google Mock should report leaked mock objects ""as failures.")
GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter)
GTEST_API_ string JoinAsTuple(const Strings &fields)
const char kRandomSeedFlag[]
TimeInMillis start_timestamp() const
const char kInfoVerbosity[]
int total_test_count() const
std::string StreamableToString(const T &streamable)
::std::vector< ElementMatcherPair > ElementMatcherPairs
internal::ThreadLocal< TestPartResultReporterInterface * > per_thread_test_part_result_reporter_
AssertionResult(const AssertionResult &other)
const char kShuffleFlag[]
static const char kTestShardStatusFile[]
GTEST_DISALLOW_COPY_AND_ASSIGN_(HasNewFatalFailureHelper)
bool HasNonfatalFailure() const
internal::TimeInMillis TimeInMillis
static const size_t kUnused
int reportable_test_count() const
bool write(ros_opcua_srvs::Write::Request &req, ros_opcua_srvs::Write::Response &res)
const char kCurrentDirectoryString[]
static CharFormat PrintAsCharLiteralTo(Char c, ostream *os)
#define GTEST_FLAG_PREFIX_DASH_
Expectation::Set::const_iterator const_iterator
std::string GetCapturedString()
const char * StringFromGTestEnv(const char *flag, const char *default_value)
int Write(int fd, const void *buf, unsigned int count)
int call_count() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex)
void PostFlagParsingInit()
const internal::TypeId fixture_class_id_
void PrintBytesInObjectTo(const unsigned char *obj_bytes, size_t count, ostream *os)
void AddTestInfo(TestInfo *test_info)
const char * source_text() const
virtual string CurrentStackTrace(int max_depth, int skip_count) GTEST_LOCK_EXCLUDED_(mutex_)
::std::ostream & GetStream()
int ConservativeUpperBound() const
AssertionResult CmpHelperEQ(const char *expected_expression, const char *actual_expression, BiggestInt expected, BiggestInt actual)
void ReportUninterestingCall(CallReaction reaction, const string &msg)
bool AllPrerequisitesAreSatisfied() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex)
void set_os_stack_trace_getter(OsStackTraceGetterInterface *getter)
std::vector< Environment * > environments_
virtual void ClearDefaultActionsLocked() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex)=0
const internal::scoped_ptr< const ::std::string > type_param_
DefaultGlobalTestPartResultReporter(UnitTestImpl *unit_test)
const GTestLogSeverity severity_
void Set(const FilePath &rhs)
TestResult ad_hoc_test_result_
static std::string TestPropertiesAsXmlAttributes(const TestResult &result)
GTEST_DECLARE_bool_(death_test_use_fork)
TimeInMillis start_timestamp_
static std::string FormatCountableNoun(int count, const char *singular_form, const char *plural_form)
GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex)
bool is_reportable() const
bool VerifyAllElementsAndMatchersAreMatched(const ::std::vector< string > &element_printouts, const MatchMatrix &matrix, MatchResultListener *listener) const
const char kPathSeparatorString[]
const char * name() const
int test_case_to_run_count() const
const std::vector< TraceInfo > & gtest_trace_stack() const
virtual void OnTestIterationEnd(const UnitTest &unit_test, int iteration)=0
int test_to_run_count() const
GTEST_DISALLOW_COPY_AND_ASSIGN_(TestCase)
virtual void OnTestProgramEnd(const UnitTest &unit_test)=0
TestCase * GetMutableTestCase(int i)
std::vector< int > test_indices_
OsStackTraceGetterInterface * os_stack_trace_getter()
virtual void UntypedDescribeUninterestingCall(const void *untyped_args,::std::ostream *os) const GTEST_LOCK_EXCLUDED_(g_gmock_mutex)=0
void Expect(bool condition, const char *file, int line, const string &msg)
static bool ParseGoogleMockBoolFlag(const char *str, const char *flag, bool *value)
const char kDeathTestStyleFlag[]
const char * message() const
AssertionResult AssertionSuccess()
static CapturedStream * g_captured_stderr
const char kWarningVerbosity[]
void set_forwarding_enabled(bool enable)
TestPartResultReporterInterface * global_test_part_result_repoter_
std::tm localtime(const std::time_t &time_tt)
TestResult ad_hoc_test_result_
void DescribeToImpl(::std::ostream *os) const
const UInt32 kMaxCodePoint1
static void LogElementMatcherPairVec(const ElementMatcherPairs &pairs,::std::ostream *stream)
const MatchMatrix * graph_
const char * Name() const GTEST_LOCK_EXCLUDED_(g_gmock_mutex)
void SetOwnerAndName(const void *mock_obj, const char *name) GTEST_LOCK_EXCLUDED_(g_gmock_mutex)
AssertionResult CmpHelperSTRNE(const char *s1_expression, const char *s2_expression, const wchar_t *s1, const wchar_t *s2)
def Iter(n, format, sep='')
std::string const message
static std::string GetOutputFormat()
internal::ThreadLocal< std::vector< TraceInfo > > gtest_trace_stack_
std::vector< TestProperty > test_properties_
TestEventListeners & listeners()
bool parameterized_tests_registered_
void SetDefaultXmlGenerator(TestEventListener *listener)
bool forwarding_enabled() const
#define GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks)
const int kMaxStackTraceDepth
static bool IsValidXmlCharacter(char c)
ElementMatcherPairs Compute()
virtual void ReportTestPartResult(const TestPartResult &result)
void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc, Test::TearDownTestCaseFunc tear_down_tc, TestInfo *test_info)
ExpectationSet immediate_prerequisites_
static const char kValueParamLabel[]
static const char kDeathTestCaseFilter[]
UInt32 Generate(UInt32 range)
AssertionResult AssertionFailure(const Message &message)
static bool CStringEquals(const char *lhs, const char *rhs)
#define GTEST_IMPL_CMP_HELPER_(op_name, op)
bool TryAugment(size_t ilhs,::std::vector< char > *seen)
int reportable_test_count() const
void RecordProperty(const TestProperty &test_property)
FilePath RemoveFileName() const
void SetTestPartResultReporterForCurrentThread(TestPartResultReporterInterface *reporter)
TestInfo(const std::string &test_case_name, const std::string &name, const char *a_type_param, const char *a_value_param, internal::TypeId fixture_class_id, internal::TestFactoryBase *factory)
static const char *const kReservedTestSuitesAttributes[]
void AddExpectation(const Expectation &expectation) const
int successful_test_count() const
std::string GetCurrentOsStackTraceExceptTop(UnitTest *, int skip_count)
GTEST_API_ void ParseGoogleTestFlagsOnly(int *argc, wchar_t **argv)
int successful_test_case_count() const
GTEST_API_ const TypeId kTestTypeIdInGoogleTest
void InitGoogleMockImpl(int *argc, CharType **argv)
int Read(int fd, void *buf, unsigned int count)
static bool GTestIsInitialized()
const std::string & string() const
GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity, const char *file, int line, const string &message)
bool CaseInsensitiveCStringEquals(const char *lhs, const char *rhs)
#define GTEST_PROJECT_URL_
static void RecordProperty(TestResult *test_result, const std::string &xml_element, const TestProperty &property)
const TestCase * GetTestCase(int i) const
TestInfo * GetMutableTestInfo(int i)
const char * file_name() const
static void PrintColorEncoded(const char *str)
TestEventListener * default_result_printer_
GTEST_API_ void Log(LogSeverity severity, const string &message, int stack_frames_to_skip)
::std::pair< size_t, size_t > ElementMatcherPair
AssertionResult FloatingPointLE(const char *expr1, const char *expr2, RawType val1, RawType val2)
void AddTestPartResult(const TestPartResult &test_part_result)
class GTEST_API_ testing::InSequence GTEST_ATTRIBUTE_UNUSED_
const TestCase * current_test_case() const
#define GTEST_DISALLOW_ASSIGN_(type)
void SpecifyCardinality(const Cardinality &cardinality)
internal::ParameterizedTestCaseRegistry & parameterized_test_registry() GTEST_LOCK_EXCLUDED_(mutex_)
static std::string FormatTestCaseCount(int test_case_count)
GMOCK_DEFINE_string_(verbose, internal::kWarningVerbosity,"Controls how verbose Google Mock's output is."" Valid values:\n"" info - prints all messages.\n"" warning - prints warnings and errors.\n"" error - prints errors only.")
int StrCaseCmp(const char *s1, const char *s2)
TestResult * current_test_result()
const InterceptMode intercept_mode_
GTEST_API_ string FormatMatcherDescription(bool negation, const char *matcher_name, const Strings ¶m_values)
bool HasFatalFailure() const
UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first, wchar_t second)
void RegisterOwner(const void *mock_obj) GTEST_LOCK_EXCLUDED_(g_gmock_mutex)
void ClearNonAdHocTestResult()
static void OutputXmlAttribute(std::ostream *stream, const std::string &element_name, const std::string &name, const std::string &value)
FilePath RemoveTrailingPathSeparator() const
ScopedTrace(const char *file, int line, const Message &message)
virtual ~OsStackTraceGetterInterface()
bool ParseStringFlag(const char *str, const char *flag, std::string *value)
const char * value_param() const
UnitTestImpl *const unit_test_
std::string GetString() const
#define GTEST_HAS_PARAM_TEST
int failed_test_count() const
static const char kUniversalFilter[]
bool IsDir(const StatStruct &st)
AssertionResult IsSubstring(const char *needle_expr, const char *haystack_expr, const char *needle, const char *haystack)
GTEST_API_ FilePath GetCurrentExecutableName()
const char * c_str() const
bool IsPrintableAscii(wchar_t c)
static const char * ParseGoogleMockFlagValue(const char *str, const char *flag, bool def_optional)
int test_to_run_count() const
GTEST_API_ TimeInMillis GetTimeInMillis()
TestEventListener * default_xml_generator_
AssertionResult CmpHelperSTRCASEEQ(const char *expected_expression, const char *actual_expression, const char *expected, const char *actual)
int total_test_case_count() const
TestEventListeners listeners_
int total_test_case_count() const
static void PrintOnOneLine(const char *str, int max_length)
static std::string FormatTestCount(int test_count)
virtual void ReportTestPartResult(const TestPartResult &result)
const TestInfo * current_test_info() const
internal::TestFactoryBase *const factory_
static std::string RemoveInvalidXmlCharacters(const std::string &str)
void ShuffleTests(internal::Random *random)
void CaptureStream(int fd, const char *stream_name, CapturedStream **stream)
const char * test_case_name() const
Expectation GetHandleOf(ExpectationBase *exp)
static bool TestPartFatallyFailed(const TestPartResult &result)
const TestCase * GetTestCase(int i) const
const TestPartResult & GetTestPartResult(int index) const
const TestInfo * current_test_info() const GTEST_LOCK_EXCLUDED_(mutex_)
const TestPartResult::Type type_
static const char *const kReservedTestCaseAttributes[]
static std::string EscapeXmlText(const char *str)
virtual void OnEnvironmentsTearDownEnd(const UnitTest &unit_test)=0
static FilePath GenerateUniqueFileName(const FilePath &directory, const FilePath &base_name, const char *extension)
int failed_test_case_count() const
GTEST_API_ std::string WideStringToUtf8(const wchar_t *str, int num_chars)
GTEST_API_ Cardinality Between(int min, int max)
bool EventForwardingEnabled() const
const char * ParseFlagValue(const char *str, const char *flag, bool def_optional)
GTEST_API_::std::string FormatCompilerIndependentFileLocation(const char *file, int line)
void Retire() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex)
internal::scoped_ptr< ::std::string > message_
UnitTestImpl *const unit_test_
const TestResult & ad_hoc_test_result() const
const char kStackTraceMarker[]
static void PrintTestPartResult(const TestPartResult &test_part_result)
int test_property_count() const
FILE * FDOpen(int fd, const char *mode)
void ShuffleRange(internal::Random *random, int begin, int end, std::vector< E > *v)
GTEST_API_ bool LogIsVisible(LogSeverity severity)
bool IsSaturated() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex)
bool IsAbsolutePath() const
void PopGTestTrace() GTEST_LOCK_EXCLUDED_(mutex_)
std::string AppendUserMessage(const std::string >est_msg, const Message &user_msg)
static const char kDefaultOutputFile[]
GTEST_API_ Cardinality Exactly(int n)
::std::vector< size_t > left_
AssertHelperData *const data_
static size_t GetFileSize(FILE *file)
Environment * AddEnvironment(Environment *env)
const_iterator end() const
UntypedFunctionMockerBase()
TestCaseNameIs(const std::string &name)
static void StreamWideCharsToMessage(const wchar_t *wstr, size_t length, Message *msg)
static bool ShouldRunTestCase(const TestCase *test_case)
int reportable_disabled_test_count() const
std::vector< TestPartResult > test_part_results_
virtual void OnTestIterationEnd(const UnitTest &unit_test, int iteration)
int CountIf(const Container &c, Predicate predicate)
int disabled_test_count() const
internal::NamedArg< char > arg(StringRef name, const T &arg)
void AddTestPartResult(TestPartResult::Type result_type, const char *file_name, int line_number, const std::string &message, const std::string &os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_)
internal::UnitTestImpl * impl()
string DebugString() const
const char kStackTraceDepthFlag[]
const char * GetAnsiColorCode(GTestColor color)
virtual const ExpectationBase * UntypedFindMatchingExpectation(const void *untyped_args, const void **untyped_action, bool *is_excessive,::std::ostream *what,::std::ostream *why) GTEST_LOCK_EXCLUDED_(g_gmock_mutex)=0
const char kCatchExceptionsFlag[]
GTEST_API_ Cardinality AnyNumber()
OsStackTraceGetterInterface * os_stack_trace_getter_
const char kInternalRunDeathTestFlag[]
bool operator()(const TestProperty &test_property) const
const_iterator begin() const
static void ClearTestCaseResult(TestCase *test_case)
internal::TestEventRepeater * repeater_
void InitGoogleTestImpl(int *argc, CharType **argv)
int Run() GTEST_MUST_USE_RESULT_
void UniversalPrintArray(const char *begin, size_t len, ostream *os)
void ParseGoogleTestFlagsOnlyImpl(int *argc, CharType **argv)
int FilterTests(ReactionToSharding shard_tests)
void Assert(bool condition, const char *file, int line)
AssertionResult EqFailure(const char *expected_expression, const char *actual_expression, const std::string &expected_value, const std::string &actual_value, bool ignoring_case)
virtual void UntypedPrintArgs(const void *untyped_args,::std::ostream *os) const =0
TestEventListeners * listeners()
TestEventListener * Release(TestEventListener *listener)
DefaultPerThreadTestPartResultReporter default_per_thread_test_part_result_reporter_
const char * StrError(int errnum)
static std::string FormatWordList(const std::vector< std::string > &words)
GTEST_API_ void ParseGoogleTestFlagsOnly(int *argc, char **argv)
void ConfigureXmlOutput()
virtual void ReportTestPartResult(const TestPartResult &result)=0
GTEST_API_ ElementMatcherPairs FindMaxBipartiteMatching(const MatchMatrix &g)
static bool HasSameFixtureClass()
bool post_flag_parse_init_performed_
void Shuffle(internal::Random *random, std::vector< E > *v)
virtual void OnTestCaseStart(const TestCase &test_case)=0
std::string GetBoolAssertionFailureMessage(const AssertionResult &assertion_result, const char *expression_text, const char *actual_predicate_value, const char *expected_predicate_value)
int successful_test_count() const
int total_test_count() const
::std::string first_used_test
internal::Random * random()
static const char kTestShardIndex[]
void RunTearDownTestCase()
virtual void OnEnvironmentsTearDownEnd(const UnitTest &)
virtual void OnTestPartResult(const TestPartResult &test_part_result)=0
::std::vector< string > Strings
std::vector< TraceInfo > & gtest_trace_stack()
static bool TestCasePassed(const TestCase *test_case)
TimeInMillis elapsed_time_
virtual void OnEnvironmentsSetUpEnd(const UnitTest &unit_test)=0
#define GTEST_FLAG_PREFIX_
const TestPartResultArray *const results_
static const char kColorEncodedHelpMessage[]
virtual void UponLeavingGTest()=0
int total_part_count() const
AssertionResult operator!() const
const char * file() const
static const char *const kElidedFramesMarker
static void TearDownEnvironment(Environment *env)
void PrintWideStringTo(const ::std::wstring &s, ostream *os)
virtual void OnTestEnd(const TestInfo &test_info)=0
virtual void OnTestProgramStart(const UnitTest &unit_test)=0
void set_should_run(bool should)
AssertionResult DoubleLE(const char *expr1, const char *expr2, double val1, double val2)
const UInt32 kMaxCodePoint4
virtual void ReportFailure(FailureType type, const char *file, int line, const string &message)
bool VerifyAndClearExpectationsLocked() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex)
void InitGoogleTest(int *argc, char **argv)
int failed_test_case_count() const
const char * name() const
int successful_test_case_count() const
Int32 Int32FromGTestEnv(const char *flag, Int32 default_value)
TimeInMillis elapsed_time() const
FMT_API int fprintf(std::FILE *f, CStringRef format, ArgList args)
UntypedActions untyped_actions_
std::string g_executable_path
const TestResult * result() const
bool also_run_disabled_tests_
AssertionResult IsNotSubstring(const char *needle_expr, const char *haystack_expr, const char *needle, const char *haystack)
static UnitTest * GetInstance()
void Append(const TestPartResult &result)
void ClearTestPartResults()
static bool IsPathSeparator(char c)
bool cardinality_specified_
void set_catch_exceptions(bool value)
GTEST_DEFINE_string_(internal_run_death_test,"","Indicates the file, line number, temporal index of ""the single death test to run, and a file descriptor to ""which a success code may be sent, all separated by ""the '|' characters. This flag is specified if and only if the current ""process is a sub-process launched for running a thread-safe ""death test. FOR INTERNAL USE ONLY.")
const UInt32 kMaxCodePoint2
static void PrintTestName(const char *test_case, const char *test)
const internal::GTestFlagSaver *const gtest_flag_saver_
OsStackTraceGetterInterface()
const char * type_param() const
std::string GetCapturedStream(CapturedStream **captured_stream)
TypeWithSize< 8 >::Int TimeInMillis
static void OutputXmlTestInfo(::std::ostream *stream, const char *test_case_name, const TestInfo &test_info)
DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_
static bool TestCaseFailed(const TestCase *test_case)
void ForEach(const Container &c, Functor functor)
TestPartResultArray *const result_
FilePath RemoveDirectoryName() const
bool nonfatally_failed() const
static void RecordProperty(const std::string &key, const std::string &value)
const TestResult & ad_hoc_test_result() const
#define GTEST_CHECK_(condition)
const char * value() const
static bool FilterMatchesTest(const std::string &test_case_name, const std::string &test_name)
int last_death_test_case_
TestPartResultReporterInterface * original_reporter_
const char * GetEnv(const char *name)
GTEST_API_ Int32 Int32FromEnvOrDie(const char *env_var, Int32 default_val)
virtual void TestBody()=0
TimeInMillis elapsed_time() const
static std::string FormatIntWidth2(int value)
void WriteToShardStatusFileIfNeeded()
#define GTEST_FLAG_PREFIX_UPPER_
virtual UntypedActionResultHolderBase * UntypedPerformDefaultAction(const void *untyped_args, const string &call_description) const =0
TestPartResultReporterInterface * old_reporter_
const Cardinality & cardinality() const
void DescribeCallCountTo(::std::ostream *os) const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex)
std::string stream_result_to_
static std::string ShowWideCString(const wchar_t *wide_c_str)
bool IsOverSaturated() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex)
int ConservativeLowerBound() const
const char kUnknownFile[]
static const size_t kUnused
std::vector< int > test_case_indices_
#define GTEST_LOG_(severity)
static bool MatchesFilter(const std::string &name, const char *filter)
DefaultPerThreadTestPartResultReporter(UnitTestImpl *unit_test)
std::vector< std::string > ArrayAsVector(const char *const (&array)[kSize])
const TestCase * current_test_case() const GTEST_LOCK_EXCLUDED_(mutex_)
internal::ParameterizedTestCaseRegistry parameterized_test_registry_
static void PrintCharsAsStringTo(const CharType *begin, size_t len, ostream *os)
static bool HasNonfatalFailure()
const char kPrintTimeFlag[]
FunctionMockers function_mockers
TestInfo * current_test_info()
const char kThrowOnFailureFlag[]
void PrintTo(const ReferenceWrapper< T > &ref,::std::ostream *os)
bool ValidateTestPropertyName(const std::string &property_name, const std::vector< std::string > &reserved_names)
TestInfo * current_test_info_
static bool ParseGoogleMockStringFlag(const char *str, const char *flag, std::string *value)
void Append(TestEventListener *listener)
static std::string PrintTestPartResultToString(const TestPartResult &test_part_result)
#define GTEST_REPEATER_METHOD_(Name, Type)
const char kPathSeparator
GTEST_API_ bool ParseInt32Flag(const char *str, const char *flag, Int32 *value)
FilePath original_working_dir_
::std::string first_used_test_case
virtual ~ScopedFakeTestPartResultReporter()
virtual ~UntypedFunctionMockerBase()
GTEST_DEFINE_string_(color, internal::StringFromGTestEnv("color","auto"),"Whether to use colors in the output. Valid values: yes, no, ""and auto. 'auto' means to use colors if the output is ""being sent to a terminal and the TERM environment variable ""is set to a terminal type that supports colors.")
virtual void OnTestProgramEnd(const UnitTest &)
#define GTEST_LOCK_EXCLUDED_(locks)
TestCase * GetMutableTestCase(int i)
AssertionResult FloatLE(const char *expr1, const char *expr2, float val1, float val2)
std::string CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_
void printf(BasicWriter< Char > &w, BasicCStringRef< Char > format, ArgList args)
static void UniversalPrintCharArray(const CharType *begin, size_t len, ostream *os)
static void OutputXmlCDataSection(::std::ostream *stream, const char *data)
TimeInMillis elapsed_time() const
static const char kTypeParamLabel[]