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