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