00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034 #include "gtest/gtest.h"
00035 #include "gtest/gtest-spi.h"
00036
00037 #include <ctype.h>
00038 #include <math.h>
00039 #include <stdarg.h>
00040 #include <stdio.h>
00041 #include <stdlib.h>
00042 #include <wchar.h>
00043 #include <wctype.h>
00044
00045 #include <algorithm>
00046 #include <ostream>
00047 #include <sstream>
00048 #include <vector>
00049
00050 #if GTEST_OS_LINUX
00051
00052
00053
00054 # define GTEST_HAS_GETTIMEOFDAY_ 1
00055
00056 # include <fcntl.h>
00057 # include <limits.h>
00058 # include <sched.h>
00059
00060 # include <strings.h>
00061 # include <sys/mman.h>
00062 # include <sys/time.h>
00063 # include <unistd.h>
00064 # include <string>
00065
00066 #elif GTEST_OS_SYMBIAN
00067 # define GTEST_HAS_GETTIMEOFDAY_ 1
00068 # include <sys/time.h>
00069
00070 #elif GTEST_OS_ZOS
00071 # define GTEST_HAS_GETTIMEOFDAY_ 1
00072 # include <sys/time.h>
00073
00074
00075 # include <strings.h>
00076
00077 #elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE.
00078
00079 # include <windows.h>
00080
00081 #elif GTEST_OS_WINDOWS // We are on Windows proper.
00082
00083 # include <io.h>
00084 # include <sys/timeb.h>
00085 # include <sys/types.h>
00086 # include <sys/stat.h>
00087
00088 # if GTEST_OS_WINDOWS_MINGW
00089
00090
00091
00092
00093
00094
00095 # define GTEST_HAS_GETTIMEOFDAY_ 1
00096 # include <sys/time.h>
00097 # endif // GTEST_OS_WINDOWS_MINGW
00098
00099
00100
00101 # include <windows.h>
00102
00103 #else
00104
00105
00106
00107
00108 # define GTEST_HAS_GETTIMEOFDAY_ 1
00109
00110
00111
00112 # include <sys/time.h>
00113 # include <unistd.h>
00114
00115 #endif // GTEST_OS_LINUX
00116
00117 #if GTEST_HAS_EXCEPTIONS
00118 # include <stdexcept>
00119 #endif
00120
00121 #if GTEST_CAN_STREAM_RESULTS_
00122 # include <arpa/inet.h>
00123 # include <netdb.h>
00124 #endif
00125
00126
00127
00128
00129
00130
00131 #define GTEST_IMPLEMENTATION_ 1
00132 #include "src/gtest-internal-inl.h"
00133 #undef GTEST_IMPLEMENTATION_
00134
00135 #if GTEST_OS_WINDOWS
00136 # define vsnprintf _vsnprintf
00137 #endif // GTEST_OS_WINDOWS
00138
00139 namespace testing {
00140
00141 using internal::CountIf;
00142 using internal::ForEach;
00143 using internal::GetElementOr;
00144 using internal::Shuffle;
00145
00146
00147
00148
00149
00150 static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
00151
00152
00153
00154
00155 static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*";
00156
00157
00158 static const char kUniversalFilter[] = "*";
00159
00160
00161 static const char kDefaultOutputFile[] = "test_detail.xml";
00162
00163
00164 static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
00165
00166 static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
00167
00168 static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
00169
00170 namespace internal {
00171
00172
00173
00174 const char kStackTraceMarker[] = "\nStack trace:\n";
00175
00176
00177
00178 bool g_help_flag = false;
00179
00180 }
00181
00182 GTEST_DEFINE_bool_(
00183 also_run_disabled_tests,
00184 internal::BoolFromGTestEnv("also_run_disabled_tests", false),
00185 "Run disabled tests too, in addition to the tests normally being run.");
00186
00187 GTEST_DEFINE_bool_(
00188 break_on_failure,
00189 internal::BoolFromGTestEnv("break_on_failure", false),
00190 "True iff a failed assertion should be a debugger break-point.");
00191
00192 GTEST_DEFINE_bool_(
00193 catch_exceptions,
00194 internal::BoolFromGTestEnv("catch_exceptions", true),
00195 "True iff " GTEST_NAME_
00196 " should catch exceptions and treat them as test failures.");
00197
00198 GTEST_DEFINE_string_(
00199 color,
00200 internal::StringFromGTestEnv("color", "auto"),
00201 "Whether to use colors in the output. Valid values: yes, no, "
00202 "and auto. 'auto' means to use colors if the output is "
00203 "being sent to a terminal and the TERM environment variable "
00204 "is set to xterm, xterm-color, xterm-256color, linux or cygwin.");
00205
00206 GTEST_DEFINE_string_(
00207 filter,
00208 internal::StringFromGTestEnv("filter", kUniversalFilter),
00209 "A colon-separated list of glob (not regex) patterns "
00210 "for filtering the tests to run, optionally followed by a "
00211 "'-' and a : separated list of negative patterns (tests to "
00212 "exclude). A test is run if it matches one of the positive "
00213 "patterns and does not match any of the negative patterns.");
00214
00215 GTEST_DEFINE_bool_(list_tests, false,
00216 "List all tests without running them.");
00217
00218 GTEST_DEFINE_string_(
00219 output,
00220 internal::StringFromGTestEnv("output", ""),
00221 "A format (currently must be \"xml\"), optionally followed "
00222 "by a colon and an output file name or directory. A directory "
00223 "is indicated by a trailing pathname separator. "
00224 "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
00225 "If a directory is specified, output files will be created "
00226 "within that directory, with file-names based on the test "
00227 "executable's name and, if necessary, made unique by adding "
00228 "digits.");
00229
00230 GTEST_DEFINE_bool_(
00231 print_time,
00232 internal::BoolFromGTestEnv("print_time", true),
00233 "True iff " GTEST_NAME_
00234 " should display elapsed time in text output.");
00235
00236 GTEST_DEFINE_int32_(
00237 random_seed,
00238 internal::Int32FromGTestEnv("random_seed", 0),
00239 "Random number seed to use when shuffling test orders. Must be in range "
00240 "[1, 99999], or 0 to use a seed based on the current time.");
00241
00242 GTEST_DEFINE_int32_(
00243 repeat,
00244 internal::Int32FromGTestEnv("repeat", 1),
00245 "How many times to repeat each test. Specify a negative number "
00246 "for repeating forever. Useful for shaking out flaky tests.");
00247
00248 GTEST_DEFINE_bool_(
00249 show_internal_stack_frames, false,
00250 "True iff " GTEST_NAME_ " should include internal stack frames when "
00251 "printing test failure stack traces.");
00252
00253 GTEST_DEFINE_bool_(
00254 shuffle,
00255 internal::BoolFromGTestEnv("shuffle", false),
00256 "True iff " GTEST_NAME_
00257 " should randomize tests' order on every run.");
00258
00259 GTEST_DEFINE_int32_(
00260 stack_trace_depth,
00261 internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
00262 "The maximum number of stack frames to print when an "
00263 "assertion fails. The valid range is 0 through 100, inclusive.");
00264
00265 GTEST_DEFINE_string_(
00266 stream_result_to,
00267 internal::StringFromGTestEnv("stream_result_to", ""),
00268 "This flag specifies the host name and the port number on which to stream "
00269 "test results. Example: \"localhost:555\". The flag is effective only on "
00270 "Linux.");
00271
00272 GTEST_DEFINE_bool_(
00273 throw_on_failure,
00274 internal::BoolFromGTestEnv("throw_on_failure", false),
00275 "When this flag is specified, a failed assertion will throw an exception "
00276 "if exceptions are enabled or exit the program with a non-zero code "
00277 "otherwise.");
00278
00279 namespace internal {
00280
00281
00282
00283
00284 UInt32 Random::Generate(UInt32 range) {
00285
00286 state_ = (1103515245U*state_ + 12345U) % kMaxRange;
00287
00288 GTEST_CHECK_(range > 0)
00289 << "Cannot generate a number in the range [0, 0).";
00290 GTEST_CHECK_(range <= kMaxRange)
00291 << "Generation of a number in [0, " << range << ") was requested, "
00292 << "but this can only generate numbers in [0, " << kMaxRange << ").";
00293
00294
00295
00296
00297 return state_ % range;
00298 }
00299
00300
00301
00302
00303
00304
00305
00306
00307
00308 int g_init_gtest_count = 0;
00309 static bool GTestIsInitialized() { return g_init_gtest_count != 0; }
00310
00311
00312
00313
00314 static int SumOverTestCaseList(const std::vector<TestCase*>& case_list,
00315 int (TestCase::*method)() const) {
00316 int sum = 0;
00317 for (size_t i = 0; i < case_list.size(); i++) {
00318 sum += (case_list[i]->*method)();
00319 }
00320 return sum;
00321 }
00322
00323
00324 static bool TestCasePassed(const TestCase* test_case) {
00325 return test_case->should_run() && test_case->Passed();
00326 }
00327
00328
00329 static bool TestCaseFailed(const TestCase* test_case) {
00330 return test_case->should_run() && test_case->Failed();
00331 }
00332
00333
00334
00335 static bool ShouldRunTestCase(const TestCase* test_case) {
00336 return test_case->should_run();
00337 }
00338
00339
00340 AssertHelper::AssertHelper(TestPartResult::Type type,
00341 const char* file,
00342 int line,
00343 const char* message)
00344 : data_(new AssertHelperData(type, file, line, message)) {
00345 }
00346
00347 AssertHelper::~AssertHelper() {
00348 delete data_;
00349 }
00350
00351
00352 void AssertHelper::operator=(const Message& message) const {
00353 UnitTest::GetInstance()->
00354 AddTestPartResult(data_->type, data_->file, data_->line,
00355 AppendUserMessage(data_->message, message),
00356 UnitTest::GetInstance()->impl()
00357 ->CurrentOsStackTraceExceptTop(1)
00358
00359 );
00360 }
00361
00362
00363 GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex);
00364
00365
00366 String g_executable_path;
00367
00368
00369
00370 FilePath GetCurrentExecutableName() {
00371 FilePath result;
00372
00373 #if GTEST_OS_WINDOWS
00374 result.Set(FilePath(g_executable_path).RemoveExtension("exe"));
00375 #else
00376 result.Set(FilePath(g_executable_path));
00377 #endif // GTEST_OS_WINDOWS
00378
00379 return result.RemoveDirectoryName();
00380 }
00381
00382
00383
00384
00385 String UnitTestOptions::GetOutputFormat() {
00386 const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
00387 if (gtest_output_flag == NULL) return String("");
00388
00389 const char* const colon = strchr(gtest_output_flag, ':');
00390 return (colon == NULL) ?
00391 String(gtest_output_flag) :
00392 String(gtest_output_flag, colon - gtest_output_flag);
00393 }
00394
00395
00396
00397 String UnitTestOptions::GetAbsolutePathToOutputFile() {
00398 const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
00399 if (gtest_output_flag == NULL)
00400 return String("");
00401
00402 const char* const colon = strchr(gtest_output_flag, ':');
00403 if (colon == NULL)
00404 return String(internal::FilePath::ConcatPaths(
00405 internal::FilePath(
00406 UnitTest::GetInstance()->original_working_dir()),
00407 internal::FilePath(kDefaultOutputFile)).ToString() );
00408
00409 internal::FilePath output_name(colon + 1);
00410 if (!output_name.IsAbsolutePath())
00411
00412
00413
00414
00415 output_name = internal::FilePath::ConcatPaths(
00416 internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
00417 internal::FilePath(colon + 1));
00418
00419 if (!output_name.IsDirectory())
00420 return output_name.ToString();
00421
00422 internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
00423 output_name, internal::GetCurrentExecutableName(),
00424 GetOutputFormat().c_str()));
00425 return result.ToString();
00426 }
00427
00428
00429
00430
00431
00432
00433 bool UnitTestOptions::PatternMatchesString(const char *pattern,
00434 const char *str) {
00435 switch (*pattern) {
00436 case '\0':
00437 case ':':
00438 return *str == '\0';
00439 case '?':
00440 return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);
00441 case '*':
00442 return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||
00443 PatternMatchesString(pattern + 1, str);
00444 default:
00445 return *pattern == *str &&
00446 PatternMatchesString(pattern + 1, str + 1);
00447 }
00448 }
00449
00450 bool UnitTestOptions::MatchesFilter(const String& name, const char* filter) {
00451 const char *cur_pattern = filter;
00452 for (;;) {
00453 if (PatternMatchesString(cur_pattern, name.c_str())) {
00454 return true;
00455 }
00456
00457
00458 cur_pattern = strchr(cur_pattern, ':');
00459
00460
00461 if (cur_pattern == NULL) {
00462 return false;
00463 }
00464
00465
00466 cur_pattern++;
00467 }
00468 }
00469
00470
00471
00472
00473
00474 bool UnitTestOptions::FilterMatchesTest(const String &test_case_name,
00475 const String &test_name) {
00476 const String& full_name = String::Format("%s.%s",
00477 test_case_name.c_str(),
00478 test_name.c_str());
00479
00480
00481
00482 const char* const p = GTEST_FLAG(filter).c_str();
00483 const char* const dash = strchr(p, '-');
00484 String positive;
00485 String negative;
00486 if (dash == NULL) {
00487 positive = GTEST_FLAG(filter).c_str();
00488 negative = String("");
00489 } else {
00490 positive = String(p, dash - p);
00491 negative = String(dash+1);
00492 if (positive.empty()) {
00493
00494 positive = kUniversalFilter;
00495 }
00496 }
00497
00498
00499
00500 return (MatchesFilter(full_name, positive.c_str()) &&
00501 !MatchesFilter(full_name, negative.c_str()));
00502 }
00503
00504 #if GTEST_HAS_SEH
00505
00506
00507
00508 int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
00509
00510
00511
00512
00513
00514
00515
00516
00517 const DWORD kCxxExceptionCode = 0xe06d7363;
00518
00519 bool should_handle = true;
00520
00521 if (!GTEST_FLAG(catch_exceptions))
00522 should_handle = false;
00523 else if (exception_code == EXCEPTION_BREAKPOINT)
00524 should_handle = false;
00525 else if (exception_code == kCxxExceptionCode)
00526 should_handle = false;
00527
00528 return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
00529 }
00530 #endif // GTEST_HAS_SEH
00531
00532 }
00533
00534
00535
00536
00537 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
00538 TestPartResultArray* result)
00539 : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
00540 result_(result) {
00541 Init();
00542 }
00543
00544
00545
00546
00547 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
00548 InterceptMode intercept_mode, TestPartResultArray* result)
00549 : intercept_mode_(intercept_mode),
00550 result_(result) {
00551 Init();
00552 }
00553
00554 void ScopedFakeTestPartResultReporter::Init() {
00555 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
00556 if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
00557 old_reporter_ = impl->GetGlobalTestPartResultReporter();
00558 impl->SetGlobalTestPartResultReporter(this);
00559 } else {
00560 old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
00561 impl->SetTestPartResultReporterForCurrentThread(this);
00562 }
00563 }
00564
00565
00566
00567 ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
00568 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
00569 if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
00570 impl->SetGlobalTestPartResultReporter(old_reporter_);
00571 } else {
00572 impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
00573 }
00574 }
00575
00576
00577
00578 void ScopedFakeTestPartResultReporter::ReportTestPartResult(
00579 const TestPartResult& result) {
00580 result_->Append(result);
00581 }
00582
00583 namespace internal {
00584
00585
00586
00587
00588
00589
00590
00591
00592
00593
00594 TypeId GetTestTypeId() {
00595 return GetTypeId<Test>();
00596 }
00597
00598
00599
00600 extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
00601
00602
00603
00604
00605 AssertionResult HasOneFailure(const char* ,
00606 const char* ,
00607 const char* ,
00608 const TestPartResultArray& results,
00609 TestPartResult::Type type,
00610 const string& substr) {
00611 const String expected(type == TestPartResult::kFatalFailure ?
00612 "1 fatal failure" :
00613 "1 non-fatal failure");
00614 Message msg;
00615 if (results.size() != 1) {
00616 msg << "Expected: " << expected << "\n"
00617 << " Actual: " << results.size() << " failures";
00618 for (int i = 0; i < results.size(); i++) {
00619 msg << "\n" << results.GetTestPartResult(i);
00620 }
00621 return AssertionFailure() << msg;
00622 }
00623
00624 const TestPartResult& r = results.GetTestPartResult(0);
00625 if (r.type() != type) {
00626 return AssertionFailure() << "Expected: " << expected << "\n"
00627 << " Actual:\n"
00628 << r;
00629 }
00630
00631 if (strstr(r.message(), substr.c_str()) == NULL) {
00632 return AssertionFailure() << "Expected: " << expected << " containing \""
00633 << substr << "\"\n"
00634 << " Actual:\n"
00635 << r;
00636 }
00637
00638 return AssertionSuccess();
00639 }
00640
00641
00642
00643
00644 SingleFailureChecker:: SingleFailureChecker(
00645 const TestPartResultArray* results,
00646 TestPartResult::Type type,
00647 const string& substr)
00648 : results_(results),
00649 type_(type),
00650 substr_(substr) {}
00651
00652
00653
00654
00655
00656 SingleFailureChecker::~SingleFailureChecker() {
00657 EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_);
00658 }
00659
00660 DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
00661 UnitTestImpl* unit_test) : unit_test_(unit_test) {}
00662
00663 void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
00664 const TestPartResult& result) {
00665 unit_test_->current_test_result()->AddTestPartResult(result);
00666 unit_test_->listeners()->repeater()->OnTestPartResult(result);
00667 }
00668
00669 DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
00670 UnitTestImpl* unit_test) : unit_test_(unit_test) {}
00671
00672 void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
00673 const TestPartResult& result) {
00674 unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
00675 }
00676
00677
00678 TestPartResultReporterInterface*
00679 UnitTestImpl::GetGlobalTestPartResultReporter() {
00680 internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
00681 return global_test_part_result_repoter_;
00682 }
00683
00684
00685 void UnitTestImpl::SetGlobalTestPartResultReporter(
00686 TestPartResultReporterInterface* reporter) {
00687 internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
00688 global_test_part_result_repoter_ = reporter;
00689 }
00690
00691
00692 TestPartResultReporterInterface*
00693 UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
00694 return per_thread_test_part_result_reporter_.get();
00695 }
00696
00697
00698 void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
00699 TestPartResultReporterInterface* reporter) {
00700 per_thread_test_part_result_reporter_.set(reporter);
00701 }
00702
00703
00704 int UnitTestImpl::successful_test_case_count() const {
00705 return CountIf(test_cases_, TestCasePassed);
00706 }
00707
00708
00709 int UnitTestImpl::failed_test_case_count() const {
00710 return CountIf(test_cases_, TestCaseFailed);
00711 }
00712
00713
00714 int UnitTestImpl::total_test_case_count() const {
00715 return static_cast<int>(test_cases_.size());
00716 }
00717
00718
00719
00720 int UnitTestImpl::test_case_to_run_count() const {
00721 return CountIf(test_cases_, ShouldRunTestCase);
00722 }
00723
00724
00725 int UnitTestImpl::successful_test_count() const {
00726 return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count);
00727 }
00728
00729
00730 int UnitTestImpl::failed_test_count() const {
00731 return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count);
00732 }
00733
00734
00735 int UnitTestImpl::disabled_test_count() const {
00736 return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count);
00737 }
00738
00739
00740 int UnitTestImpl::total_test_count() const {
00741 return SumOverTestCaseList(test_cases_, &TestCase::total_test_count);
00742 }
00743
00744
00745 int UnitTestImpl::test_to_run_count() const {
00746 return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count);
00747 }
00748
00749
00750
00751
00752
00753
00754
00755
00756
00757
00758
00759 String UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
00760 (void)skip_count;
00761 return String("");
00762 }
00763
00764
00765 TimeInMillis GetTimeInMillis() {
00766 #if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__)
00767
00768
00769 const TimeInMillis kJavaEpochToWinFileTimeDelta =
00770 static_cast<TimeInMillis>(116444736UL) * 100000UL;
00771 const DWORD kTenthMicrosInMilliSecond = 10000;
00772
00773 SYSTEMTIME now_systime;
00774 FILETIME now_filetime;
00775 ULARGE_INTEGER now_int64;
00776
00777
00778 GetSystemTime(&now_systime);
00779 if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
00780 now_int64.LowPart = now_filetime.dwLowDateTime;
00781 now_int64.HighPart = now_filetime.dwHighDateTime;
00782 now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
00783 kJavaEpochToWinFileTimeDelta;
00784 return now_int64.QuadPart;
00785 }
00786 return 0;
00787 #elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_
00788 __timeb64 now;
00789
00790 # ifdef _MSC_VER
00791
00792
00793
00794
00795
00796 # pragma warning(push) // Saves the current warning state.
00797 # pragma warning(disable:4996) // Temporarily disables warning 4996.
00798 _ftime64(&now);
00799 # pragma warning(pop) // Restores the warning state.
00800 # else
00801
00802 _ftime64(&now);
00803
00804 # endif // _MSC_VER
00805
00806 return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
00807 #elif GTEST_HAS_GETTIMEOFDAY_
00808 struct timeval now;
00809 gettimeofday(&now, NULL);
00810 return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
00811 #else
00812 # error "Don't know how to get the current time on your system."
00813 #endif
00814 }
00815
00816
00817
00818
00819
00820
00821
00822
00823
00824
00825
00826
00827 String String::ShowCStringQuoted(const char* c_str) {
00828 return c_str ? String::Format("\"%s\"", c_str) : String("(null)");
00829 }
00830
00831
00832
00833
00834
00835 static char* CloneString(const char* str, size_t length) {
00836 if (str == NULL) {
00837 return NULL;
00838 } else {
00839 char* const clone = new char[length + 1];
00840 posix::StrNCpy(clone, str, length);
00841 clone[length] = '\0';
00842 return clone;
00843 }
00844 }
00845
00846
00847
00848
00849 const char * String::CloneCString(const char* c_str) {
00850 return (c_str == NULL) ?
00851 NULL : CloneString(c_str, strlen(c_str));
00852 }
00853
00854 #if GTEST_OS_WINDOWS_MOBILE
00855
00856
00857
00858
00859 LPCWSTR String::AnsiToUtf16(const char* ansi) {
00860 if (!ansi) return NULL;
00861 const int length = strlen(ansi);
00862 const int unicode_length =
00863 MultiByteToWideChar(CP_ACP, 0, ansi, length,
00864 NULL, 0);
00865 WCHAR* unicode = new WCHAR[unicode_length + 1];
00866 MultiByteToWideChar(CP_ACP, 0, ansi, length,
00867 unicode, unicode_length);
00868 unicode[unicode_length] = 0;
00869 return unicode;
00870 }
00871
00872
00873
00874
00875
00876 const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
00877 if (!utf16_str) return NULL;
00878 const int ansi_length =
00879 WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
00880 NULL, 0, NULL, NULL);
00881 char* ansi = new char[ansi_length + 1];
00882 WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
00883 ansi, ansi_length, NULL, NULL);
00884 ansi[ansi_length] = 0;
00885 return ansi;
00886 }
00887
00888 #endif // GTEST_OS_WINDOWS_MOBILE
00889
00890
00891
00892
00893
00894
00895 bool String::CStringEquals(const char * lhs, const char * rhs) {
00896 if ( lhs == NULL ) return rhs == NULL;
00897
00898 if ( rhs == NULL ) return false;
00899
00900 return strcmp(lhs, rhs) == 0;
00901 }
00902
00903 #if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
00904
00905
00906
00907 static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
00908 Message* msg) {
00909
00910
00911
00912
00913
00914 for (size_t i = 0; i != length; ) {
00915 if (wstr[i] != L'\0') {
00916 *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
00917 while (i != length && wstr[i] != L'\0')
00918 i++;
00919 } else {
00920 *msg << '\0';
00921 i++;
00922 }
00923 }
00924 }
00925
00926 #endif // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
00927
00928 }
00929
00930 #if GTEST_HAS_STD_WSTRING
00931
00932
00933 Message& Message::operator <<(const ::std::wstring& wstr) {
00934 internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
00935 return *this;
00936 }
00937 #endif // GTEST_HAS_STD_WSTRING
00938
00939 #if GTEST_HAS_GLOBAL_WSTRING
00940
00941
00942 Message& Message::operator <<(const ::wstring& wstr) {
00943 internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
00944 return *this;
00945 }
00946 #endif // GTEST_HAS_GLOBAL_WSTRING
00947
00948
00949
00950 AssertionResult::AssertionResult(const AssertionResult& other)
00951 : success_(other.success_),
00952 message_(other.message_.get() != NULL ?
00953 new ::std::string(*other.message_) :
00954 static_cast< ::std::string*>(NULL)) {
00955 }
00956
00957
00958 AssertionResult AssertionResult::operator!() const {
00959 AssertionResult negation(!success_);
00960 if (message_.get() != NULL)
00961 negation << *message_;
00962 return negation;
00963 }
00964
00965
00966 AssertionResult AssertionSuccess() {
00967 return AssertionResult(true);
00968 }
00969
00970
00971 AssertionResult AssertionFailure() {
00972 return AssertionResult(false);
00973 }
00974
00975
00976
00977 AssertionResult AssertionFailure(const Message& message) {
00978 return AssertionFailure() << message;
00979 }
00980
00981 namespace internal {
00982
00983
00984
00985
00986
00987
00988
00989
00990
00991
00992
00993
00994
00995
00996
00997
00998 AssertionResult EqFailure(const char* expected_expression,
00999 const char* actual_expression,
01000 const String& expected_value,
01001 const String& actual_value,
01002 bool ignoring_case) {
01003 Message msg;
01004 msg << "Value of: " << actual_expression;
01005 if (actual_value != actual_expression) {
01006 msg << "\n Actual: " << actual_value;
01007 }
01008
01009 msg << "\nExpected: " << expected_expression;
01010 if (ignoring_case) {
01011 msg << " (ignoring case)";
01012 }
01013 if (expected_value != expected_expression) {
01014 msg << "\nWhich is: " << expected_value;
01015 }
01016
01017 return AssertionFailure() << msg;
01018 }
01019
01020
01021 String GetBoolAssertionFailureMessage(const AssertionResult& assertion_result,
01022 const char* expression_text,
01023 const char* actual_predicate_value,
01024 const char* expected_predicate_value) {
01025 const char* actual_message = assertion_result.message();
01026 Message msg;
01027 msg << "Value of: " << expression_text
01028 << "\n Actual: " << actual_predicate_value;
01029 if (actual_message[0] != '\0')
01030 msg << " (" << actual_message << ")";
01031 msg << "\nExpected: " << expected_predicate_value;
01032 return msg.GetString();
01033 }
01034
01035
01036 AssertionResult DoubleNearPredFormat(const char* expr1,
01037 const char* expr2,
01038 const char* abs_error_expr,
01039 double val1,
01040 double val2,
01041 double abs_error) {
01042 const double diff = fabs(val1 - val2);
01043 if (diff <= abs_error) return AssertionSuccess();
01044
01045
01046
01047 return AssertionFailure()
01048 << "The difference between " << expr1 << " and " << expr2
01049 << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"
01050 << expr1 << " evaluates to " << val1 << ",\n"
01051 << expr2 << " evaluates to " << val2 << ", and\n"
01052 << abs_error_expr << " evaluates to " << abs_error << ".";
01053 }
01054
01055
01056
01057 template <typename RawType>
01058 AssertionResult FloatingPointLE(const char* expr1,
01059 const char* expr2,
01060 RawType val1,
01061 RawType val2) {
01062
01063 if (val1 < val2) {
01064 return AssertionSuccess();
01065 }
01066
01067
01068 const FloatingPoint<RawType> lhs(val1), rhs(val2);
01069 if (lhs.AlmostEquals(rhs)) {
01070 return AssertionSuccess();
01071 }
01072
01073
01074
01075
01076
01077 ::std::stringstream val1_ss;
01078 val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
01079 << val1;
01080
01081 ::std::stringstream val2_ss;
01082 val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
01083 << val2;
01084
01085 return AssertionFailure()
01086 << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
01087 << " Actual: " << StringStreamToString(&val1_ss) << " vs "
01088 << StringStreamToString(&val2_ss);
01089 }
01090
01091 }
01092
01093
01094
01095 AssertionResult FloatLE(const char* expr1, const char* expr2,
01096 float val1, float val2) {
01097 return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
01098 }
01099
01100
01101
01102 AssertionResult DoubleLE(const char* expr1, const char* expr2,
01103 double val1, double val2) {
01104 return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
01105 }
01106
01107 namespace internal {
01108
01109
01110
01111 AssertionResult CmpHelperEQ(const char* expected_expression,
01112 const char* actual_expression,
01113 BiggestInt expected,
01114 BiggestInt actual) {
01115 if (expected == actual) {
01116 return AssertionSuccess();
01117 }
01118
01119 return EqFailure(expected_expression,
01120 actual_expression,
01121 FormatForComparisonFailureMessage(expected, actual),
01122 FormatForComparisonFailureMessage(actual, expected),
01123 false);
01124 }
01125
01126
01127
01128
01129 #define GTEST_IMPL_CMP_HELPER_(op_name, op)\
01130 AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
01131 BiggestInt val1, BiggestInt val2) {\
01132 if (val1 op val2) {\
01133 return AssertionSuccess();\
01134 } else {\
01135 return AssertionFailure() \
01136 << "Expected: (" << expr1 << ") " #op " (" << expr2\
01137 << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
01138 << " vs " << FormatForComparisonFailureMessage(val2, val1);\
01139 }\
01140 }
01141
01142
01143
01144 GTEST_IMPL_CMP_HELPER_(NE, !=)
01145
01146
01147 GTEST_IMPL_CMP_HELPER_(LE, <=)
01148
01149
01150 GTEST_IMPL_CMP_HELPER_(LT, < )
01151
01152
01153 GTEST_IMPL_CMP_HELPER_(GE, >=)
01154
01155
01156 GTEST_IMPL_CMP_HELPER_(GT, > )
01157
01158 #undef GTEST_IMPL_CMP_HELPER_
01159
01160
01161 AssertionResult CmpHelperSTREQ(const char* expected_expression,
01162 const char* actual_expression,
01163 const char* expected,
01164 const char* actual) {
01165 if (String::CStringEquals(expected, actual)) {
01166 return AssertionSuccess();
01167 }
01168
01169 return EqFailure(expected_expression,
01170 actual_expression,
01171 String::ShowCStringQuoted(expected),
01172 String::ShowCStringQuoted(actual),
01173 false);
01174 }
01175
01176
01177 AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression,
01178 const char* actual_expression,
01179 const char* expected,
01180 const char* actual) {
01181 if (String::CaseInsensitiveCStringEquals(expected, actual)) {
01182 return AssertionSuccess();
01183 }
01184
01185 return EqFailure(expected_expression,
01186 actual_expression,
01187 String::ShowCStringQuoted(expected),
01188 String::ShowCStringQuoted(actual),
01189 true);
01190 }
01191
01192
01193 AssertionResult CmpHelperSTRNE(const char* s1_expression,
01194 const char* s2_expression,
01195 const char* s1,
01196 const char* s2) {
01197 if (!String::CStringEquals(s1, s2)) {
01198 return AssertionSuccess();
01199 } else {
01200 return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
01201 << s2_expression << "), actual: \""
01202 << s1 << "\" vs \"" << s2 << "\"";
01203 }
01204 }
01205
01206
01207 AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
01208 const char* s2_expression,
01209 const char* s1,
01210 const char* s2) {
01211 if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
01212 return AssertionSuccess();
01213 } else {
01214 return AssertionFailure()
01215 << "Expected: (" << s1_expression << ") != ("
01216 << s2_expression << ") (ignoring case), actual: \""
01217 << s1 << "\" vs \"" << s2 << "\"";
01218 }
01219 }
01220
01221 }
01222
01223 namespace {
01224
01225
01226
01227
01228
01229
01230
01231 bool IsSubstringPred(const char* needle, const char* haystack) {
01232 if (needle == NULL || haystack == NULL)
01233 return needle == haystack;
01234
01235 return strstr(haystack, needle) != NULL;
01236 }
01237
01238 bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
01239 if (needle == NULL || haystack == NULL)
01240 return needle == haystack;
01241
01242 return wcsstr(haystack, needle) != NULL;
01243 }
01244
01245
01246 template <typename StringType>
01247 bool IsSubstringPred(const StringType& needle,
01248 const StringType& haystack) {
01249 return haystack.find(needle) != StringType::npos;
01250 }
01251
01252
01253
01254
01255
01256 template <typename StringType>
01257 AssertionResult IsSubstringImpl(
01258 bool expected_to_be_substring,
01259 const char* needle_expr, const char* haystack_expr,
01260 const StringType& needle, const StringType& haystack) {
01261 if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
01262 return AssertionSuccess();
01263
01264 const bool is_wide_string = sizeof(needle[0]) > 1;
01265 const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
01266 return AssertionFailure()
01267 << "Value of: " << needle_expr << "\n"
01268 << " Actual: " << begin_string_quote << needle << "\"\n"
01269 << "Expected: " << (expected_to_be_substring ? "" : "not ")
01270 << "a substring of " << haystack_expr << "\n"
01271 << "Which is: " << begin_string_quote << haystack << "\"";
01272 }
01273
01274 }
01275
01276
01277
01278
01279
01280 AssertionResult IsSubstring(
01281 const char* needle_expr, const char* haystack_expr,
01282 const char* needle, const char* haystack) {
01283 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
01284 }
01285
01286 AssertionResult IsSubstring(
01287 const char* needle_expr, const char* haystack_expr,
01288 const wchar_t* needle, const wchar_t* haystack) {
01289 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
01290 }
01291
01292 AssertionResult IsNotSubstring(
01293 const char* needle_expr, const char* haystack_expr,
01294 const char* needle, const char* haystack) {
01295 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
01296 }
01297
01298 AssertionResult IsNotSubstring(
01299 const char* needle_expr, const char* haystack_expr,
01300 const wchar_t* needle, const wchar_t* haystack) {
01301 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
01302 }
01303
01304 AssertionResult IsSubstring(
01305 const char* needle_expr, const char* haystack_expr,
01306 const ::std::string& needle, const ::std::string& haystack) {
01307 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
01308 }
01309
01310 AssertionResult IsNotSubstring(
01311 const char* needle_expr, const char* haystack_expr,
01312 const ::std::string& needle, const ::std::string& haystack) {
01313 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
01314 }
01315
01316 #if GTEST_HAS_STD_WSTRING
01317 AssertionResult IsSubstring(
01318 const char* needle_expr, const char* haystack_expr,
01319 const ::std::wstring& needle, const ::std::wstring& haystack) {
01320 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
01321 }
01322
01323 AssertionResult IsNotSubstring(
01324 const char* needle_expr, const char* haystack_expr,
01325 const ::std::wstring& needle, const ::std::wstring& haystack) {
01326 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
01327 }
01328 #endif // GTEST_HAS_STD_WSTRING
01329
01330 namespace internal {
01331
01332 #if GTEST_OS_WINDOWS
01333
01334 namespace {
01335
01336
01337 AssertionResult HRESULTFailureHelper(const char* expr,
01338 const char* expected,
01339 long hr) {
01340 # if GTEST_OS_WINDOWS_MOBILE
01341
01342
01343 const char error_text[] = "";
01344
01345 # else
01346
01347
01348
01349
01350 const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
01351 FORMAT_MESSAGE_IGNORE_INSERTS;
01352 const DWORD kBufSize = 4096;
01353
01354 char error_text[kBufSize] = { '\0' };
01355 DWORD message_length = ::FormatMessageA(kFlags,
01356 0,
01357 hr,
01358 0,
01359 error_text,
01360 kBufSize,
01361 NULL);
01362
01363 for (; message_length && IsSpace(error_text[message_length - 1]);
01364 --message_length) {
01365 error_text[message_length - 1] = '\0';
01366 }
01367
01368 # endif // GTEST_OS_WINDOWS_MOBILE
01369
01370 const String error_hex(String::Format("0x%08X ", hr));
01371 return ::testing::AssertionFailure()
01372 << "Expected: " << expr << " " << expected << ".\n"
01373 << " Actual: " << error_hex << error_text << "\n";
01374 }
01375
01376 }
01377
01378 AssertionResult IsHRESULTSuccess(const char* expr, long hr) {
01379 if (SUCCEEDED(hr)) {
01380 return AssertionSuccess();
01381 }
01382 return HRESULTFailureHelper(expr, "succeeds", hr);
01383 }
01384
01385 AssertionResult IsHRESULTFailure(const char* expr, long hr) {
01386 if (FAILED(hr)) {
01387 return AssertionSuccess();
01388 }
01389 return HRESULTFailureHelper(expr, "fails", hr);
01390 }
01391
01392 #endif // GTEST_OS_WINDOWS
01393
01394
01395
01396
01397
01398
01399
01400
01401
01402
01403
01404
01405
01406
01407 const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) << 7) - 1;
01408
01409
01410 const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1;
01411
01412
01413 const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2*6)) - 1;
01414
01415
01416 const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3*6)) - 1;
01417
01418
01419
01420
01421 inline UInt32 ChopLowBits(UInt32* bits, int n) {
01422 const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1);
01423 *bits >>= n;
01424 return low_bits;
01425 }
01426
01427
01428
01429
01430
01431
01432
01433
01434
01435 char* CodePointToUtf8(UInt32 code_point, char* str) {
01436 if (code_point <= kMaxCodePoint1) {
01437 str[1] = '\0';
01438 str[0] = static_cast<char>(code_point);
01439 } else if (code_point <= kMaxCodePoint2) {
01440 str[2] = '\0';
01441 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));
01442 str[0] = static_cast<char>(0xC0 | code_point);
01443 } else if (code_point <= kMaxCodePoint3) {
01444 str[3] = '\0';
01445 str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));
01446 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));
01447 str[0] = static_cast<char>(0xE0 | code_point);
01448 } else if (code_point <= kMaxCodePoint4) {
01449 str[4] = '\0';
01450 str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));
01451 str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));
01452 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));
01453 str[0] = static_cast<char>(0xF0 | code_point);
01454 } else {
01455
01456
01457
01458
01459
01460 posix::StrNCpy(
01461 str, String::Format("(Invalid Unicode 0x%X)", code_point).c_str(), 32);
01462 str[31] = '\0';
01463
01464 }
01465 return str;
01466 }
01467
01468
01469
01470
01471
01472
01473
01474
01475 inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
01476 return sizeof(wchar_t) == 2 &&
01477 (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;
01478 }
01479
01480
01481 inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first,
01482 wchar_t second) {
01483 const UInt32 mask = (1 << 10) - 1;
01484 return (sizeof(wchar_t) == 2) ?
01485 (((first & mask) << 10) | (second & mask)) + 0x10000 :
01486
01487
01488 static_cast<UInt32>(first);
01489 }
01490
01491
01492
01493
01494
01495
01496
01497
01498
01499
01500
01501
01502
01503
01504 String WideStringToUtf8(const wchar_t* str, int num_chars) {
01505 if (num_chars == -1)
01506 num_chars = static_cast<int>(wcslen(str));
01507
01508 ::std::stringstream stream;
01509 for (int i = 0; i < num_chars; ++i) {
01510 UInt32 unicode_code_point;
01511
01512 if (str[i] == L'\0') {
01513 break;
01514 } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
01515 unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i],
01516 str[i + 1]);
01517 i++;
01518 } else {
01519 unicode_code_point = static_cast<UInt32>(str[i]);
01520 }
01521
01522 char buffer[32];
01523 stream << CodePointToUtf8(unicode_code_point, buffer);
01524 }
01525 return StringStreamToString(&stream);
01526 }
01527
01528
01529
01530 String String::ShowWideCString(const wchar_t * wide_c_str) {
01531 if (wide_c_str == NULL) return String("(null)");
01532
01533 return String(internal::WideStringToUtf8(wide_c_str, -1).c_str());
01534 }
01535
01536
01537
01538 String String::ShowWideCStringQuoted(const wchar_t* wide_c_str) {
01539 if (wide_c_str == NULL) return String("(null)");
01540
01541 return String::Format("L\"%s\"",
01542 String::ShowWideCString(wide_c_str).c_str());
01543 }
01544
01545
01546
01547
01548
01549
01550
01551 bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {
01552 if (lhs == NULL) return rhs == NULL;
01553
01554 if (rhs == NULL) return false;
01555
01556 return wcscmp(lhs, rhs) == 0;
01557 }
01558
01559
01560 AssertionResult CmpHelperSTREQ(const char* expected_expression,
01561 const char* actual_expression,
01562 const wchar_t* expected,
01563 const wchar_t* actual) {
01564 if (String::WideCStringEquals(expected, actual)) {
01565 return AssertionSuccess();
01566 }
01567
01568 return EqFailure(expected_expression,
01569 actual_expression,
01570 String::ShowWideCStringQuoted(expected),
01571 String::ShowWideCStringQuoted(actual),
01572 false);
01573 }
01574
01575
01576 AssertionResult CmpHelperSTRNE(const char* s1_expression,
01577 const char* s2_expression,
01578 const wchar_t* s1,
01579 const wchar_t* s2) {
01580 if (!String::WideCStringEquals(s1, s2)) {
01581 return AssertionSuccess();
01582 }
01583
01584 return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
01585 << s2_expression << "), actual: "
01586 << String::ShowWideCStringQuoted(s1)
01587 << " vs " << String::ShowWideCStringQuoted(s2);
01588 }
01589
01590
01591
01592
01593
01594
01595
01596 bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) {
01597 if (lhs == NULL)
01598 return rhs == NULL;
01599 if (rhs == NULL)
01600 return false;
01601 return posix::StrCaseCmp(lhs, rhs) == 0;
01602 }
01603
01604
01605
01606
01607
01608
01609
01610
01611
01612
01613
01614
01615
01616 bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
01617 const wchar_t* rhs) {
01618 if (lhs == NULL) return rhs == NULL;
01619
01620 if (rhs == NULL) return false;
01621
01622 #if GTEST_OS_WINDOWS
01623 return _wcsicmp(lhs, rhs) == 0;
01624 #elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID
01625 return wcscasecmp(lhs, rhs) == 0;
01626 #else
01627
01628
01629 wint_t left, right;
01630 do {
01631 left = towlower(*lhs++);
01632 right = towlower(*rhs++);
01633 } while (left && left == right);
01634 return left == right;
01635 #endif // OS selector
01636 }
01637
01638
01639
01640
01641 int String::Compare(const String & rhs) const {
01642 const char* const lhs_c_str = c_str();
01643 const char* const rhs_c_str = rhs.c_str();
01644
01645 if (lhs_c_str == NULL) {
01646 return rhs_c_str == NULL ? 0 : -1;
01647 } else if (rhs_c_str == NULL) {
01648 return 1;
01649 }
01650
01651 const size_t shorter_str_len =
01652 length() <= rhs.length() ? length() : rhs.length();
01653 for (size_t i = 0; i != shorter_str_len; i++) {
01654 if (lhs_c_str[i] < rhs_c_str[i]) {
01655 return -1;
01656 } else if (lhs_c_str[i] > rhs_c_str[i]) {
01657 return 1;
01658 }
01659 }
01660 return (length() < rhs.length()) ? -1 :
01661 (length() > rhs.length()) ? 1 : 0;
01662 }
01663
01664
01665
01666 bool String::EndsWith(const char* suffix) const {
01667 if (suffix == NULL || CStringEquals(suffix, "")) return true;
01668
01669 if (c_str() == NULL) return false;
01670
01671 const size_t this_len = strlen(c_str());
01672 const size_t suffix_len = strlen(suffix);
01673 return (this_len >= suffix_len) &&
01674 CStringEquals(c_str() + this_len - suffix_len, suffix);
01675 }
01676
01677
01678
01679 bool String::EndsWithCaseInsensitive(const char* suffix) const {
01680 if (suffix == NULL || CStringEquals(suffix, "")) return true;
01681
01682 if (c_str() == NULL) return false;
01683
01684 const size_t this_len = strlen(c_str());
01685 const size_t suffix_len = strlen(suffix);
01686 return (this_len >= suffix_len) &&
01687 CaseInsensitiveCStringEquals(c_str() + this_len - suffix_len, suffix);
01688 }
01689
01690
01691
01692
01693
01694
01695
01696
01697
01698
01699
01700 String String::Format(const char * format, ...) {
01701 va_list args;
01702 va_start(args, format);
01703
01704 char buffer[4096];
01705 const int kBufferSize = sizeof(buffer)/sizeof(buffer[0]);
01706
01707
01708
01709 #ifdef _MSC_VER // We are using MSVC.
01710 # pragma warning(push) // Saves the current warning state.
01711 # pragma warning(disable:4996) // Temporarily disables warning 4996.
01712
01713 const int size = vsnprintf(buffer, kBufferSize, format, args);
01714
01715 # pragma warning(pop) // Restores the warning state.
01716 #else // We are not using MSVC.
01717 const int size = vsnprintf(buffer, kBufferSize, format, args);
01718 #endif // _MSC_VER
01719 va_end(args);
01720
01721
01722
01723
01724
01725
01726 if (size < 0 || size >= kBufferSize) {
01727 return String("<formatting error or buffer exceeded>");
01728 } else {
01729 return String(buffer, size);
01730 }
01731 }
01732
01733
01734
01735 String StringStreamToString(::std::stringstream* ss) {
01736 const ::std::string& str = ss->str();
01737 const char* const start = str.c_str();
01738 const char* const end = start + str.length();
01739
01740
01741
01742 ::std::stringstream helper;
01743 for (const char* ch = start; ch != end; ++ch) {
01744 if (*ch == '\0') {
01745 helper << "\\0";
01746 } else {
01747 helper.put(*ch);
01748 }
01749 }
01750
01751 return String(helper.str().c_str());
01752 }
01753
01754
01755 String AppendUserMessage(const String& gtest_msg,
01756 const Message& user_msg) {
01757
01758 const String user_msg_string = user_msg.GetString();
01759 if (user_msg_string.empty()) {
01760 return gtest_msg;
01761 }
01762
01763 Message msg;
01764 msg << gtest_msg << "\n" << user_msg_string;
01765
01766 return msg.GetString();
01767 }
01768
01769 }
01770
01771
01772
01773
01774 TestResult::TestResult()
01775 : death_test_count_(0),
01776 elapsed_time_(0) {
01777 }
01778
01779
01780 TestResult::~TestResult() {
01781 }
01782
01783
01784
01785
01786 const TestPartResult& TestResult::GetTestPartResult(int i) const {
01787 if (i < 0 || i >= total_part_count())
01788 internal::posix::Abort();
01789 return test_part_results_.at(i);
01790 }
01791
01792
01793
01794
01795 const TestProperty& TestResult::GetTestProperty(int i) const {
01796 if (i < 0 || i >= test_property_count())
01797 internal::posix::Abort();
01798 return test_properties_.at(i);
01799 }
01800
01801
01802 void TestResult::ClearTestPartResults() {
01803 test_part_results_.clear();
01804 }
01805
01806
01807 void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
01808 test_part_results_.push_back(test_part_result);
01809 }
01810
01811
01812
01813
01814 void TestResult::RecordProperty(const TestProperty& test_property) {
01815 if (!ValidateTestProperty(test_property)) {
01816 return;
01817 }
01818 internal::MutexLock lock(&test_properites_mutex_);
01819 const std::vector<TestProperty>::iterator property_with_matching_key =
01820 std::find_if(test_properties_.begin(), test_properties_.end(),
01821 internal::TestPropertyKeyIs(test_property.key()));
01822 if (property_with_matching_key == test_properties_.end()) {
01823 test_properties_.push_back(test_property);
01824 return;
01825 }
01826 property_with_matching_key->SetValue(test_property.value());
01827 }
01828
01829
01830
01831 bool TestResult::ValidateTestProperty(const TestProperty& test_property) {
01832 internal::String key(test_property.key());
01833 if (key == "name" || key == "status" || key == "time" || key == "classname") {
01834 ADD_FAILURE()
01835 << "Reserved key used in RecordProperty(): "
01836 << key
01837 << " ('name', 'status', 'time', and 'classname' are reserved by "
01838 << GTEST_NAME_ << ")";
01839 return false;
01840 }
01841 return true;
01842 }
01843
01844
01845 void TestResult::Clear() {
01846 test_part_results_.clear();
01847 test_properties_.clear();
01848 death_test_count_ = 0;
01849 elapsed_time_ = 0;
01850 }
01851
01852
01853 bool TestResult::Failed() const {
01854 for (int i = 0; i < total_part_count(); ++i) {
01855 if (GetTestPartResult(i).failed())
01856 return true;
01857 }
01858 return false;
01859 }
01860
01861
01862 static bool TestPartFatallyFailed(const TestPartResult& result) {
01863 return result.fatally_failed();
01864 }
01865
01866
01867 bool TestResult::HasFatalFailure() const {
01868 return CountIf(test_part_results_, TestPartFatallyFailed) > 0;
01869 }
01870
01871
01872 static bool TestPartNonfatallyFailed(const TestPartResult& result) {
01873 return result.nonfatally_failed();
01874 }
01875
01876
01877 bool TestResult::HasNonfatalFailure() const {
01878 return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0;
01879 }
01880
01881
01882
01883 int TestResult::total_part_count() const {
01884 return static_cast<int>(test_part_results_.size());
01885 }
01886
01887
01888 int TestResult::test_property_count() const {
01889 return static_cast<int>(test_properties_.size());
01890 }
01891
01892
01893
01894
01895
01896
01897 Test::Test()
01898 : gtest_flag_saver_(new internal::GTestFlagSaver) {
01899 }
01900
01901
01902 Test::~Test() {
01903 delete gtest_flag_saver_;
01904 }
01905
01906
01907
01908
01909 void Test::SetUp() {
01910 }
01911
01912
01913
01914
01915 void Test::TearDown() {
01916 }
01917
01918
01919 void Test::RecordProperty(const char* key, const char* value) {
01920 UnitTest::GetInstance()->RecordPropertyForCurrentTest(key, value);
01921 }
01922
01923
01924 void Test::RecordProperty(const char* key, int value) {
01925 Message value_message;
01926 value_message << value;
01927 RecordProperty(key, value_message.GetString().c_str());
01928 }
01929
01930 namespace internal {
01931
01932 void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
01933 const String& message) {
01934
01935
01936 UnitTest::GetInstance()->AddTestPartResult(
01937 result_type,
01938 NULL,
01939 -1,
01940 message,
01941 String());
01942 }
01943
01944 }
01945
01946
01947
01948
01949
01950
01951 bool Test::HasSameFixtureClass() {
01952 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
01953 const TestCase* const test_case = impl->current_test_case();
01954
01955
01956 const TestInfo* const first_test_info = test_case->test_info_list()[0];
01957 const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_;
01958 const char* const first_test_name = first_test_info->name();
01959
01960
01961 const TestInfo* const this_test_info = impl->current_test_info();
01962 const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_;
01963 const char* const this_test_name = this_test_info->name();
01964
01965 if (this_fixture_id != first_fixture_id) {
01966
01967 const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();
01968
01969 const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();
01970
01971 if (first_is_TEST || this_is_TEST) {
01972
01973
01974
01975
01976
01977
01978 const char* const TEST_name =
01979 first_is_TEST ? first_test_name : this_test_name;
01980 const char* const TEST_F_name =
01981 first_is_TEST ? this_test_name : first_test_name;
01982
01983 ADD_FAILURE()
01984 << "All tests in the same test case must use the same test fixture\n"
01985 << "class, so mixing TEST_F and TEST in the same test case is\n"
01986 << "illegal. In test case " << this_test_info->test_case_name()
01987 << ",\n"
01988 << "test " << TEST_F_name << " is defined using TEST_F but\n"
01989 << "test " << TEST_name << " is defined using TEST. You probably\n"
01990 << "want to change the TEST to TEST_F or move it to another test\n"
01991 << "case.";
01992 } else {
01993
01994
01995 ADD_FAILURE()
01996 << "All tests in the same test case must use the same test fixture\n"
01997 << "class. However, in test case "
01998 << this_test_info->test_case_name() << ",\n"
01999 << "you defined test " << first_test_name
02000 << " and test " << this_test_name << "\n"
02001 << "using two different test fixture classes. This can happen if\n"
02002 << "the two classes are from different namespaces or translation\n"
02003 << "units and have the same name. You should probably rename one\n"
02004 << "of the classes to put the tests into different test cases.";
02005 }
02006 return false;
02007 }
02008
02009 return true;
02010 }
02011
02012 #if GTEST_HAS_SEH
02013
02014
02015
02016
02017
02018 static internal::String* FormatSehExceptionMessage(DWORD exception_code,
02019 const char* location) {
02020 Message message;
02021 message << "SEH exception with code 0x" << std::setbase(16) <<
02022 exception_code << std::setbase(10) << " thrown in " << location << ".";
02023
02024 return new internal::String(message.GetString());
02025 }
02026
02027 #endif // GTEST_HAS_SEH
02028
02029 #if GTEST_HAS_EXCEPTIONS
02030
02031
02032 static internal::String FormatCxxExceptionMessage(const char* description,
02033 const char* location) {
02034 Message message;
02035 if (description != NULL) {
02036 message << "C++ exception with description \"" << description << "\"";
02037 } else {
02038 message << "Unknown C++ exception";
02039 }
02040 message << " thrown in " << location << ".";
02041
02042 return message.GetString();
02043 }
02044
02045 static internal::String PrintTestPartResultToString(
02046 const TestPartResult& test_part_result);
02047
02048
02049
02050
02051
02052
02053
02054 class GoogleTestFailureException : public ::std::runtime_error {
02055 public:
02056 explicit GoogleTestFailureException(const TestPartResult& failure)
02057 : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
02058 };
02059 #endif // GTEST_HAS_EXCEPTIONS
02060
02061 namespace internal {
02062
02063
02064
02065
02066
02067
02068
02069
02070 template <class T, typename Result>
02071 Result HandleSehExceptionsInMethodIfSupported(
02072 T* object, Result (T::*method)(), const char* location) {
02073 #if GTEST_HAS_SEH
02074 __try {
02075 return (object->*method)();
02076 } __except (internal::UnitTestOptions::GTestShouldProcessSEH(
02077 GetExceptionCode())) {
02078
02079
02080
02081 internal::String* exception_message = FormatSehExceptionMessage(
02082 GetExceptionCode(), location);
02083 internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
02084 *exception_message);
02085 delete exception_message;
02086 return static_cast<Result>(0);
02087 }
02088 #else
02089 (void)location;
02090 return (object->*method)();
02091 #endif // GTEST_HAS_SEH
02092 }
02093
02094
02095
02096
02097 template <class T, typename Result>
02098 Result HandleExceptionsInMethodIfSupported(
02099 T* object, Result (T::*method)(), const char* location) {
02100
02101
02102
02103
02104
02105
02106
02107
02108
02109
02110
02111
02112
02113
02114
02115
02116
02117
02118
02119
02120
02121
02122
02123 if (internal::GetUnitTestImpl()->catch_exceptions()) {
02124 #if GTEST_HAS_EXCEPTIONS
02125 try {
02126 return HandleSehExceptionsInMethodIfSupported(object, method, location);
02127 } catch (const GoogleTestFailureException&) {
02128
02129
02130 throw;
02131 } catch (const std::exception& e) {
02132 internal::ReportFailureInUnknownLocation(
02133 TestPartResult::kFatalFailure,
02134 FormatCxxExceptionMessage(e.what(), location));
02135 } catch (...) {
02136 internal::ReportFailureInUnknownLocation(
02137 TestPartResult::kFatalFailure,
02138 FormatCxxExceptionMessage(NULL, location));
02139 }
02140 return static_cast<Result>(0);
02141 #else
02142 return HandleSehExceptionsInMethodIfSupported(object, method, location);
02143 #endif // GTEST_HAS_EXCEPTIONS
02144 } else {
02145 return (object->*method)();
02146 }
02147 }
02148
02149 }
02150
02151
02152 void Test::Run() {
02153 if (!HasSameFixtureClass()) return;
02154
02155 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
02156 impl->os_stack_trace_getter()->UponLeavingGTest();
02157 internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()");
02158
02159 if (!HasFatalFailure()) {
02160 impl->os_stack_trace_getter()->UponLeavingGTest();
02161 internal::HandleExceptionsInMethodIfSupported(
02162 this, &Test::TestBody, "the test body");
02163 }
02164
02165
02166
02167
02168 impl->os_stack_trace_getter()->UponLeavingGTest();
02169 internal::HandleExceptionsInMethodIfSupported(
02170 this, &Test::TearDown, "TearDown()");
02171 }
02172
02173
02174 bool Test::HasFatalFailure() {
02175 return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
02176 }
02177
02178
02179 bool Test::HasNonfatalFailure() {
02180 return internal::GetUnitTestImpl()->current_test_result()->
02181 HasNonfatalFailure();
02182 }
02183
02184
02185
02186
02187
02188
02189
02190 TestInfo::TestInfo(const char* a_test_case_name,
02191 const char* a_name,
02192 const char* a_type_param,
02193 const char* a_value_param,
02194 internal::TypeId fixture_class_id,
02195 internal::TestFactoryBase* factory)
02196 : test_case_name_(a_test_case_name),
02197 name_(a_name),
02198 type_param_(a_type_param ? new std::string(a_type_param) : NULL),
02199 value_param_(a_value_param ? new std::string(a_value_param) : NULL),
02200 fixture_class_id_(fixture_class_id),
02201 should_run_(false),
02202 is_disabled_(false),
02203 matches_filter_(false),
02204 factory_(factory),
02205 result_() {}
02206
02207
02208 TestInfo::~TestInfo() { delete factory_; }
02209
02210 namespace internal {
02211
02212
02213
02214
02215
02216
02217
02218
02219
02220
02221
02222
02223
02224
02225
02226
02227
02228
02229 TestInfo* MakeAndRegisterTestInfo(
02230 const char* test_case_name, const char* name,
02231 const char* type_param,
02232 const char* value_param,
02233 TypeId fixture_class_id,
02234 SetUpTestCaseFunc set_up_tc,
02235 TearDownTestCaseFunc tear_down_tc,
02236 TestFactoryBase* factory) {
02237 TestInfo* const test_info =
02238 new TestInfo(test_case_name, name, type_param, value_param,
02239 fixture_class_id, factory);
02240 GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
02241 return test_info;
02242 }
02243
02244 #if GTEST_HAS_PARAM_TEST
02245 void ReportInvalidTestCaseType(const char* test_case_name,
02246 const char* file, int line) {
02247 Message errors;
02248 errors
02249 << "Attempted redefinition of test case " << test_case_name << ".\n"
02250 << "All tests in the same test case must use the same test fixture\n"
02251 << "class. However, in test case " << test_case_name << ", you tried\n"
02252 << "to define a test using a fixture class different from the one\n"
02253 << "used earlier. This can happen if the two fixture classes are\n"
02254 << "from different namespaces and have the same name. You should\n"
02255 << "probably rename one of the classes to put the tests into different\n"
02256 << "test cases.";
02257
02258 fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
02259 errors.GetString().c_str());
02260 }
02261 #endif // GTEST_HAS_PARAM_TEST
02262
02263 }
02264
02265 namespace {
02266
02267
02268
02269
02270
02271
02272
02273
02274
02275 class TestNameIs {
02276 public:
02277
02278
02279
02280 explicit TestNameIs(const char* name)
02281 : name_(name) {}
02282
02283
02284 bool operator()(const TestInfo * test_info) const {
02285 return test_info && internal::String(test_info->name()).Compare(name_) == 0;
02286 }
02287
02288 private:
02289 internal::String name_;
02290 };
02291
02292 }
02293
02294 namespace internal {
02295
02296
02297
02298
02299 void UnitTestImpl::RegisterParameterizedTests() {
02300 #if GTEST_HAS_PARAM_TEST
02301 if (!parameterized_tests_registered_) {
02302 parameterized_test_registry_.RegisterTests();
02303 parameterized_tests_registered_ = true;
02304 }
02305 #endif
02306 }
02307
02308 }
02309
02310
02311
02312 void TestInfo::Run() {
02313 if (!should_run_) return;
02314
02315
02316 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
02317 impl->set_current_test_info(this);
02318
02319 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
02320
02321
02322 repeater->OnTestStart(*this);
02323
02324 const TimeInMillis start = internal::GetTimeInMillis();
02325
02326 impl->os_stack_trace_getter()->UponLeavingGTest();
02327
02328
02329 Test* const test = internal::HandleExceptionsInMethodIfSupported(
02330 factory_, &internal::TestFactoryBase::CreateTest,
02331 "the test fixture's constructor");
02332
02333
02334
02335 if ((test != NULL) && !Test::HasFatalFailure()) {
02336
02337
02338 test->Run();
02339 }
02340
02341
02342 impl->os_stack_trace_getter()->UponLeavingGTest();
02343 internal::HandleExceptionsInMethodIfSupported(
02344 test, &Test::DeleteSelf_, "the test fixture's destructor");
02345
02346 result_.set_elapsed_time(internal::GetTimeInMillis() - start);
02347
02348
02349 repeater->OnTestEnd(*this);
02350
02351
02352
02353 impl->set_current_test_info(NULL);
02354 }
02355
02356
02357
02358
02359 int TestCase::successful_test_count() const {
02360 return CountIf(test_info_list_, TestPassed);
02361 }
02362
02363
02364 int TestCase::failed_test_count() const {
02365 return CountIf(test_info_list_, TestFailed);
02366 }
02367
02368 int TestCase::disabled_test_count() const {
02369 return CountIf(test_info_list_, TestDisabled);
02370 }
02371
02372
02373 int TestCase::test_to_run_count() const {
02374 return CountIf(test_info_list_, ShouldRunTest);
02375 }
02376
02377
02378 int TestCase::total_test_count() const {
02379 return static_cast<int>(test_info_list_.size());
02380 }
02381
02382
02383
02384
02385
02386
02387
02388
02389
02390
02391 TestCase::TestCase(const char* a_name, const char* a_type_param,
02392 Test::SetUpTestCaseFunc set_up_tc,
02393 Test::TearDownTestCaseFunc tear_down_tc)
02394 : name_(a_name),
02395 type_param_(a_type_param ? new std::string(a_type_param) : NULL),
02396 set_up_tc_(set_up_tc),
02397 tear_down_tc_(tear_down_tc),
02398 should_run_(false),
02399 elapsed_time_(0) {
02400 }
02401
02402
02403 TestCase::~TestCase() {
02404
02405 ForEach(test_info_list_, internal::Delete<TestInfo>);
02406 }
02407
02408
02409
02410 const TestInfo* TestCase::GetTestInfo(int i) const {
02411 const int index = GetElementOr(test_indices_, i, -1);
02412 return index < 0 ? NULL : test_info_list_[index];
02413 }
02414
02415
02416
02417 TestInfo* TestCase::GetMutableTestInfo(int i) {
02418 const int index = GetElementOr(test_indices_, i, -1);
02419 return index < 0 ? NULL : test_info_list_[index];
02420 }
02421
02422
02423
02424 void TestCase::AddTestInfo(TestInfo * test_info) {
02425 test_info_list_.push_back(test_info);
02426 test_indices_.push_back(static_cast<int>(test_indices_.size()));
02427 }
02428
02429
02430 void TestCase::Run() {
02431 if (!should_run_) return;
02432
02433 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
02434 impl->set_current_test_case(this);
02435
02436 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
02437
02438 repeater->OnTestCaseStart(*this);
02439 impl->os_stack_trace_getter()->UponLeavingGTest();
02440 internal::HandleExceptionsInMethodIfSupported(
02441 this, &TestCase::RunSetUpTestCase, "SetUpTestCase()");
02442
02443 const internal::TimeInMillis start = internal::GetTimeInMillis();
02444 for (int i = 0; i < total_test_count(); i++) {
02445 GetMutableTestInfo(i)->Run();
02446 }
02447 elapsed_time_ = internal::GetTimeInMillis() - start;
02448
02449 impl->os_stack_trace_getter()->UponLeavingGTest();
02450 internal::HandleExceptionsInMethodIfSupported(
02451 this, &TestCase::RunTearDownTestCase, "TearDownTestCase()");
02452
02453 repeater->OnTestCaseEnd(*this);
02454 impl->set_current_test_case(NULL);
02455 }
02456
02457
02458 void TestCase::ClearResult() {
02459 ForEach(test_info_list_, TestInfo::ClearTestResult);
02460 }
02461
02462
02463 void TestCase::ShuffleTests(internal::Random* random) {
02464 Shuffle(random, &test_indices_);
02465 }
02466
02467
02468 void TestCase::UnshuffleTests() {
02469 for (size_t i = 0; i < test_indices_.size(); i++) {
02470 test_indices_[i] = static_cast<int>(i);
02471 }
02472 }
02473
02474
02475
02476
02477
02478
02479 static internal::String FormatCountableNoun(int count,
02480 const char * singular_form,
02481 const char * plural_form) {
02482 return internal::String::Format("%d %s", count,
02483 count == 1 ? singular_form : plural_form);
02484 }
02485
02486
02487 static internal::String FormatTestCount(int test_count) {
02488 return FormatCountableNoun(test_count, "test", "tests");
02489 }
02490
02491
02492 static internal::String FormatTestCaseCount(int test_case_count) {
02493 return FormatCountableNoun(test_case_count, "test case", "test cases");
02494 }
02495
02496
02497
02498
02499
02500 static const char * TestPartResultTypeToString(TestPartResult::Type type) {
02501 switch (type) {
02502 case TestPartResult::kSuccess:
02503 return "Success";
02504
02505 case TestPartResult::kNonFatalFailure:
02506 case TestPartResult::kFatalFailure:
02507 #ifdef _MSC_VER
02508 return "error: ";
02509 #else
02510 return "Failure\n";
02511 #endif
02512 default:
02513 return "Unknown result type";
02514 }
02515 }
02516
02517
02518 static internal::String PrintTestPartResultToString(
02519 const TestPartResult& test_part_result) {
02520 return (Message()
02521 << internal::FormatFileLocation(test_part_result.file_name(),
02522 test_part_result.line_number())
02523 << " " << TestPartResultTypeToString(test_part_result.type())
02524 << test_part_result.message()).GetString();
02525 }
02526
02527
02528 static void PrintTestPartResult(const TestPartResult& test_part_result) {
02529 const internal::String& result =
02530 PrintTestPartResultToString(test_part_result);
02531 printf("%s\n", result.c_str());
02532 fflush(stdout);
02533
02534
02535
02536
02537 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
02538
02539
02540
02541 ::OutputDebugStringA(result.c_str());
02542 ::OutputDebugStringA("\n");
02543 #endif
02544 }
02545
02546
02547
02548 namespace internal {
02549
02550 enum GTestColor {
02551 COLOR_DEFAULT,
02552 COLOR_RED,
02553 COLOR_GREEN,
02554 COLOR_YELLOW
02555 };
02556
02557 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
02558
02559
02560 WORD GetColorAttribute(GTestColor color) {
02561 switch (color) {
02562 case COLOR_RED: return FOREGROUND_RED;
02563 case COLOR_GREEN: return FOREGROUND_GREEN;
02564 case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
02565 default: return 0;
02566 }
02567 }
02568
02569 #else
02570
02571
02572
02573 const char* GetAnsiColorCode(GTestColor color) {
02574 switch (color) {
02575 case COLOR_RED: return "1";
02576 case COLOR_GREEN: return "2";
02577 case COLOR_YELLOW: return "3";
02578 default: return NULL;
02579 };
02580 }
02581
02582 #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
02583
02584
02585 bool ShouldUseColor(bool stdout_is_tty) {
02586 const char* const gtest_color = GTEST_FLAG(color).c_str();
02587
02588 if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
02589 #if GTEST_OS_WINDOWS
02590
02591
02592 return stdout_is_tty;
02593 #else
02594
02595 const char* const term = posix::GetEnv("TERM");
02596 const bool term_supports_color =
02597 String::CStringEquals(term, "xterm") ||
02598 String::CStringEquals(term, "xterm-color") ||
02599 String::CStringEquals(term, "xterm-256color") ||
02600 String::CStringEquals(term, "screen") ||
02601 String::CStringEquals(term, "linux") ||
02602 String::CStringEquals(term, "cygwin");
02603 return stdout_is_tty && term_supports_color;
02604 #endif // GTEST_OS_WINDOWS
02605 }
02606
02607 return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
02608 String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
02609 String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
02610 String::CStringEquals(gtest_color, "1");
02611
02612
02613
02614 }
02615
02616
02617
02618
02619
02620 void ColoredPrintf(GTestColor color, const char* fmt, ...) {
02621 va_list args;
02622 va_start(args, fmt);
02623
02624 #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
02625 const bool use_color = false;
02626 #else
02627 static const bool in_color_mode =
02628 ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
02629 const bool use_color = in_color_mode && (color != COLOR_DEFAULT);
02630 #endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
02631
02632
02633 if (!use_color) {
02634 vprintf(fmt, args);
02635 va_end(args);
02636 return;
02637 }
02638
02639 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
02640 const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
02641
02642
02643 CONSOLE_SCREEN_BUFFER_INFO buffer_info;
02644 GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
02645 const WORD old_color_attrs = buffer_info.wAttributes;
02646
02647
02648
02649
02650 fflush(stdout);
02651 SetConsoleTextAttribute(stdout_handle,
02652 GetColorAttribute(color) | FOREGROUND_INTENSITY);
02653 vprintf(fmt, args);
02654
02655 fflush(stdout);
02656
02657 SetConsoleTextAttribute(stdout_handle, old_color_attrs);
02658 #else
02659 printf("\033[0;3%sm", GetAnsiColorCode(color));
02660 vprintf(fmt, args);
02661 printf("\033[m");
02662 #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
02663 va_end(args);
02664 }
02665
02666 void PrintFullTestCommentIfPresent(const TestInfo& test_info) {
02667 const char* const type_param = test_info.type_param();
02668 const char* const value_param = test_info.value_param();
02669
02670 if (type_param != NULL || value_param != NULL) {
02671 printf(", where ");
02672 if (type_param != NULL) {
02673 printf("TypeParam = %s", type_param);
02674 if (value_param != NULL)
02675 printf(" and ");
02676 }
02677 if (value_param != NULL) {
02678 printf("GetParam() = %s", value_param);
02679 }
02680 }
02681 }
02682
02683
02684
02685
02686 class PrettyUnitTestResultPrinter : public TestEventListener {
02687 public:
02688 PrettyUnitTestResultPrinter() {}
02689 static void PrintTestName(const char * test_case, const char * test) {
02690 printf("%s.%s", test_case, test);
02691 }
02692
02693
02694 virtual void OnTestProgramStart(const UnitTest& ) {}
02695 virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
02696 virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
02697 virtual void OnEnvironmentsSetUpEnd(const UnitTest& ) {}
02698 virtual void OnTestCaseStart(const TestCase& test_case);
02699 virtual void OnTestStart(const TestInfo& test_info);
02700 virtual void OnTestPartResult(const TestPartResult& result);
02701 virtual void OnTestEnd(const TestInfo& test_info);
02702 virtual void OnTestCaseEnd(const TestCase& test_case);
02703 virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
02704 virtual void OnEnvironmentsTearDownEnd(const UnitTest& ) {}
02705 virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
02706 virtual void OnTestProgramEnd(const UnitTest& ) {}
02707
02708 private:
02709 static void PrintFailedTests(const UnitTest& unit_test);
02710
02711 internal::String test_case_name_;
02712 };
02713
02714
02715 void PrettyUnitTestResultPrinter::OnTestIterationStart(
02716 const UnitTest& unit_test, int iteration) {
02717 if (GTEST_FLAG(repeat) != 1)
02718 printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
02719
02720 const char* const filter = GTEST_FLAG(filter).c_str();
02721
02722
02723
02724 if (!internal::String::CStringEquals(filter, kUniversalFilter)) {
02725 ColoredPrintf(COLOR_YELLOW,
02726 "Note: %s filter = %s\n", GTEST_NAME_, filter);
02727 }
02728
02729 if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
02730 const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
02731 ColoredPrintf(COLOR_YELLOW,
02732 "Note: This is test shard %d of %s.\n",
02733 static_cast<int>(shard_index) + 1,
02734 internal::posix::GetEnv(kTestTotalShards));
02735 }
02736
02737 if (GTEST_FLAG(shuffle)) {
02738 ColoredPrintf(COLOR_YELLOW,
02739 "Note: Randomizing tests' orders with a seed of %d .\n",
02740 unit_test.random_seed());
02741 }
02742
02743 ColoredPrintf(COLOR_GREEN, "[==========] ");
02744 printf("Running %s from %s.\n",
02745 FormatTestCount(unit_test.test_to_run_count()).c_str(),
02746 FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
02747 fflush(stdout);
02748 }
02749
02750 void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
02751 const UnitTest& ) {
02752 ColoredPrintf(COLOR_GREEN, "[----------] ");
02753 printf("Global test environment set-up.\n");
02754 fflush(stdout);
02755 }
02756
02757 void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {
02758 test_case_name_ = test_case.name();
02759 const internal::String counts =
02760 FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
02761 ColoredPrintf(COLOR_GREEN, "[----------] ");
02762 printf("%s from %s", counts.c_str(), test_case_name_.c_str());
02763 if (test_case.type_param() == NULL) {
02764 printf("\n");
02765 } else {
02766 printf(", where TypeParam = %s\n", test_case.type_param());
02767 }
02768 fflush(stdout);
02769 }
02770
02771 void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
02772 ColoredPrintf(COLOR_GREEN, "[ RUN ] ");
02773 PrintTestName(test_case_name_.c_str(), test_info.name());
02774 printf("\n");
02775 fflush(stdout);
02776 }
02777
02778
02779 void PrettyUnitTestResultPrinter::OnTestPartResult(
02780 const TestPartResult& result) {
02781
02782 if (result.type() == TestPartResult::kSuccess)
02783 return;
02784
02785
02786 PrintTestPartResult(result);
02787 fflush(stdout);
02788 }
02789
02790 void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
02791 if (test_info.result()->Passed()) {
02792 ColoredPrintf(COLOR_GREEN, "[ OK ] ");
02793 } else {
02794 ColoredPrintf(COLOR_RED, "[ FAILED ] ");
02795 }
02796 PrintTestName(test_case_name_.c_str(), test_info.name());
02797 if (test_info.result()->Failed())
02798 PrintFullTestCommentIfPresent(test_info);
02799
02800 if (GTEST_FLAG(print_time)) {
02801 printf(" (%s ms)\n", internal::StreamableToString(
02802 test_info.result()->elapsed_time()).c_str());
02803 } else {
02804 printf("\n");
02805 }
02806 fflush(stdout);
02807 }
02808
02809 void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {
02810 if (!GTEST_FLAG(print_time)) return;
02811
02812 test_case_name_ = test_case.name();
02813 const internal::String counts =
02814 FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
02815 ColoredPrintf(COLOR_GREEN, "[----------] ");
02816 printf("%s from %s (%s ms total)\n\n",
02817 counts.c_str(), test_case_name_.c_str(),
02818 internal::StreamableToString(test_case.elapsed_time()).c_str());
02819 fflush(stdout);
02820 }
02821
02822 void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
02823 const UnitTest& ) {
02824 ColoredPrintf(COLOR_GREEN, "[----------] ");
02825 printf("Global test environment tear-down\n");
02826 fflush(stdout);
02827 }
02828
02829
02830 void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
02831 const int failed_test_count = unit_test.failed_test_count();
02832 if (failed_test_count == 0) {
02833 return;
02834 }
02835
02836 for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
02837 const TestCase& test_case = *unit_test.GetTestCase(i);
02838 if (!test_case.should_run() || (test_case.failed_test_count() == 0)) {
02839 continue;
02840 }
02841 for (int j = 0; j < test_case.total_test_count(); ++j) {
02842 const TestInfo& test_info = *test_case.GetTestInfo(j);
02843 if (!test_info.should_run() || test_info.result()->Passed()) {
02844 continue;
02845 }
02846 ColoredPrintf(COLOR_RED, "[ FAILED ] ");
02847 printf("%s.%s", test_case.name(), test_info.name());
02848 PrintFullTestCommentIfPresent(test_info);
02849 printf("\n");
02850 }
02851 }
02852 }
02853
02854 void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
02855 int ) {
02856 ColoredPrintf(COLOR_GREEN, "[==========] ");
02857 printf("%s from %s ran.",
02858 FormatTestCount(unit_test.test_to_run_count()).c_str(),
02859 FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
02860 if (GTEST_FLAG(print_time)) {
02861 printf(" (%s ms total)",
02862 internal::StreamableToString(unit_test.elapsed_time()).c_str());
02863 }
02864 printf("\n");
02865 ColoredPrintf(COLOR_GREEN, "[ PASSED ] ");
02866 printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
02867
02868 int num_failures = unit_test.failed_test_count();
02869 if (!unit_test.Passed()) {
02870 const int failed_test_count = unit_test.failed_test_count();
02871 ColoredPrintf(COLOR_RED, "[ FAILED ] ");
02872 printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
02873 PrintFailedTests(unit_test);
02874 printf("\n%2d FAILED %s\n", num_failures,
02875 num_failures == 1 ? "TEST" : "TESTS");
02876 }
02877
02878 int num_disabled = unit_test.disabled_test_count();
02879 if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
02880 if (!num_failures) {
02881 printf("\n");
02882 }
02883 ColoredPrintf(COLOR_YELLOW,
02884 " YOU HAVE %d DISABLED %s\n\n",
02885 num_disabled,
02886 num_disabled == 1 ? "TEST" : "TESTS");
02887 }
02888
02889 fflush(stdout);
02890 }
02891
02892
02893
02894
02895
02896
02897 class TestEventRepeater : public TestEventListener {
02898 public:
02899 TestEventRepeater() : forwarding_enabled_(true) {}
02900 virtual ~TestEventRepeater();
02901 void Append(TestEventListener *listener);
02902 TestEventListener* Release(TestEventListener* listener);
02903
02904
02905
02906 bool forwarding_enabled() const { return forwarding_enabled_; }
02907 void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }
02908
02909 virtual void OnTestProgramStart(const UnitTest& unit_test);
02910 virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
02911 virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
02912 virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test);
02913 virtual void OnTestCaseStart(const TestCase& test_case);
02914 virtual void OnTestStart(const TestInfo& test_info);
02915 virtual void OnTestPartResult(const TestPartResult& result);
02916 virtual void OnTestEnd(const TestInfo& test_info);
02917 virtual void OnTestCaseEnd(const TestCase& test_case);
02918 virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
02919 virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test);
02920 virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
02921 virtual void OnTestProgramEnd(const UnitTest& unit_test);
02922
02923 private:
02924
02925
02926 bool forwarding_enabled_;
02927
02928 std::vector<TestEventListener*> listeners_;
02929
02930 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater);
02931 };
02932
02933 TestEventRepeater::~TestEventRepeater() {
02934 ForEach(listeners_, Delete<TestEventListener>);
02935 }
02936
02937 void TestEventRepeater::Append(TestEventListener *listener) {
02938 listeners_.push_back(listener);
02939 }
02940
02941
02942 TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {
02943 for (size_t i = 0; i < listeners_.size(); ++i) {
02944 if (listeners_[i] == listener) {
02945 listeners_.erase(listeners_.begin() + i);
02946 return listener;
02947 }
02948 }
02949
02950 return NULL;
02951 }
02952
02953
02954
02955 #define GTEST_REPEATER_METHOD_(Name, Type) \
02956 void TestEventRepeater::Name(const Type& parameter) { \
02957 if (forwarding_enabled_) { \
02958 for (size_t i = 0; i < listeners_.size(); i++) { \
02959 listeners_[i]->Name(parameter); \
02960 } \
02961 } \
02962 }
02963
02964
02965 #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
02966 void TestEventRepeater::Name(const Type& parameter) { \
02967 if (forwarding_enabled_) { \
02968 for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \
02969 listeners_[i]->Name(parameter); \
02970 } \
02971 } \
02972 }
02973
02974 GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)
02975 GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)
02976 GTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase)
02977 GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
02978 GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)
02979 GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)
02980 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)
02981 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)
02982 GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)
02983 GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestCase)
02984 GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)
02985
02986 #undef GTEST_REPEATER_METHOD_
02987 #undef GTEST_REVERSE_REPEATER_METHOD_
02988
02989 void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,
02990 int iteration) {
02991 if (forwarding_enabled_) {
02992 for (size_t i = 0; i < listeners_.size(); i++) {
02993 listeners_[i]->OnTestIterationStart(unit_test, iteration);
02994 }
02995 }
02996 }
02997
02998 void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,
02999 int iteration) {
03000 if (forwarding_enabled_) {
03001 for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) {
03002 listeners_[i]->OnTestIterationEnd(unit_test, iteration);
03003 }
03004 }
03005 }
03006
03007
03008
03009
03010 class XmlUnitTestResultPrinter : public EmptyTestEventListener {
03011 public:
03012 explicit XmlUnitTestResultPrinter(const char* output_file);
03013
03014 virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
03015
03016 private:
03017
03018
03019 static bool IsNormalizableWhitespace(char c) {
03020 return c == 0x9 || c == 0xA || c == 0xD;
03021 }
03022
03023
03024 static bool IsValidXmlCharacter(char c) {
03025 return IsNormalizableWhitespace(c) || c >= 0x20;
03026 }
03027
03028
03029
03030
03031
03032 static String EscapeXml(const char* str, bool is_attribute);
03033
03034
03035 static string RemoveInvalidXmlCharacters(const string& str);
03036
03037
03038 static String EscapeXmlAttribute(const char* str) {
03039 return EscapeXml(str, true);
03040 }
03041
03042
03043 static String EscapeXmlText(const char* str) { return EscapeXml(str, false); }
03044
03045
03046 static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
03047
03048
03049 static void OutputXmlTestInfo(::std::ostream* stream,
03050 const char* test_case_name,
03051 const TestInfo& test_info);
03052
03053
03054 static void PrintXmlTestCase(FILE* out, const TestCase& test_case);
03055
03056
03057 static void PrintXmlUnitTest(FILE* out, const UnitTest& unit_test);
03058
03059
03060
03061
03062
03063 static String TestPropertiesAsXmlAttributes(const TestResult& result);
03064
03065
03066 const String output_file_;
03067
03068 GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);
03069 };
03070
03071
03072 XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
03073 : output_file_(output_file) {
03074 if (output_file_.c_str() == NULL || output_file_.empty()) {
03075 fprintf(stderr, "XML output file may not be null\n");
03076 fflush(stderr);
03077 exit(EXIT_FAILURE);
03078 }
03079 }
03080
03081
03082 void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
03083 int ) {
03084 FILE* xmlout = NULL;
03085 FilePath output_file(output_file_);
03086 FilePath output_dir(output_file.RemoveFileName());
03087
03088 if (output_dir.CreateDirectoriesRecursively()) {
03089 xmlout = posix::FOpen(output_file_.c_str(), "w");
03090 }
03091 if (xmlout == NULL) {
03092
03093
03094
03095
03096
03097
03098
03099
03100
03101
03102 fprintf(stderr,
03103 "Unable to open file \"%s\"\n",
03104 output_file_.c_str());
03105 fflush(stderr);
03106 exit(EXIT_FAILURE);
03107 }
03108 PrintXmlUnitTest(xmlout, unit_test);
03109 fclose(xmlout);
03110 }
03111
03112
03113
03114
03115
03116
03117
03118
03119
03120
03121
03122
03123
03124 String XmlUnitTestResultPrinter::EscapeXml(const char* str, bool is_attribute) {
03125 Message m;
03126
03127 if (str != NULL) {
03128 for (const char* src = str; *src; ++src) {
03129 switch (*src) {
03130 case '<':
03131 m << "<";
03132 break;
03133 case '>':
03134 m << ">";
03135 break;
03136 case '&':
03137 m << "&";
03138 break;
03139 case '\'':
03140 if (is_attribute)
03141 m << "'";
03142 else
03143 m << '\'';
03144 break;
03145 case '"':
03146 if (is_attribute)
03147 m << """;
03148 else
03149 m << '"';
03150 break;
03151 default:
03152 if (IsValidXmlCharacter(*src)) {
03153 if (is_attribute && IsNormalizableWhitespace(*src))
03154 m << String::Format("&#x%02X;", unsigned(*src));
03155 else
03156 m << *src;
03157 }
03158 break;
03159 }
03160 }
03161 }
03162
03163 return m.GetString();
03164 }
03165
03166
03167
03168
03169 string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(const string& str) {
03170 string output;
03171 output.reserve(str.size());
03172 for (string::const_iterator it = str.begin(); it != str.end(); ++it)
03173 if (IsValidXmlCharacter(*it))
03174 output.push_back(*it);
03175
03176 return output;
03177 }
03178
03179
03180
03181
03182
03183
03184
03185
03186
03187
03188
03189
03190
03191
03192
03193
03194
03195
03196 std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {
03197 ::std::stringstream ss;
03198 ss << double (ms) / 1000.0;
03199 return ss.str();
03200 }
03201
03202
03203 void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
03204 const char* data) {
03205 const char* segment = data;
03206 *stream << "<![CDATA[";
03207 for (;;) {
03208 const char* const next_segment = strstr(segment, "]]>");
03209 if (next_segment != NULL) {
03210 stream->write(
03211 segment, static_cast<std::streamsize>(next_segment - segment));
03212 *stream << "]]>]]><![CDATA[";
03213 segment = next_segment + strlen("]]>");
03214 } else {
03215 *stream << segment;
03216 break;
03217 }
03218 }
03219 *stream << "]]>";
03220 }
03221
03222
03223
03224 void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
03225 const char* test_case_name,
03226 const TestInfo& test_info) {
03227 const TestResult& result = *test_info.result();
03228 *stream << " <testcase name=\""
03229 << EscapeXmlAttribute(test_info.name()).c_str() << "\"";
03230
03231 if (test_info.value_param() != NULL) {
03232 *stream << " value_param=\"" << EscapeXmlAttribute(test_info.value_param())
03233 << "\"";
03234 }
03235 if (test_info.type_param() != NULL) {
03236 *stream << " type_param=\"" << EscapeXmlAttribute(test_info.type_param())
03237 << "\"";
03238 }
03239
03240 *stream << " status=\""
03241 << (test_info.should_run() ? "run" : "notrun")
03242 << "\" time=\""
03243 << FormatTimeInMillisAsSeconds(result.elapsed_time())
03244 << "\" classname=\"" << EscapeXmlAttribute(test_case_name).c_str()
03245 << "\"" << TestPropertiesAsXmlAttributes(result).c_str();
03246
03247 int failures = 0;
03248 for (int i = 0; i < result.total_part_count(); ++i) {
03249 const TestPartResult& part = result.GetTestPartResult(i);
03250 if (part.failed()) {
03251 if (++failures == 1)
03252 *stream << ">\n";
03253 *stream << " <failure message=\""
03254 << EscapeXmlAttribute(part.summary()).c_str()
03255 << "\" type=\"\">";
03256 const string location = internal::FormatCompilerIndependentFileLocation(
03257 part.file_name(), part.line_number());
03258 const string message = location + "\n" + part.message();
03259 OutputXmlCDataSection(stream,
03260 RemoveInvalidXmlCharacters(message).c_str());
03261 *stream << "</failure>\n";
03262 }
03263 }
03264
03265 if (failures == 0)
03266 *stream << " />\n";
03267 else
03268 *stream << " </testcase>\n";
03269 }
03270
03271
03272 void XmlUnitTestResultPrinter::PrintXmlTestCase(FILE* out,
03273 const TestCase& test_case) {
03274 fprintf(out,
03275 " <testsuite name=\"%s\" tests=\"%d\" failures=\"%d\" "
03276 "disabled=\"%d\" ",
03277 EscapeXmlAttribute(test_case.name()).c_str(),
03278 test_case.total_test_count(),
03279 test_case.failed_test_count(),
03280 test_case.disabled_test_count());
03281 fprintf(out,
03282 "errors=\"0\" time=\"%s\">\n",
03283 FormatTimeInMillisAsSeconds(test_case.elapsed_time()).c_str());
03284 for (int i = 0; i < test_case.total_test_count(); ++i) {
03285 ::std::stringstream stream;
03286 OutputXmlTestInfo(&stream, test_case.name(), *test_case.GetTestInfo(i));
03287 fprintf(out, "%s", StringStreamToString(&stream).c_str());
03288 }
03289 fprintf(out, " </testsuite>\n");
03290 }
03291
03292
03293 void XmlUnitTestResultPrinter::PrintXmlUnitTest(FILE* out,
03294 const UnitTest& unit_test) {
03295 fprintf(out, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
03296 fprintf(out,
03297 "<testsuites tests=\"%d\" failures=\"%d\" disabled=\"%d\" "
03298 "errors=\"0\" time=\"%s\" ",
03299 unit_test.total_test_count(),
03300 unit_test.failed_test_count(),
03301 unit_test.disabled_test_count(),
03302 FormatTimeInMillisAsSeconds(unit_test.elapsed_time()).c_str());
03303 if (GTEST_FLAG(shuffle)) {
03304 fprintf(out, "random_seed=\"%d\" ", unit_test.random_seed());
03305 }
03306 fprintf(out, "name=\"AllTests\">\n");
03307 for (int i = 0; i < unit_test.total_test_case_count(); ++i)
03308 PrintXmlTestCase(out, *unit_test.GetTestCase(i));
03309 fprintf(out, "</testsuites>\n");
03310 }
03311
03312
03313
03314 String XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
03315 const TestResult& result) {
03316 Message attributes;
03317 for (int i = 0; i < result.test_property_count(); ++i) {
03318 const TestProperty& property = result.GetTestProperty(i);
03319 attributes << " " << property.key() << "="
03320 << "\"" << EscapeXmlAttribute(property.value()) << "\"";
03321 }
03322 return attributes.GetString();
03323 }
03324
03325
03326
03327 #if GTEST_CAN_STREAM_RESULTS_
03328
03329
03330 class StreamingListener : public EmptyTestEventListener {
03331 public:
03332
03333 static string UrlEncode(const char* str);
03334
03335 StreamingListener(const string& host, const string& port)
03336 : sockfd_(-1), host_name_(host), port_num_(port) {
03337 MakeConnection();
03338 Send("gtest_streaming_protocol_version=1.0\n");
03339 }
03340
03341 virtual ~StreamingListener() {
03342 if (sockfd_ != -1)
03343 CloseConnection();
03344 }
03345
03346 void OnTestProgramStart(const UnitTest& ) {
03347 Send("event=TestProgramStart\n");
03348 }
03349
03350 void OnTestProgramEnd(const UnitTest& unit_test) {
03351
03352
03353 Send(String::Format("event=TestProgramEnd&passed=%d\n",
03354 unit_test.Passed()));
03355
03356
03357 CloseConnection();
03358 }
03359
03360 void OnTestIterationStart(const UnitTest& , int iteration) {
03361 Send(String::Format("event=TestIterationStart&iteration=%d\n",
03362 iteration));
03363 }
03364
03365 void OnTestIterationEnd(const UnitTest& unit_test, int ) {
03366 Send(String::Format("event=TestIterationEnd&passed=%d&elapsed_time=%sms\n",
03367 unit_test.Passed(),
03368 StreamableToString(unit_test.elapsed_time()).c_str()));
03369 }
03370
03371 void OnTestCaseStart(const TestCase& test_case) {
03372 Send(String::Format("event=TestCaseStart&name=%s\n", test_case.name()));
03373 }
03374
03375 void OnTestCaseEnd(const TestCase& test_case) {
03376 Send(String::Format("event=TestCaseEnd&passed=%d&elapsed_time=%sms\n",
03377 test_case.Passed(),
03378 StreamableToString(test_case.elapsed_time()).c_str()));
03379 }
03380
03381 void OnTestStart(const TestInfo& test_info) {
03382 Send(String::Format("event=TestStart&name=%s\n", test_info.name()));
03383 }
03384
03385 void OnTestEnd(const TestInfo& test_info) {
03386 Send(String::Format(
03387 "event=TestEnd&passed=%d&elapsed_time=%sms\n",
03388 (test_info.result())->Passed(),
03389 StreamableToString((test_info.result())->elapsed_time()).c_str()));
03390 }
03391
03392 void OnTestPartResult(const TestPartResult& test_part_result) {
03393 const char* file_name = test_part_result.file_name();
03394 if (file_name == NULL)
03395 file_name = "";
03396 Send(String::Format("event=TestPartResult&file=%s&line=%d&message=",
03397 UrlEncode(file_name).c_str(),
03398 test_part_result.line_number()));
03399 Send(UrlEncode(test_part_result.message()) + "\n");
03400 }
03401
03402 private:
03403
03404 void MakeConnection();
03405
03406
03407 void CloseConnection() {
03408 GTEST_CHECK_(sockfd_ != -1)
03409 << "CloseConnection() can be called only when there is a connection.";
03410
03411 close(sockfd_);
03412 sockfd_ = -1;
03413 }
03414
03415
03416 void Send(const string& message) {
03417 GTEST_CHECK_(sockfd_ != -1)
03418 << "Send() can be called only when there is a connection.";
03419
03420 const int len = static_cast<int>(message.length());
03421 if (write(sockfd_, message.c_str(), len) != len) {
03422 GTEST_LOG_(WARNING)
03423 << "stream_result_to: failed to stream to "
03424 << host_name_ << ":" << port_num_;
03425 }
03426 }
03427
03428 int sockfd_;
03429 const string host_name_;
03430 const string port_num_;
03431
03432 GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener);
03433 };
03434
03435
03436
03437
03438
03439
03440 string StreamingListener::UrlEncode(const char* str) {
03441 string result;
03442 result.reserve(strlen(str) + 1);
03443 for (char ch = *str; ch != '\0'; ch = *++str) {
03444 switch (ch) {
03445 case '%':
03446 case '=':
03447 case '&':
03448 case '\n':
03449 result.append(String::Format("%%%02x", static_cast<unsigned char>(ch)));
03450 break;
03451 default:
03452 result.push_back(ch);
03453 break;
03454 }
03455 }
03456 return result;
03457 }
03458
03459 void StreamingListener::MakeConnection() {
03460 GTEST_CHECK_(sockfd_ == -1)
03461 << "MakeConnection() can't be called when there is already a connection.";
03462
03463 addrinfo hints;
03464 memset(&hints, 0, sizeof(hints));
03465 hints.ai_family = AF_UNSPEC;
03466 hints.ai_socktype = SOCK_STREAM;
03467 addrinfo* servinfo = NULL;
03468
03469
03470
03471 const int error_num = getaddrinfo(
03472 host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
03473 if (error_num != 0) {
03474 GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: "
03475 << gai_strerror(error_num);
03476 }
03477
03478
03479 for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != NULL;
03480 cur_addr = cur_addr->ai_next) {
03481 sockfd_ = socket(
03482 cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol);
03483 if (sockfd_ != -1) {
03484
03485 if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
03486 close(sockfd_);
03487 sockfd_ = -1;
03488 }
03489 }
03490 }
03491
03492 freeaddrinfo(servinfo);
03493
03494 if (sockfd_ == -1) {
03495 GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to "
03496 << host_name_ << ":" << port_num_;
03497 }
03498 }
03499
03500
03501 #endif // GTEST_CAN_STREAM_RESULTS__
03502
03503
03504
03505
03506
03507
03508 ScopedTrace::ScopedTrace(const char* file, int line, const Message& message) {
03509 TraceInfo trace;
03510 trace.file = file;
03511 trace.line = line;
03512 trace.message = message.GetString();
03513
03514 UnitTest::GetInstance()->PushGTestTrace(trace);
03515 }
03516
03517
03518
03519 ScopedTrace::~ScopedTrace() {
03520 UnitTest::GetInstance()->PopGTestTrace();
03521 }
03522
03523
03524
03525
03526
03527
03528
03529
03530
03531
03532
03533
03534
03535 String OsStackTraceGetter::CurrentStackTrace(int, int) {
03536 return String("");
03537 }
03538
03539
03540 void OsStackTraceGetter::UponLeavingGTest() {
03541 }
03542
03543 const char* const
03544 OsStackTraceGetter::kElidedFramesMarker =
03545 "... " GTEST_NAME_ " internal frames ...";
03546
03547 }
03548
03549
03550
03551 TestEventListeners::TestEventListeners()
03552 : repeater_(new internal::TestEventRepeater()),
03553 default_result_printer_(NULL),
03554 default_xml_generator_(NULL) {
03555 }
03556
03557 TestEventListeners::~TestEventListeners() { delete repeater_; }
03558
03559
03560
03561
03562
03563 void TestEventListeners::Append(TestEventListener* listener) {
03564 repeater_->Append(listener);
03565 }
03566
03567
03568
03569
03570 TestEventListener* TestEventListeners::Release(TestEventListener* listener) {
03571 if (listener == default_result_printer_)
03572 default_result_printer_ = NULL;
03573 else if (listener == default_xml_generator_)
03574 default_xml_generator_ = NULL;
03575 return repeater_->Release(listener);
03576 }
03577
03578
03579
03580 TestEventListener* TestEventListeners::repeater() { return repeater_; }
03581
03582
03583
03584
03585
03586
03587 void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
03588 if (default_result_printer_ != listener) {
03589
03590
03591 delete Release(default_result_printer_);
03592 default_result_printer_ = listener;
03593 if (listener != NULL)
03594 Append(listener);
03595 }
03596 }
03597
03598
03599
03600
03601
03602
03603 void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
03604 if (default_xml_generator_ != listener) {
03605
03606
03607 delete Release(default_xml_generator_);
03608 default_xml_generator_ = listener;
03609 if (listener != NULL)
03610 Append(listener);
03611 }
03612 }
03613
03614
03615
03616 bool TestEventListeners::EventForwardingEnabled() const {
03617 return repeater_->forwarding_enabled();
03618 }
03619
03620 void TestEventListeners::SuppressEventForwarding() {
03621 repeater_->set_forwarding_enabled(false);
03622 }
03623
03624
03625
03626
03627
03628
03629
03630
03631
03632
03633 UnitTest * UnitTest::GetInstance() {
03634
03635
03636
03637
03638
03639
03640
03641
03642
03643
03644
03645 #if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
03646 static UnitTest* const instance = new UnitTest;
03647 return instance;
03648 #else
03649 static UnitTest instance;
03650 return &instance;
03651 #endif // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
03652 }
03653
03654
03655 int UnitTest::successful_test_case_count() const {
03656 return impl()->successful_test_case_count();
03657 }
03658
03659
03660 int UnitTest::failed_test_case_count() const {
03661 return impl()->failed_test_case_count();
03662 }
03663
03664
03665 int UnitTest::total_test_case_count() const {
03666 return impl()->total_test_case_count();
03667 }
03668
03669
03670
03671 int UnitTest::test_case_to_run_count() const {
03672 return impl()->test_case_to_run_count();
03673 }
03674
03675
03676 int UnitTest::successful_test_count() const {
03677 return impl()->successful_test_count();
03678 }
03679
03680
03681 int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
03682
03683
03684 int UnitTest::disabled_test_count() const {
03685 return impl()->disabled_test_count();
03686 }
03687
03688
03689 int UnitTest::total_test_count() const { return impl()->total_test_count(); }
03690
03691
03692 int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
03693
03694
03695 internal::TimeInMillis UnitTest::elapsed_time() const {
03696 return impl()->elapsed_time();
03697 }
03698
03699
03700 bool UnitTest::Passed() const { return impl()->Passed(); }
03701
03702
03703
03704 bool UnitTest::Failed() const { return impl()->Failed(); }
03705
03706
03707
03708 const TestCase* UnitTest::GetTestCase(int i) const {
03709 return impl()->GetTestCase(i);
03710 }
03711
03712
03713
03714 TestCase* UnitTest::GetMutableTestCase(int i) {
03715 return impl()->GetMutableTestCase(i);
03716 }
03717
03718
03719
03720 TestEventListeners& UnitTest::listeners() {
03721 return *impl()->listeners();
03722 }
03723
03724
03725
03726
03727
03728
03729
03730
03731
03732
03733
03734 Environment* UnitTest::AddEnvironment(Environment* env) {
03735 if (env == NULL) {
03736 return NULL;
03737 }
03738
03739 impl_->environments().push_back(env);
03740 return env;
03741 }
03742
03743
03744
03745
03746
03747
03748 void UnitTest::AddTestPartResult(TestPartResult::Type result_type,
03749 const char* file_name,
03750 int line_number,
03751 const internal::String& message,
03752 const internal::String& os_stack_trace) {
03753 Message msg;
03754 msg << message;
03755
03756 internal::MutexLock lock(&mutex_);
03757 if (impl_->gtest_trace_stack().size() > 0) {
03758 msg << "\n" << GTEST_NAME_ << " trace:";
03759
03760 for (int i = static_cast<int>(impl_->gtest_trace_stack().size());
03761 i > 0; --i) {
03762 const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
03763 msg << "\n" << internal::FormatFileLocation(trace.file, trace.line)
03764 << " " << trace.message;
03765 }
03766 }
03767
03768 if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) {
03769 msg << internal::kStackTraceMarker << os_stack_trace;
03770 }
03771
03772 const TestPartResult result =
03773 TestPartResult(result_type, file_name, line_number,
03774 msg.GetString().c_str());
03775 impl_->GetTestPartResultReporterForCurrentThread()->
03776 ReportTestPartResult(result);
03777
03778 if (result_type != TestPartResult::kSuccess) {
03779
03780
03781
03782
03783
03784 if (GTEST_FLAG(break_on_failure)) {
03785 #if GTEST_OS_WINDOWS
03786
03787
03788
03789 DebugBreak();
03790 #else
03791
03792
03793
03794
03795 *static_cast<volatile int*>(NULL) = 1;
03796 #endif // GTEST_OS_WINDOWS
03797 } else if (GTEST_FLAG(throw_on_failure)) {
03798 #if GTEST_HAS_EXCEPTIONS
03799 throw GoogleTestFailureException(result);
03800 #else
03801
03802
03803 exit(1);
03804 #endif
03805 }
03806 }
03807 }
03808
03809
03810
03811 void UnitTest::RecordPropertyForCurrentTest(const char* key,
03812 const char* value) {
03813 const TestProperty test_property(key, value);
03814 impl_->current_test_result()->RecordProperty(test_property);
03815 }
03816
03817
03818
03819
03820
03821
03822 int UnitTest::Run() {
03823
03824
03825 impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions));
03826
03827 #if GTEST_HAS_SEH
03828 const bool in_death_test_child_process =
03829 internal::GTEST_FLAG(internal_run_death_test).length() > 0;
03830
03831
03832
03833
03834
03835 if (impl()->catch_exceptions() || in_death_test_child_process) {
03836
03837 # if !GTEST_OS_WINDOWS_MOBILE
03838
03839 SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
03840 SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
03841 # endif // !GTEST_OS_WINDOWS_MOBILE
03842
03843 # if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
03844
03845
03846
03847 _set_error_mode(_OUT_TO_STDERR);
03848 # endif
03849
03850 # if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
03851
03852
03853
03854
03855
03856
03857
03858
03859
03860
03861
03862 if (!GTEST_FLAG(break_on_failure))
03863 _set_abort_behavior(
03864 0x0,
03865 _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
03866 # endif
03867
03868 }
03869 #endif // GTEST_HAS_SEH
03870
03871 return internal::HandleExceptionsInMethodIfSupported(
03872 impl(),
03873 &internal::UnitTestImpl::RunAllTests,
03874 "auxiliary test code (environments or event listeners)") ? 0 : 1;
03875 }
03876
03877
03878
03879 const char* UnitTest::original_working_dir() const {
03880 return impl_->original_working_dir_.c_str();
03881 }
03882
03883
03884
03885
03886 const TestCase* UnitTest::current_test_case() const {
03887 internal::MutexLock lock(&mutex_);
03888 return impl_->current_test_case();
03889 }
03890
03891
03892
03893
03894 const TestInfo* UnitTest::current_test_info() const {
03895 internal::MutexLock lock(&mutex_);
03896 return impl_->current_test_info();
03897 }
03898
03899
03900 int UnitTest::random_seed() const { return impl_->random_seed(); }
03901
03902 #if GTEST_HAS_PARAM_TEST
03903
03904
03905
03906 internal::ParameterizedTestCaseRegistry&
03907 UnitTest::parameterized_test_registry() {
03908 return impl_->parameterized_test_registry();
03909 }
03910 #endif // GTEST_HAS_PARAM_TEST
03911
03912
03913 UnitTest::UnitTest() {
03914 impl_ = new internal::UnitTestImpl(this);
03915 }
03916
03917
03918 UnitTest::~UnitTest() {
03919 delete impl_;
03920 }
03921
03922
03923
03924
03925 void UnitTest::PushGTestTrace(const internal::TraceInfo& trace) {
03926 internal::MutexLock lock(&mutex_);
03927 impl_->gtest_trace_stack().push_back(trace);
03928 }
03929
03930
03931
03932 void UnitTest::PopGTestTrace() {
03933 internal::MutexLock lock(&mutex_);
03934 impl_->gtest_trace_stack().pop_back();
03935 }
03936
03937 namespace internal {
03938
03939 UnitTestImpl::UnitTestImpl(UnitTest* parent)
03940 : parent_(parent),
03941 #ifdef _MSC_VER
03942 # pragma warning(push)
03943 # pragma warning(disable:4355)
03944
03945 default_global_test_part_result_reporter_(this),
03946 default_per_thread_test_part_result_reporter_(this),
03947 # pragma warning(pop)
03948 #else
03949 default_global_test_part_result_reporter_(this),
03950 default_per_thread_test_part_result_reporter_(this),
03951 #endif
03952 global_test_part_result_repoter_(
03953 &default_global_test_part_result_reporter_),
03954 per_thread_test_part_result_reporter_(
03955 &default_per_thread_test_part_result_reporter_),
03956 #if GTEST_HAS_PARAM_TEST
03957 parameterized_test_registry_(),
03958 parameterized_tests_registered_(false),
03959 #endif
03960 last_death_test_case_(-1),
03961 current_test_case_(NULL),
03962 current_test_info_(NULL),
03963 ad_hoc_test_result_(),
03964 os_stack_trace_getter_(NULL),
03965 post_flag_parse_init_performed_(false),
03966 random_seed_(0),
03967 random_(0),
03968 elapsed_time_(0),
03969 #if GTEST_HAS_DEATH_TEST
03970 internal_run_death_test_flag_(NULL),
03971 death_test_factory_(new DefaultDeathTestFactory),
03972 #endif
03973
03974 catch_exceptions_(false) {
03975 listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);
03976 }
03977
03978 UnitTestImpl::~UnitTestImpl() {
03979
03980 ForEach(test_cases_, internal::Delete<TestCase>);
03981
03982
03983 ForEach(environments_, internal::Delete<Environment>);
03984
03985 delete os_stack_trace_getter_;
03986 }
03987
03988 #if GTEST_HAS_DEATH_TEST
03989
03990
03991 void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
03992 if (internal_run_death_test_flag_.get() != NULL)
03993 listeners()->SuppressEventForwarding();
03994 }
03995 #endif // GTEST_HAS_DEATH_TEST
03996
03997
03998
03999 void UnitTestImpl::ConfigureXmlOutput() {
04000 const String& output_format = UnitTestOptions::GetOutputFormat();
04001 if (output_format == "xml") {
04002 listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
04003 UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
04004 } else if (output_format != "") {
04005 printf("WARNING: unrecognized output format \"%s\" ignored.\n",
04006 output_format.c_str());
04007 fflush(stdout);
04008 }
04009 }
04010
04011 #if GTEST_CAN_STREAM_RESULTS_
04012
04013
04014 void UnitTestImpl::ConfigureStreamingOutput() {
04015 const string& target = GTEST_FLAG(stream_result_to);
04016 if (!target.empty()) {
04017 const size_t pos = target.find(':');
04018 if (pos != string::npos) {
04019 listeners()->Append(new StreamingListener(target.substr(0, pos),
04020 target.substr(pos+1)));
04021 } else {
04022 printf("WARNING: unrecognized streaming target \"%s\" ignored.\n",
04023 target.c_str());
04024 fflush(stdout);
04025 }
04026 }
04027 }
04028 #endif // GTEST_CAN_STREAM_RESULTS_
04029
04030
04031
04032
04033
04034
04035 void UnitTestImpl::PostFlagParsingInit() {
04036
04037 if (!post_flag_parse_init_performed_) {
04038 post_flag_parse_init_performed_ = true;
04039
04040 #if GTEST_HAS_DEATH_TEST
04041 InitDeathTestSubprocessControlInfo();
04042 SuppressTestEventsIfInSubprocess();
04043 #endif // GTEST_HAS_DEATH_TEST
04044
04045
04046
04047
04048 RegisterParameterizedTests();
04049
04050
04051
04052 ConfigureXmlOutput();
04053
04054 #if GTEST_CAN_STREAM_RESULTS_
04055
04056 ConfigureStreamingOutput();
04057 #endif // GTEST_CAN_STREAM_RESULTS_
04058 }
04059 }
04060
04061
04062
04063
04064
04065
04066
04067
04068
04069 class TestCaseNameIs {
04070 public:
04071
04072 explicit TestCaseNameIs(const String& name)
04073 : name_(name) {}
04074
04075
04076 bool operator()(const TestCase* test_case) const {
04077 return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0;
04078 }
04079
04080 private:
04081 String name_;
04082 };
04083
04084
04085
04086
04087
04088
04089
04090
04091
04092
04093
04094
04095
04096 TestCase* UnitTestImpl::GetTestCase(const char* test_case_name,
04097 const char* type_param,
04098 Test::SetUpTestCaseFunc set_up_tc,
04099 Test::TearDownTestCaseFunc tear_down_tc) {
04100
04101 const std::vector<TestCase*>::const_iterator test_case =
04102 std::find_if(test_cases_.begin(), test_cases_.end(),
04103 TestCaseNameIs(test_case_name));
04104
04105 if (test_case != test_cases_.end())
04106 return *test_case;
04107
04108
04109 TestCase* const new_test_case =
04110 new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc);
04111
04112
04113 if (internal::UnitTestOptions::MatchesFilter(String(test_case_name),
04114 kDeathTestCaseFilter)) {
04115
04116
04117
04118
04119 ++last_death_test_case_;
04120 test_cases_.insert(test_cases_.begin() + last_death_test_case_,
04121 new_test_case);
04122 } else {
04123
04124 test_cases_.push_back(new_test_case);
04125 }
04126
04127 test_case_indices_.push_back(static_cast<int>(test_case_indices_.size()));
04128 return new_test_case;
04129 }
04130
04131
04132
04133 static void SetUpEnvironment(Environment* env) { env->SetUp(); }
04134 static void TearDownEnvironment(Environment* env) { env->TearDown(); }
04135
04136
04137
04138
04139
04140
04141
04142
04143
04144
04145 bool UnitTestImpl::RunAllTests() {
04146
04147 if (!GTestIsInitialized()) {
04148 printf("%s",
04149 "\nThis test program did NOT call ::testing::InitGoogleTest "
04150 "before calling RUN_ALL_TESTS(). Please fix it.\n");
04151 return false;
04152 }
04153
04154
04155 if (g_help_flag)
04156 return true;
04157
04158
04159
04160 PostFlagParsingInit();
04161
04162
04163
04164
04165 internal::WriteToShardStatusFileIfNeeded();
04166
04167
04168
04169 bool in_subprocess_for_death_test = false;
04170
04171 #if GTEST_HAS_DEATH_TEST
04172 in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL);
04173 #endif // GTEST_HAS_DEATH_TEST
04174
04175 const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
04176 in_subprocess_for_death_test);
04177
04178
04179
04180 const bool has_tests_to_run = FilterTests(should_shard
04181 ? HONOR_SHARDING_PROTOCOL
04182 : IGNORE_SHARDING_PROTOCOL) > 0;
04183
04184
04185 if (GTEST_FLAG(list_tests)) {
04186
04187 ListTestsMatchingFilter();
04188 return true;
04189 }
04190
04191 random_seed_ = GTEST_FLAG(shuffle) ?
04192 GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;
04193
04194
04195 bool failed = false;
04196
04197 TestEventListener* repeater = listeners()->repeater();
04198
04199 repeater->OnTestProgramStart(*parent_);
04200
04201
04202
04203 const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);
04204
04205 const bool forever = repeat < 0;
04206 for (int i = 0; forever || i != repeat; i++) {
04207
04208
04209 ClearNonAdHocTestResult();
04210
04211 const TimeInMillis start = GetTimeInMillis();
04212
04213
04214 if (has_tests_to_run && GTEST_FLAG(shuffle)) {
04215 random()->Reseed(random_seed_);
04216
04217
04218
04219 ShuffleTests();
04220 }
04221
04222
04223 repeater->OnTestIterationStart(*parent_, i);
04224
04225
04226 if (has_tests_to_run) {
04227
04228 repeater->OnEnvironmentsSetUpStart(*parent_);
04229 ForEach(environments_, SetUpEnvironment);
04230 repeater->OnEnvironmentsSetUpEnd(*parent_);
04231
04232
04233
04234 if (!Test::HasFatalFailure()) {
04235 for (int test_index = 0; test_index < total_test_case_count();
04236 test_index++) {
04237 GetMutableTestCase(test_index)->Run();
04238 }
04239 }
04240
04241
04242 repeater->OnEnvironmentsTearDownStart(*parent_);
04243 std::for_each(environments_.rbegin(), environments_.rend(),
04244 TearDownEnvironment);
04245 repeater->OnEnvironmentsTearDownEnd(*parent_);
04246 }
04247
04248 elapsed_time_ = GetTimeInMillis() - start;
04249
04250
04251 repeater->OnTestIterationEnd(*parent_, i);
04252
04253
04254 if (!Passed()) {
04255 failed = true;
04256 }
04257
04258
04259
04260
04261
04262
04263
04264 UnshuffleTests();
04265
04266 if (GTEST_FLAG(shuffle)) {
04267
04268 random_seed_ = GetNextRandomSeed(random_seed_);
04269 }
04270 }
04271
04272 repeater->OnTestProgramEnd(*parent_);
04273
04274 return !failed;
04275 }
04276
04277
04278
04279
04280
04281 void WriteToShardStatusFileIfNeeded() {
04282 const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);
04283 if (test_shard_file != NULL) {
04284 FILE* const file = posix::FOpen(test_shard_file, "w");
04285 if (file == NULL) {
04286 ColoredPrintf(COLOR_RED,
04287 "Could not write to the test shard status file \"%s\" "
04288 "specified by the %s environment variable.\n",
04289 test_shard_file, kTestShardStatusFile);
04290 fflush(stdout);
04291 exit(EXIT_FAILURE);
04292 }
04293 fclose(file);
04294 }
04295 }
04296
04297
04298
04299
04300
04301
04302
04303 bool ShouldShard(const char* total_shards_env,
04304 const char* shard_index_env,
04305 bool in_subprocess_for_death_test) {
04306 if (in_subprocess_for_death_test) {
04307 return false;
04308 }
04309
04310 const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1);
04311 const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1);
04312
04313 if (total_shards == -1 && shard_index == -1) {
04314 return false;
04315 } else if (total_shards == -1 && shard_index != -1) {
04316 const Message msg = Message()
04317 << "Invalid environment variables: you have "
04318 << kTestShardIndex << " = " << shard_index
04319 << ", but have left " << kTestTotalShards << " unset.\n";
04320 ColoredPrintf(COLOR_RED, msg.GetString().c_str());
04321 fflush(stdout);
04322 exit(EXIT_FAILURE);
04323 } else if (total_shards != -1 && shard_index == -1) {
04324 const Message msg = Message()
04325 << "Invalid environment variables: you have "
04326 << kTestTotalShards << " = " << total_shards
04327 << ", but have left " << kTestShardIndex << " unset.\n";
04328 ColoredPrintf(COLOR_RED, msg.GetString().c_str());
04329 fflush(stdout);
04330 exit(EXIT_FAILURE);
04331 } else if (shard_index < 0 || shard_index >= total_shards) {
04332 const Message msg = Message()
04333 << "Invalid environment variables: we require 0 <= "
04334 << kTestShardIndex << " < " << kTestTotalShards
04335 << ", but you have " << kTestShardIndex << "=" << shard_index
04336 << ", " << kTestTotalShards << "=" << total_shards << ".\n";
04337 ColoredPrintf(COLOR_RED, msg.GetString().c_str());
04338 fflush(stdout);
04339 exit(EXIT_FAILURE);
04340 }
04341
04342 return total_shards > 1;
04343 }
04344
04345
04346
04347
04348 Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) {
04349 const char* str_val = posix::GetEnv(var);
04350 if (str_val == NULL) {
04351 return default_val;
04352 }
04353
04354 Int32 result;
04355 if (!ParseInt32(Message() << "The value of environment variable " << var,
04356 str_val, &result)) {
04357 exit(EXIT_FAILURE);
04358 }
04359 return result;
04360 }
04361
04362
04363
04364
04365
04366 bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
04367 return (test_id % total_shards) == shard_index;
04368 }
04369
04370
04371
04372
04373
04374
04375
04376
04377 int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
04378 const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?
04379 Int32FromEnvOrDie(kTestTotalShards, -1) : -1;
04380 const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?
04381 Int32FromEnvOrDie(kTestShardIndex, -1) : -1;
04382
04383
04384
04385
04386
04387 int num_runnable_tests = 0;
04388 int num_selected_tests = 0;
04389 for (size_t i = 0; i < test_cases_.size(); i++) {
04390 TestCase* const test_case = test_cases_[i];
04391 const String &test_case_name = test_case->name();
04392 test_case->set_should_run(false);
04393
04394 for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
04395 TestInfo* const test_info = test_case->test_info_list()[j];
04396 const String test_name(test_info->name());
04397
04398
04399 const bool is_disabled =
04400 internal::UnitTestOptions::MatchesFilter(test_case_name,
04401 kDisableTestFilter) ||
04402 internal::UnitTestOptions::MatchesFilter(test_name,
04403 kDisableTestFilter);
04404 test_info->is_disabled_ = is_disabled;
04405
04406 const bool matches_filter =
04407 internal::UnitTestOptions::FilterMatchesTest(test_case_name,
04408 test_name);
04409 test_info->matches_filter_ = matches_filter;
04410
04411 const bool is_runnable =
04412 (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
04413 matches_filter;
04414
04415 const bool is_selected = is_runnable &&
04416 (shard_tests == IGNORE_SHARDING_PROTOCOL ||
04417 ShouldRunTestOnShard(total_shards, shard_index,
04418 num_runnable_tests));
04419
04420 num_runnable_tests += is_runnable;
04421 num_selected_tests += is_selected;
04422
04423 test_info->should_run_ = is_selected;
04424 test_case->set_should_run(test_case->should_run() || is_selected);
04425 }
04426 }
04427 return num_selected_tests;
04428 }
04429
04430
04431 void UnitTestImpl::ListTestsMatchingFilter() {
04432 for (size_t i = 0; i < test_cases_.size(); i++) {
04433 const TestCase* const test_case = test_cases_[i];
04434 bool printed_test_case_name = false;
04435
04436 for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
04437 const TestInfo* const test_info =
04438 test_case->test_info_list()[j];
04439 if (test_info->matches_filter_) {
04440 if (!printed_test_case_name) {
04441 printed_test_case_name = true;
04442 printf("%s.\n", test_case->name());
04443 }
04444 printf(" %s\n", test_info->name());
04445 }
04446 }
04447 }
04448 fflush(stdout);
04449 }
04450
04451
04452
04453
04454
04455
04456 void UnitTestImpl::set_os_stack_trace_getter(
04457 OsStackTraceGetterInterface* getter) {
04458 if (os_stack_trace_getter_ != getter) {
04459 delete os_stack_trace_getter_;
04460 os_stack_trace_getter_ = getter;
04461 }
04462 }
04463
04464
04465
04466
04467 OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
04468 if (os_stack_trace_getter_ == NULL) {
04469 os_stack_trace_getter_ = new OsStackTraceGetter;
04470 }
04471
04472 return os_stack_trace_getter_;
04473 }
04474
04475
04476
04477 TestResult* UnitTestImpl::current_test_result() {
04478 return current_test_info_ ?
04479 &(current_test_info_->result_) : &ad_hoc_test_result_;
04480 }
04481
04482
04483
04484 void UnitTestImpl::ShuffleTests() {
04485
04486 ShuffleRange(random(), 0, last_death_test_case_ + 1, &test_case_indices_);
04487
04488
04489 ShuffleRange(random(), last_death_test_case_ + 1,
04490 static_cast<int>(test_cases_.size()), &test_case_indices_);
04491
04492
04493 for (size_t i = 0; i < test_cases_.size(); i++) {
04494 test_cases_[i]->ShuffleTests(random());
04495 }
04496 }
04497
04498
04499 void UnitTestImpl::UnshuffleTests() {
04500 for (size_t i = 0; i < test_cases_.size(); i++) {
04501
04502 test_cases_[i]->UnshuffleTests();
04503
04504 test_case_indices_[i] = static_cast<int>(i);
04505 }
04506 }
04507
04508
04509
04510
04511
04512
04513
04514
04515
04516
04517
04518 String GetCurrentOsStackTraceExceptTop(UnitTest* ,
04519 int skip_count) {
04520
04521
04522 return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
04523 }
04524
04525
04526
04527 namespace {
04528 class ClassUniqueToAlwaysTrue {};
04529 }
04530
04531 bool IsTrue(bool condition) { return condition; }
04532
04533 bool AlwaysTrue() {
04534 #if GTEST_HAS_EXCEPTIONS
04535
04536
04537 if (IsTrue(false))
04538 throw ClassUniqueToAlwaysTrue();
04539 #endif // GTEST_HAS_EXCEPTIONS
04540 return true;
04541 }
04542
04543
04544
04545
04546 bool SkipPrefix(const char* prefix, const char** pstr) {
04547 const size_t prefix_len = strlen(prefix);
04548 if (strncmp(*pstr, prefix, prefix_len) == 0) {
04549 *pstr += prefix_len;
04550 return true;
04551 }
04552 return false;
04553 }
04554
04555
04556
04557
04558
04559
04560 const char* ParseFlagValue(const char* str,
04561 const char* flag,
04562 bool def_optional) {
04563
04564 if (str == NULL || flag == NULL) return NULL;
04565
04566
04567 const String flag_str = String::Format("--%s%s", GTEST_FLAG_PREFIX_, flag);
04568 const size_t flag_len = flag_str.length();
04569 if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;
04570
04571
04572 const char* flag_end = str + flag_len;
04573
04574
04575 if (def_optional && (flag_end[0] == '\0')) {
04576 return flag_end;
04577 }
04578
04579
04580
04581
04582 if (flag_end[0] != '=') return NULL;
04583
04584
04585 return flag_end + 1;
04586 }
04587
04588
04589
04590
04591
04592
04593
04594
04595
04596
04597
04598 bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
04599
04600 const char* const value_str = ParseFlagValue(str, flag, true);
04601
04602
04603 if (value_str == NULL) return false;
04604
04605
04606 *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
04607 return true;
04608 }
04609
04610
04611
04612
04613
04614
04615 bool ParseInt32Flag(const char* str, const char* flag, Int32* value) {
04616
04617 const char* const value_str = ParseFlagValue(str, flag, false);
04618
04619
04620 if (value_str == NULL) return false;
04621
04622
04623 return ParseInt32(Message() << "The value of flag --" << flag,
04624 value_str, value);
04625 }
04626
04627
04628
04629
04630
04631
04632 bool ParseStringFlag(const char* str, const char* flag, String* value) {
04633
04634 const char* const value_str = ParseFlagValue(str, flag, false);
04635
04636
04637 if (value_str == NULL) return false;
04638
04639
04640 *value = value_str;
04641 return true;
04642 }
04643
04644
04645
04646
04647
04648
04649
04650 static bool HasGoogleTestFlagPrefix(const char* str) {
04651 return (SkipPrefix("--", &str) ||
04652 SkipPrefix("-", &str) ||
04653 SkipPrefix("/", &str)) &&
04654 !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
04655 (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
04656 SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str));
04657 }
04658
04659
04660
04661
04662
04663
04664
04665
04666
04667
04668
04669
04670 static void PrintColorEncoded(const char* str) {
04671 GTestColor color = COLOR_DEFAULT;
04672
04673
04674
04675
04676
04677 for (;;) {
04678 const char* p = strchr(str, '@');
04679 if (p == NULL) {
04680 ColoredPrintf(color, "%s", str);
04681 return;
04682 }
04683
04684 ColoredPrintf(color, "%s", String(str, p - str).c_str());
04685
04686 const char ch = p[1];
04687 str = p + 2;
04688 if (ch == '@') {
04689 ColoredPrintf(color, "@");
04690 } else if (ch == 'D') {
04691 color = COLOR_DEFAULT;
04692 } else if (ch == 'R') {
04693 color = COLOR_RED;
04694 } else if (ch == 'G') {
04695 color = COLOR_GREEN;
04696 } else if (ch == 'Y') {
04697 color = COLOR_YELLOW;
04698 } else {
04699 --str;
04700 }
04701 }
04702 }
04703
04704 static const char kColorEncodedHelpMessage[] =
04705 "This program contains tests written using " GTEST_NAME_ ". You can use the\n"
04706 "following command line flags to control its behavior:\n"
04707 "\n"
04708 "Test Selection:\n"
04709 " @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n"
04710 " List the names of all tests instead of running them. The name of\n"
04711 " TEST(Foo, Bar) is \"Foo.Bar\".\n"
04712 " @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS"
04713 "[@G-@YNEGATIVE_PATTERNS]@D\n"
04714 " Run only the tests whose name matches one of the positive patterns but\n"
04715 " none of the negative patterns. '?' matches any single character; '*'\n"
04716 " matches any substring; ':' separates two patterns.\n"
04717 " @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n"
04718 " Run all disabled tests too.\n"
04719 "\n"
04720 "Test Execution:\n"
04721 " @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n"
04722 " Run the tests repeatedly; use a negative count to repeat forever.\n"
04723 " @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n"
04724 " Randomize tests' orders on every iteration.\n"
04725 " @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n"
04726 " Random number seed to use for shuffling test orders (between 1 and\n"
04727 " 99999, or 0 to use a seed based on the current time).\n"
04728 "\n"
04729 "Test Output:\n"
04730 " @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
04731 " Enable/disable colored output. The default is @Gauto@D.\n"
04732 " -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n"
04733 " Don't print the elapsed time of each test.\n"
04734 " @G--" GTEST_FLAG_PREFIX_ "output=xml@Y[@G:@YDIRECTORY_PATH@G"
04735 GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n"
04736 " Generate an XML report in the given directory or with the given file\n"
04737 " name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n"
04738 #if GTEST_CAN_STREAM_RESULTS_
04739 " @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n"
04740 " Stream test results to the given server.\n"
04741 #endif // GTEST_CAN_STREAM_RESULTS_
04742 "\n"
04743 "Assertion Behavior:\n"
04744 #if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
04745 " @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
04746 " Set the default death test style.\n"
04747 #endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
04748 " @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n"
04749 " Turn assertion failures into debugger break-points.\n"
04750 " @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n"
04751 " Turn assertion failures into C++ exceptions.\n"
04752 " @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n"
04753 " Do not report exceptions as test failures. Instead, allow them\n"
04754 " to crash the program or throw a pop-up (on Windows).\n"
04755 "\n"
04756 "Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set "
04757 "the corresponding\n"
04758 "environment variable of a flag (all letters in upper-case). For example, to\n"
04759 "disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_
04760 "color=no@D or set\n"
04761 "the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n"
04762 "\n"
04763 "For more information, please read the " GTEST_NAME_ " documentation at\n"
04764 "@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n"
04765 "(not one in your own code or tests), please report it to\n"
04766 "@G<" GTEST_DEV_EMAIL_ ">@D.\n";
04767
04768
04769
04770
04771 template <typename CharType>
04772 void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
04773 for (int i = 1; i < *argc; i++) {
04774 const String arg_string = StreamableToString(argv[i]);
04775 const char* const arg = arg_string.c_str();
04776
04777 using internal::ParseBoolFlag;
04778 using internal::ParseInt32Flag;
04779 using internal::ParseStringFlag;
04780
04781
04782 if (ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,
04783 >EST_FLAG(also_run_disabled_tests)) ||
04784 ParseBoolFlag(arg, kBreakOnFailureFlag,
04785 >EST_FLAG(break_on_failure)) ||
04786 ParseBoolFlag(arg, kCatchExceptionsFlag,
04787 >EST_FLAG(catch_exceptions)) ||
04788 ParseStringFlag(arg, kColorFlag, >EST_FLAG(color)) ||
04789 ParseStringFlag(arg, kDeathTestStyleFlag,
04790 >EST_FLAG(death_test_style)) ||
04791 ParseBoolFlag(arg, kDeathTestUseFork,
04792 >EST_FLAG(death_test_use_fork)) ||
04793 ParseStringFlag(arg, kFilterFlag, >EST_FLAG(filter)) ||
04794 ParseStringFlag(arg, kInternalRunDeathTestFlag,
04795 >EST_FLAG(internal_run_death_test)) ||
04796 ParseBoolFlag(arg, kListTestsFlag, >EST_FLAG(list_tests)) ||
04797 ParseStringFlag(arg, kOutputFlag, >EST_FLAG(output)) ||
04798 ParseBoolFlag(arg, kPrintTimeFlag, >EST_FLAG(print_time)) ||
04799 ParseInt32Flag(arg, kRandomSeedFlag, >EST_FLAG(random_seed)) ||
04800 ParseInt32Flag(arg, kRepeatFlag, >EST_FLAG(repeat)) ||
04801 ParseBoolFlag(arg, kShuffleFlag, >EST_FLAG(shuffle)) ||
04802 ParseInt32Flag(arg, kStackTraceDepthFlag,
04803 >EST_FLAG(stack_trace_depth)) ||
04804 ParseStringFlag(arg, kStreamResultToFlag,
04805 >EST_FLAG(stream_result_to)) ||
04806 ParseBoolFlag(arg, kThrowOnFailureFlag,
04807 >EST_FLAG(throw_on_failure))
04808 ) {
04809
04810
04811
04812
04813 for (int j = i; j != *argc; j++) {
04814 argv[j] = argv[j + 1];
04815 }
04816
04817
04818 (*argc)--;
04819
04820
04821
04822 i--;
04823 } else if (arg_string == "--help" || arg_string == "-h" ||
04824 arg_string == "-?" || arg_string == "/?" ||
04825 HasGoogleTestFlagPrefix(arg)) {
04826
04827
04828 g_help_flag = true;
04829 }
04830 }
04831
04832 if (g_help_flag) {
04833
04834
04835
04836 PrintColorEncoded(kColorEncodedHelpMessage);
04837 }
04838 }
04839
04840
04841
04842 void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
04843 ParseGoogleTestFlagsOnlyImpl(argc, argv);
04844 }
04845 void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {
04846 ParseGoogleTestFlagsOnlyImpl(argc, argv);
04847 }
04848
04849
04850
04851
04852
04853 template <typename CharType>
04854 void InitGoogleTestImpl(int* argc, CharType** argv) {
04855 g_init_gtest_count++;
04856
04857
04858 if (g_init_gtest_count != 1) return;
04859
04860 if (*argc <= 0) return;
04861
04862 internal::g_executable_path = internal::StreamableToString(argv[0]);
04863
04864 #if GTEST_HAS_DEATH_TEST
04865
04866 g_argvs.clear();
04867 for (int i = 0; i != *argc; i++) {
04868 g_argvs.push_back(StreamableToString(argv[i]));
04869 }
04870
04871 #endif // GTEST_HAS_DEATH_TEST
04872
04873 ParseGoogleTestFlagsOnly(argc, argv);
04874 GetUnitTestImpl()->PostFlagParsingInit();
04875 }
04876
04877 }
04878
04879
04880
04881
04882
04883
04884
04885
04886
04887
04888 void InitGoogleTest(int* argc, char** argv) {
04889 internal::InitGoogleTestImpl(argc, argv);
04890 }
04891
04892
04893
04894 void InitGoogleTest(int* argc, wchar_t** argv) {
04895 internal::InitGoogleTestImpl(argc, argv);
04896 }
04897
04898 }