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
00035
00036
00037
00038
00039 #include "gtest/gtest.h"
00040
00041
00042
00043
00044
00045
00046
00047
00048
00049
00050
00051
00052
00053
00054
00055
00056
00057
00058
00059
00060
00061
00062
00063
00064
00065
00066
00067
00068
00069
00070
00071
00072
00073
00074
00075
00076
00077
00078
00079
00080
00081
00082
00083
00084
00085
00086
00087
00088
00089
00090
00091
00092
00093
00094
00095
00096
00097
00098
00099
00100
00101
00102
00103
00104
00105
00106
00107
00108
00109 #ifndef GTEST_INCLUDE_GTEST_GTEST_SPI_H_
00110 #define GTEST_INCLUDE_GTEST_GTEST_SPI_H_
00111
00112
00113 namespace testing {
00114
00115
00116
00117
00118
00119
00120
00121
00122
00123
00124 class GTEST_API_ ScopedFakeTestPartResultReporter
00125 : public TestPartResultReporterInterface {
00126 public:
00127
00128 enum InterceptMode {
00129 INTERCEPT_ONLY_CURRENT_THREAD,
00130 INTERCEPT_ALL_THREADS
00131 };
00132
00133
00134
00135
00136
00137 explicit ScopedFakeTestPartResultReporter(TestPartResultArray* result);
00138
00139
00140 ScopedFakeTestPartResultReporter(InterceptMode intercept_mode,
00141 TestPartResultArray* result);
00142
00143
00144 virtual ~ScopedFakeTestPartResultReporter();
00145
00146
00147
00148
00149
00150
00151 virtual void ReportTestPartResult(const TestPartResult& result);
00152 private:
00153 void Init();
00154
00155 const InterceptMode intercept_mode_;
00156 TestPartResultReporterInterface* old_reporter_;
00157 TestPartResultArray* const result_;
00158
00159 GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedFakeTestPartResultReporter);
00160 };
00161
00162 namespace internal {
00163
00164
00165
00166
00167
00168
00169 class GTEST_API_ SingleFailureChecker {
00170 public:
00171
00172 SingleFailureChecker(const TestPartResultArray* results,
00173 TestPartResult::Type type,
00174 const string& substr);
00175 ~SingleFailureChecker();
00176 private:
00177 const TestPartResultArray* const results_;
00178 const TestPartResult::Type type_;
00179 const string substr_;
00180
00181 GTEST_DISALLOW_COPY_AND_ASSIGN_(SingleFailureChecker);
00182 };
00183
00184 }
00185
00186 }
00187
00188
00189
00190
00191
00192
00193
00194
00195
00196
00197
00198
00199
00200
00201
00202
00203
00204
00205
00206
00207
00208
00209
00210
00211 #define EXPECT_FATAL_FAILURE(statement, substr) \
00212 do { \
00213 class GTestExpectFatalFailureHelper {\
00214 public:\
00215 static void Execute() { statement; }\
00216 };\
00217 ::testing::TestPartResultArray gtest_failures;\
00218 ::testing::internal::SingleFailureChecker gtest_checker(\
00219 >est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
00220 {\
00221 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
00222 ::testing::ScopedFakeTestPartResultReporter:: \
00223 INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\
00224 GTestExpectFatalFailureHelper::Execute();\
00225 }\
00226 } while (::testing::internal::AlwaysFalse())
00227
00228 #define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
00229 do { \
00230 class GTestExpectFatalFailureHelper {\
00231 public:\
00232 static void Execute() { statement; }\
00233 };\
00234 ::testing::TestPartResultArray gtest_failures;\
00235 ::testing::internal::SingleFailureChecker gtest_checker(\
00236 >est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
00237 {\
00238 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
00239 ::testing::ScopedFakeTestPartResultReporter:: \
00240 INTERCEPT_ALL_THREADS, >est_failures);\
00241 GTestExpectFatalFailureHelper::Execute();\
00242 }\
00243 } while (::testing::internal::AlwaysFalse())
00244
00245
00246
00247
00248
00249
00250
00251
00252
00253
00254
00255
00256
00257
00258
00259
00260
00261
00262
00263
00264
00265
00266
00267
00268
00269
00270
00271
00272
00273
00274
00275
00276
00277 #define EXPECT_NONFATAL_FAILURE(statement, substr) \
00278 do {\
00279 ::testing::TestPartResultArray gtest_failures;\
00280 ::testing::internal::SingleFailureChecker gtest_checker(\
00281 >est_failures, ::testing::TestPartResult::kNonFatalFailure, \
00282 (substr));\
00283 {\
00284 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
00285 ::testing::ScopedFakeTestPartResultReporter:: \
00286 INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\
00287 if (::testing::internal::AlwaysTrue()) { statement; }\
00288 }\
00289 } while (::testing::internal::AlwaysFalse())
00290
00291 #define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
00292 do {\
00293 ::testing::TestPartResultArray gtest_failures;\
00294 ::testing::internal::SingleFailureChecker gtest_checker(\
00295 >est_failures, ::testing::TestPartResult::kNonFatalFailure, \
00296 (substr));\
00297 {\
00298 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
00299 ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \
00300 >est_failures);\
00301 if (::testing::internal::AlwaysTrue()) { statement; }\
00302 }\
00303 } while (::testing::internal::AlwaysFalse())
00304
00305 #endif // GTEST_INCLUDE_GTEST_GTEST_SPI_H_
00306
00307 #include <ctype.h>
00308 #include <math.h>
00309 #include <stdarg.h>
00310 #include <stdio.h>
00311 #include <stdlib.h>
00312 #include <time.h>
00313 #include <wchar.h>
00314 #include <wctype.h>
00315
00316 #include <algorithm>
00317 #include <iomanip>
00318 #include <limits>
00319 #include <ostream>
00320 #include <sstream>
00321 #include <vector>
00322
00323 #if GTEST_OS_LINUX
00324
00325
00326
00327 # define GTEST_HAS_GETTIMEOFDAY_ 1
00328
00329 # include <fcntl.h>
00330 # include <limits.h>
00331 # include <sched.h>
00332
00333 # include <strings.h>
00334 # include <sys/mman.h>
00335 # include <sys/time.h>
00336 # include <unistd.h>
00337 # include <string>
00338
00339 #elif GTEST_OS_SYMBIAN
00340 # define GTEST_HAS_GETTIMEOFDAY_ 1
00341 # include <sys/time.h>
00342
00343 #elif GTEST_OS_ZOS
00344 # define GTEST_HAS_GETTIMEOFDAY_ 1
00345 # include <sys/time.h>
00346
00347
00348 # include <strings.h>
00349
00350 #elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE.
00351
00352 # include <windows.h>
00353
00354 #elif GTEST_OS_WINDOWS // We are on Windows proper.
00355
00356 # include <io.h>
00357 # include <sys/timeb.h>
00358 # include <sys/types.h>
00359 # include <sys/stat.h>
00360
00361 # if GTEST_OS_WINDOWS_MINGW
00362
00363
00364
00365
00366
00367
00368 # define GTEST_HAS_GETTIMEOFDAY_ 1
00369 # include <sys/time.h>
00370 # endif // GTEST_OS_WINDOWS_MINGW
00371
00372
00373
00374 # include <windows.h>
00375
00376 #else
00377
00378
00379
00380
00381 # define GTEST_HAS_GETTIMEOFDAY_ 1
00382
00383
00384
00385 # include <sys/time.h>
00386 # include <unistd.h>
00387
00388 #endif // GTEST_OS_LINUX
00389
00390 #if GTEST_HAS_EXCEPTIONS
00391 # include <stdexcept>
00392 #endif
00393
00394 #if GTEST_CAN_STREAM_RESULTS_
00395 # include <arpa/inet.h>
00396 # include <netdb.h>
00397 #endif
00398
00399
00400
00401
00402
00403
00404 #define GTEST_IMPLEMENTATION_ 1
00405
00406
00407
00408
00409
00410
00411
00412
00413
00414
00415
00416
00417
00418
00419
00420
00421
00422
00423
00424
00425
00426
00427
00428
00429
00430
00431
00432
00433
00434
00435
00436
00437
00438
00439
00440
00441 #ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_
00442 #define GTEST_SRC_GTEST_INTERNAL_INL_H_
00443
00444
00445
00446 #if !GTEST_IMPLEMENTATION_
00447
00448 # error "gtest-internal-inl.h is part of Google Test's internal implementation."
00449 # error "It must not be included except by Google Test itself."
00450 #endif // GTEST_IMPLEMENTATION_
00451
00452 #ifndef _WIN32_WCE
00453 # include <errno.h>
00454 #endif // !_WIN32_WCE
00455 #include <stddef.h>
00456 #include <stdlib.h>
00457 #include <string.h>
00458
00459 #include <algorithm>
00460 #include <string>
00461 #include <vector>
00462
00463
00464 #if GTEST_CAN_STREAM_RESULTS_
00465 # include <arpa/inet.h>
00466 # include <netdb.h>
00467 #endif
00468
00469 #if GTEST_OS_WINDOWS
00470 # include <windows.h>
00471 #endif // GTEST_OS_WINDOWS
00472
00473
00474 namespace testing {
00475
00476
00477
00478
00479
00480
00481 GTEST_DECLARE_bool_(death_test_use_fork);
00482
00483 namespace internal {
00484
00485
00486
00487 GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest;
00488
00489
00490 const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests";
00491 const char kBreakOnFailureFlag[] = "break_on_failure";
00492 const char kCatchExceptionsFlag[] = "catch_exceptions";
00493 const char kColorFlag[] = "color";
00494 const char kFilterFlag[] = "filter";
00495 const char kListTestsFlag[] = "list_tests";
00496 const char kOutputFlag[] = "output";
00497 const char kPrintTimeFlag[] = "print_time";
00498 const char kRandomSeedFlag[] = "random_seed";
00499 const char kRepeatFlag[] = "repeat";
00500 const char kShuffleFlag[] = "shuffle";
00501 const char kStackTraceDepthFlag[] = "stack_trace_depth";
00502 const char kStreamResultToFlag[] = "stream_result_to";
00503 const char kThrowOnFailureFlag[] = "throw_on_failure";
00504
00505
00506 const int kMaxRandomSeed = 99999;
00507
00508
00509
00510 GTEST_API_ extern bool g_help_flag;
00511
00512
00513 GTEST_API_ TimeInMillis GetTimeInMillis();
00514
00515
00516 GTEST_API_ bool ShouldUseColor(bool stdout_is_tty);
00517
00518
00519 GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms);
00520
00521
00522
00523
00524
00525 GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms);
00526
00527
00528
00529
00530
00531 GTEST_API_ bool ParseInt32Flag(
00532 const char* str, const char* flag, Int32* value);
00533
00534
00535
00536 inline int GetRandomSeedFromFlag(Int32 random_seed_flag) {
00537 const unsigned int raw_seed = (random_seed_flag == 0) ?
00538 static_cast<unsigned int>(GetTimeInMillis()) :
00539 static_cast<unsigned int>(random_seed_flag);
00540
00541
00542
00543 const int normalized_seed =
00544 static_cast<int>((raw_seed - 1U) %
00545 static_cast<unsigned int>(kMaxRandomSeed)) + 1;
00546 return normalized_seed;
00547 }
00548
00549
00550
00551
00552 inline int GetNextRandomSeed(int seed) {
00553 GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed)
00554 << "Invalid random seed " << seed << " - must be in [1, "
00555 << kMaxRandomSeed << "].";
00556 const int next_seed = seed + 1;
00557 return (next_seed > kMaxRandomSeed) ? 1 : next_seed;
00558 }
00559
00560
00561
00562 class GTestFlagSaver {
00563 public:
00564
00565 GTestFlagSaver() {
00566 also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests);
00567 break_on_failure_ = GTEST_FLAG(break_on_failure);
00568 catch_exceptions_ = GTEST_FLAG(catch_exceptions);
00569 color_ = GTEST_FLAG(color);
00570 death_test_style_ = GTEST_FLAG(death_test_style);
00571 death_test_use_fork_ = GTEST_FLAG(death_test_use_fork);
00572 filter_ = GTEST_FLAG(filter);
00573 internal_run_death_test_ = GTEST_FLAG(internal_run_death_test);
00574 list_tests_ = GTEST_FLAG(list_tests);
00575 output_ = GTEST_FLAG(output);
00576 print_time_ = GTEST_FLAG(print_time);
00577 random_seed_ = GTEST_FLAG(random_seed);
00578 repeat_ = GTEST_FLAG(repeat);
00579 shuffle_ = GTEST_FLAG(shuffle);
00580 stack_trace_depth_ = GTEST_FLAG(stack_trace_depth);
00581 stream_result_to_ = GTEST_FLAG(stream_result_to);
00582 throw_on_failure_ = GTEST_FLAG(throw_on_failure);
00583 }
00584
00585
00586 ~GTestFlagSaver() {
00587 GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_;
00588 GTEST_FLAG(break_on_failure) = break_on_failure_;
00589 GTEST_FLAG(catch_exceptions) = catch_exceptions_;
00590 GTEST_FLAG(color) = color_;
00591 GTEST_FLAG(death_test_style) = death_test_style_;
00592 GTEST_FLAG(death_test_use_fork) = death_test_use_fork_;
00593 GTEST_FLAG(filter) = filter_;
00594 GTEST_FLAG(internal_run_death_test) = internal_run_death_test_;
00595 GTEST_FLAG(list_tests) = list_tests_;
00596 GTEST_FLAG(output) = output_;
00597 GTEST_FLAG(print_time) = print_time_;
00598 GTEST_FLAG(random_seed) = random_seed_;
00599 GTEST_FLAG(repeat) = repeat_;
00600 GTEST_FLAG(shuffle) = shuffle_;
00601 GTEST_FLAG(stack_trace_depth) = stack_trace_depth_;
00602 GTEST_FLAG(stream_result_to) = stream_result_to_;
00603 GTEST_FLAG(throw_on_failure) = throw_on_failure_;
00604 }
00605
00606 private:
00607
00608 bool also_run_disabled_tests_;
00609 bool break_on_failure_;
00610 bool catch_exceptions_;
00611 std::string color_;
00612 std::string death_test_style_;
00613 bool death_test_use_fork_;
00614 std::string filter_;
00615 std::string internal_run_death_test_;
00616 bool list_tests_;
00617 std::string output_;
00618 bool print_time_;
00619 internal::Int32 random_seed_;
00620 internal::Int32 repeat_;
00621 bool shuffle_;
00622 internal::Int32 stack_trace_depth_;
00623 std::string stream_result_to_;
00624 bool throw_on_failure_;
00625 } GTEST_ATTRIBUTE_UNUSED_;
00626
00627
00628
00629
00630
00631
00632
00633 GTEST_API_ std::string CodePointToUtf8(UInt32 code_point);
00634
00635
00636
00637
00638
00639
00640
00641
00642
00643
00644
00645
00646
00647
00648 GTEST_API_ std::string WideStringToUtf8(const wchar_t* str, int num_chars);
00649
00650
00651
00652
00653
00654 void WriteToShardStatusFileIfNeeded();
00655
00656
00657
00658
00659
00660
00661
00662 GTEST_API_ bool ShouldShard(const char* total_shards_str,
00663 const char* shard_index_str,
00664 bool in_subprocess_for_death_test);
00665
00666
00667
00668
00669 GTEST_API_ Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val);
00670
00671
00672
00673
00674
00675 GTEST_API_ bool ShouldRunTestOnShard(
00676 int total_shards, int shard_index, int test_id);
00677
00678
00679
00680
00681
00682 template <class Container, typename Predicate>
00683 inline int CountIf(const Container& c, Predicate predicate) {
00684
00685
00686 int count = 0;
00687 for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) {
00688 if (predicate(*it))
00689 ++count;
00690 }
00691 return count;
00692 }
00693
00694
00695 template <class Container, typename Functor>
00696 void ForEach(const Container& c, Functor functor) {
00697 std::for_each(c.begin(), c.end(), functor);
00698 }
00699
00700
00701
00702 template <typename E>
00703 inline E GetElementOr(const std::vector<E>& v, int i, E default_value) {
00704 return (i < 0 || i >= static_cast<int>(v.size())) ? default_value : v[i];
00705 }
00706
00707
00708
00709
00710
00711 template <typename E>
00712 void ShuffleRange(internal::Random* random, int begin, int end,
00713 std::vector<E>* v) {
00714 const int size = static_cast<int>(v->size());
00715 GTEST_CHECK_(0 <= begin && begin <= size)
00716 << "Invalid shuffle range start " << begin << ": must be in range [0, "
00717 << size << "].";
00718 GTEST_CHECK_(begin <= end && end <= size)
00719 << "Invalid shuffle range finish " << end << ": must be in range ["
00720 << begin << ", " << size << "].";
00721
00722
00723
00724 for (int range_width = end - begin; range_width >= 2; range_width--) {
00725 const int last_in_range = begin + range_width - 1;
00726 const int selected = begin + random->Generate(range_width);
00727 std::swap((*v)[selected], (*v)[last_in_range]);
00728 }
00729 }
00730
00731
00732 template <typename E>
00733 inline void Shuffle(internal::Random* random, std::vector<E>* v) {
00734 ShuffleRange(random, 0, static_cast<int>(v->size()), v);
00735 }
00736
00737
00738
00739 template <typename T>
00740 static void Delete(T* x) {
00741 delete x;
00742 }
00743
00744
00745
00746
00747 class TestPropertyKeyIs {
00748 public:
00749
00750
00751
00752 explicit TestPropertyKeyIs(const std::string& key) : key_(key) {}
00753
00754
00755 bool operator()(const TestProperty& test_property) const {
00756 return test_property.key() == key_;
00757 }
00758
00759 private:
00760 std::string key_;
00761 };
00762
00763
00764
00765
00766
00767
00768
00769
00770
00771
00772
00773 class GTEST_API_ UnitTestOptions {
00774 public:
00775
00776
00777
00778 static std::string GetOutputFormat();
00779
00780
00781
00782
00783 static std::string GetAbsolutePathToOutputFile();
00784
00785
00786
00787
00788
00789
00790
00791
00792 static bool PatternMatchesString(const char *pattern, const char *str);
00793
00794
00795
00796 static bool FilterMatchesTest(const std::string &test_case_name,
00797 const std::string &test_name);
00798
00799 #if GTEST_OS_WINDOWS
00800
00801
00802
00803
00804
00805 static int GTestShouldProcessSEH(DWORD exception_code);
00806 #endif // GTEST_OS_WINDOWS
00807
00808
00809
00810 static bool MatchesFilter(const std::string& name, const char* filter);
00811 };
00812
00813
00814
00815 GTEST_API_ FilePath GetCurrentExecutableName();
00816
00817
00818 class OsStackTraceGetterInterface {
00819 public:
00820 OsStackTraceGetterInterface() {}
00821 virtual ~OsStackTraceGetterInterface() {}
00822
00823
00824
00825
00826
00827
00828
00829 virtual string CurrentStackTrace(int max_depth, int skip_count) = 0;
00830
00831
00832
00833
00834 virtual void UponLeavingGTest() = 0;
00835
00836 private:
00837 GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface);
00838 };
00839
00840
00841 class OsStackTraceGetter : public OsStackTraceGetterInterface {
00842 public:
00843 OsStackTraceGetter() : caller_frame_(NULL) {}
00844
00845 virtual string CurrentStackTrace(int max_depth, int skip_count)
00846 GTEST_LOCK_EXCLUDED_(mutex_);
00847
00848 virtual void UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_);
00849
00850
00851
00852 static const char* const kElidedFramesMarker;
00853
00854 private:
00855 Mutex mutex_;
00856
00857
00858
00859
00860
00861 void* caller_frame_;
00862
00863 GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter);
00864 };
00865
00866
00867 struct TraceInfo {
00868 const char* file;
00869 int line;
00870 std::string message;
00871 };
00872
00873
00874
00875 class DefaultGlobalTestPartResultReporter
00876 : public TestPartResultReporterInterface {
00877 public:
00878 explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test);
00879
00880
00881 virtual void ReportTestPartResult(const TestPartResult& result);
00882
00883 private:
00884 UnitTestImpl* const unit_test_;
00885
00886 GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter);
00887 };
00888
00889
00890
00891 class DefaultPerThreadTestPartResultReporter
00892 : public TestPartResultReporterInterface {
00893 public:
00894 explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test);
00895
00896
00897 virtual void ReportTestPartResult(const TestPartResult& result);
00898
00899 private:
00900 UnitTestImpl* const unit_test_;
00901
00902 GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter);
00903 };
00904
00905
00906
00907
00908
00909 class GTEST_API_ UnitTestImpl {
00910 public:
00911 explicit UnitTestImpl(UnitTest* parent);
00912 virtual ~UnitTestImpl();
00913
00914
00915
00916
00917
00918
00919
00920
00921
00922 TestPartResultReporterInterface* GetGlobalTestPartResultReporter();
00923
00924
00925 void SetGlobalTestPartResultReporter(
00926 TestPartResultReporterInterface* reporter);
00927
00928
00929 TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread();
00930
00931
00932 void SetTestPartResultReporterForCurrentThread(
00933 TestPartResultReporterInterface* reporter);
00934
00935
00936 int successful_test_case_count() const;
00937
00938
00939 int failed_test_case_count() const;
00940
00941
00942 int total_test_case_count() const;
00943
00944
00945
00946 int test_case_to_run_count() const;
00947
00948
00949 int successful_test_count() const;
00950
00951
00952 int failed_test_count() const;
00953
00954
00955 int reportable_disabled_test_count() const;
00956
00957
00958 int disabled_test_count() const;
00959
00960
00961 int reportable_test_count() const;
00962
00963
00964 int total_test_count() const;
00965
00966
00967 int test_to_run_count() const;
00968
00969
00970
00971 TimeInMillis start_timestamp() const { return start_timestamp_; }
00972
00973
00974 TimeInMillis elapsed_time() const { return elapsed_time_; }
00975
00976
00977 bool Passed() const { return !Failed(); }
00978
00979
00980
00981 bool Failed() const {
00982 return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed();
00983 }
00984
00985
00986
00987 const TestCase* GetTestCase(int i) const {
00988 const int index = GetElementOr(test_case_indices_, i, -1);
00989 return index < 0 ? NULL : test_cases_[i];
00990 }
00991
00992
00993
00994 TestCase* GetMutableTestCase(int i) {
00995 const int index = GetElementOr(test_case_indices_, i, -1);
00996 return index < 0 ? NULL : test_cases_[index];
00997 }
00998
00999
01000 TestEventListeners* listeners() { return &listeners_; }
01001
01002
01003
01004 TestResult* current_test_result();
01005
01006
01007 const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; }
01008
01009
01010
01011
01012
01013
01014 void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter);
01015
01016
01017
01018
01019 OsStackTraceGetterInterface* os_stack_trace_getter();
01020
01021
01022
01023
01024
01025
01026
01027
01028
01029
01030
01031 std::string CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_;
01032
01033
01034
01035
01036
01037
01038
01039
01040
01041
01042
01043 TestCase* GetTestCase(const char* test_case_name,
01044 const char* type_param,
01045 Test::SetUpTestCaseFunc set_up_tc,
01046 Test::TearDownTestCaseFunc tear_down_tc);
01047
01048
01049
01050
01051
01052
01053
01054
01055 void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc,
01056 Test::TearDownTestCaseFunc tear_down_tc,
01057 TestInfo* test_info) {
01058
01059
01060
01061
01062
01063
01064
01065 if (original_working_dir_.IsEmpty()) {
01066 original_working_dir_.Set(FilePath::GetCurrentDir());
01067 GTEST_CHECK_(!original_working_dir_.IsEmpty())
01068 << "Failed to get the current working directory.";
01069 }
01070
01071 GetTestCase(test_info->test_case_name(),
01072 test_info->type_param(),
01073 set_up_tc,
01074 tear_down_tc)->AddTestInfo(test_info);
01075 }
01076
01077 #if GTEST_HAS_PARAM_TEST
01078
01079
01080 internal::ParameterizedTestCaseRegistry& parameterized_test_registry() {
01081 return parameterized_test_registry_;
01082 }
01083 #endif // GTEST_HAS_PARAM_TEST
01084
01085
01086 void set_current_test_case(TestCase* a_current_test_case) {
01087 current_test_case_ = a_current_test_case;
01088 }
01089
01090
01091
01092
01093 void set_current_test_info(TestInfo* a_current_test_info) {
01094 current_test_info_ = a_current_test_info;
01095 }
01096
01097
01098
01099
01100
01101
01102
01103 void RegisterParameterizedTests();
01104
01105
01106
01107
01108
01109 bool RunAllTests();
01110
01111
01112 void ClearNonAdHocTestResult() {
01113 ForEach(test_cases_, TestCase::ClearTestCaseResult);
01114 }
01115
01116
01117 void ClearAdHocTestResult() {
01118 ad_hoc_test_result_.Clear();
01119 }
01120
01121
01122
01123
01124
01125 void RecordProperty(const TestProperty& test_property);
01126
01127 enum ReactionToSharding {
01128 HONOR_SHARDING_PROTOCOL,
01129 IGNORE_SHARDING_PROTOCOL
01130 };
01131
01132
01133
01134
01135
01136
01137
01138 int FilterTests(ReactionToSharding shard_tests);
01139
01140
01141 void ListTestsMatchingFilter();
01142
01143 const TestCase* current_test_case() const { return current_test_case_; }
01144 TestInfo* current_test_info() { return current_test_info_; }
01145 const TestInfo* current_test_info() const { return current_test_info_; }
01146
01147
01148
01149 std::vector<Environment*>& environments() { return environments_; }
01150
01151
01152 std::vector<TraceInfo>& gtest_trace_stack() {
01153 return *(gtest_trace_stack_.pointer());
01154 }
01155 const std::vector<TraceInfo>& gtest_trace_stack() const {
01156 return gtest_trace_stack_.get();
01157 }
01158
01159 #if GTEST_HAS_DEATH_TEST
01160 void InitDeathTestSubprocessControlInfo() {
01161 internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());
01162 }
01163
01164
01165
01166
01167 const InternalRunDeathTestFlag* internal_run_death_test_flag() const {
01168 return internal_run_death_test_flag_.get();
01169 }
01170
01171
01172 internal::DeathTestFactory* death_test_factory() {
01173 return death_test_factory_.get();
01174 }
01175
01176 void SuppressTestEventsIfInSubprocess();
01177
01178 friend class ReplaceDeathTestFactory;
01179 #endif // GTEST_HAS_DEATH_TEST
01180
01181
01182
01183 void ConfigureXmlOutput();
01184
01185 #if GTEST_CAN_STREAM_RESULTS_
01186
01187
01188 void ConfigureStreamingOutput();
01189 #endif
01190
01191
01192
01193
01194
01195
01196 void PostFlagParsingInit();
01197
01198
01199 int random_seed() const { return random_seed_; }
01200
01201
01202 internal::Random* random() { return &random_; }
01203
01204
01205
01206 void ShuffleTests();
01207
01208
01209 void UnshuffleTests();
01210
01211
01212
01213 bool catch_exceptions() const { return catch_exceptions_; }
01214
01215 private:
01216 friend class ::testing::UnitTest;
01217
01218
01219
01220 void set_catch_exceptions(bool value) { catch_exceptions_ = value; }
01221
01222
01223 UnitTest* const parent_;
01224
01225
01226
01227 internal::FilePath original_working_dir_;
01228
01229
01230 DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_;
01231 DefaultPerThreadTestPartResultReporter
01232 default_per_thread_test_part_result_reporter_;
01233
01234
01235 TestPartResultReporterInterface* global_test_part_result_repoter_;
01236
01237
01238 internal::Mutex global_test_part_result_reporter_mutex_;
01239
01240
01241 internal::ThreadLocal<TestPartResultReporterInterface*>
01242 per_thread_test_part_result_reporter_;
01243
01244
01245
01246 std::vector<Environment*> environments_;
01247
01248
01249
01250 std::vector<TestCase*> test_cases_;
01251
01252
01253
01254
01255
01256 std::vector<int> test_case_indices_;
01257
01258 #if GTEST_HAS_PARAM_TEST
01259
01260
01261 internal::ParameterizedTestCaseRegistry parameterized_test_registry_;
01262
01263
01264 bool parameterized_tests_registered_;
01265 #endif // GTEST_HAS_PARAM_TEST
01266
01267
01268 int last_death_test_case_;
01269
01270
01271
01272
01273
01274 TestCase* current_test_case_;
01275
01276
01277
01278
01279
01280 TestInfo* current_test_info_;
01281
01282
01283
01284
01285
01286
01287
01288
01289
01290 TestResult ad_hoc_test_result_;
01291
01292
01293
01294 TestEventListeners listeners_;
01295
01296
01297
01298
01299
01300 OsStackTraceGetterInterface* os_stack_trace_getter_;
01301
01302
01303 bool post_flag_parse_init_performed_;
01304
01305
01306 int random_seed_;
01307
01308
01309 internal::Random random_;
01310
01311
01312
01313 TimeInMillis start_timestamp_;
01314
01315
01316 TimeInMillis elapsed_time_;
01317
01318 #if GTEST_HAS_DEATH_TEST
01319
01320
01321 internal::scoped_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;
01322 internal::scoped_ptr<internal::DeathTestFactory> death_test_factory_;
01323 #endif // GTEST_HAS_DEATH_TEST
01324
01325
01326 internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_;
01327
01328
01329
01330 bool catch_exceptions_;
01331
01332 GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl);
01333 };
01334
01335
01336
01337 inline UnitTestImpl* GetUnitTestImpl() {
01338 return UnitTest::GetInstance()->impl();
01339 }
01340
01341 #if GTEST_USES_SIMPLE_RE
01342
01343
01344
01345 GTEST_API_ bool IsInSet(char ch, const char* str);
01346 GTEST_API_ bool IsAsciiDigit(char ch);
01347 GTEST_API_ bool IsAsciiPunct(char ch);
01348 GTEST_API_ bool IsRepeat(char ch);
01349 GTEST_API_ bool IsAsciiWhiteSpace(char ch);
01350 GTEST_API_ bool IsAsciiWordChar(char ch);
01351 GTEST_API_ bool IsValidEscape(char ch);
01352 GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch);
01353 GTEST_API_ bool ValidateRegex(const char* regex);
01354 GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str);
01355 GTEST_API_ bool MatchRepetitionAndRegexAtHead(
01356 bool escaped, char ch, char repeat, const char* regex, const char* str);
01357 GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str);
01358
01359 #endif // GTEST_USES_SIMPLE_RE
01360
01361
01362
01363 GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv);
01364 GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv);
01365
01366 #if GTEST_HAS_DEATH_TEST
01367
01368
01369
01370 GTEST_API_ std::string GetLastErrnoDescription();
01371
01372 # if GTEST_OS_WINDOWS
01373
01374 class AutoHandle {
01375 public:
01376 AutoHandle() : handle_(INVALID_HANDLE_VALUE) {}
01377 explicit AutoHandle(HANDLE handle) : handle_(handle) {}
01378
01379 ~AutoHandle() { Reset(); }
01380
01381 HANDLE Get() const { return handle_; }
01382 void Reset() { Reset(INVALID_HANDLE_VALUE); }
01383 void Reset(HANDLE handle) {
01384 if (handle != handle_) {
01385 if (handle_ != INVALID_HANDLE_VALUE)
01386 ::CloseHandle(handle_);
01387 handle_ = handle;
01388 }
01389 }
01390
01391 private:
01392 HANDLE handle_;
01393
01394 GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle);
01395 };
01396 # endif // GTEST_OS_WINDOWS
01397
01398
01399
01400
01401
01402 template <typename Integer>
01403 bool ParseNaturalNumber(const ::std::string& str, Integer* number) {
01404
01405
01406
01407 if (str.empty() || !IsDigit(str[0])) {
01408 return false;
01409 }
01410 errno = 0;
01411
01412 char* end;
01413
01414
01415
01416 # if GTEST_OS_WINDOWS && !defined(__GNUC__)
01417
01418
01419 typedef unsigned __int64 BiggestConvertible;
01420 const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10);
01421
01422 # else
01423
01424 typedef unsigned long long BiggestConvertible;
01425 const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10);
01426
01427 # endif // GTEST_OS_WINDOWS && !defined(__GNUC__)
01428
01429 const bool parse_success = *end == '\0' && errno == 0;
01430
01431
01432
01433 GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed));
01434
01435 const Integer result = static_cast<Integer>(parsed);
01436 if (parse_success && static_cast<BiggestConvertible>(result) == parsed) {
01437 *number = result;
01438 return true;
01439 }
01440 return false;
01441 }
01442 #endif // GTEST_HAS_DEATH_TEST
01443
01444
01445
01446
01447
01448
01449
01450 class TestResultAccessor {
01451 public:
01452 static void RecordProperty(TestResult* test_result,
01453 const std::string& xml_element,
01454 const TestProperty& property) {
01455 test_result->RecordProperty(xml_element, property);
01456 }
01457
01458 static void ClearTestPartResults(TestResult* test_result) {
01459 test_result->ClearTestPartResults();
01460 }
01461
01462 static const std::vector<testing::TestPartResult>& test_part_results(
01463 const TestResult& test_result) {
01464 return test_result.test_part_results();
01465 }
01466 };
01467
01468 #if GTEST_CAN_STREAM_RESULTS_
01469
01470
01471 class StreamingListener : public EmptyTestEventListener {
01472 public:
01473
01474 class AbstractSocketWriter {
01475 public:
01476 virtual ~AbstractSocketWriter() {}
01477
01478
01479 virtual void Send(const string& message) = 0;
01480
01481
01482 virtual void CloseConnection() {}
01483
01484
01485 void SendLn(const string& message) {
01486 Send(message + "\n");
01487 }
01488 };
01489
01490
01491 class SocketWriter : public AbstractSocketWriter {
01492 public:
01493 SocketWriter(const string& host, const string& port)
01494 : sockfd_(-1), host_name_(host), port_num_(port) {
01495 MakeConnection();
01496 }
01497
01498 virtual ~SocketWriter() {
01499 if (sockfd_ != -1)
01500 CloseConnection();
01501 }
01502
01503
01504 virtual void Send(const string& message) {
01505 GTEST_CHECK_(sockfd_ != -1)
01506 << "Send() can be called only when there is a connection.";
01507
01508 const int len = static_cast<int>(message.length());
01509 if (write(sockfd_, message.c_str(), len) != len) {
01510 GTEST_LOG_(WARNING)
01511 << "stream_result_to: failed to stream to "
01512 << host_name_ << ":" << port_num_;
01513 }
01514 }
01515
01516 private:
01517
01518 void MakeConnection();
01519
01520
01521 void CloseConnection() {
01522 GTEST_CHECK_(sockfd_ != -1)
01523 << "CloseConnection() can be called only when there is a connection.";
01524
01525 close(sockfd_);
01526 sockfd_ = -1;
01527 }
01528
01529 int sockfd_;
01530 const string host_name_;
01531 const string port_num_;
01532
01533 GTEST_DISALLOW_COPY_AND_ASSIGN_(SocketWriter);
01534 };
01535
01536
01537 static string UrlEncode(const char* str);
01538
01539 StreamingListener(const string& host, const string& port)
01540 : socket_writer_(new SocketWriter(host, port)) { Start(); }
01541
01542 explicit StreamingListener(AbstractSocketWriter* socket_writer)
01543 : socket_writer_(socket_writer) { Start(); }
01544
01545 void OnTestProgramStart(const UnitTest& ) {
01546 SendLn("event=TestProgramStart");
01547 }
01548
01549 void OnTestProgramEnd(const UnitTest& unit_test) {
01550
01551
01552 SendLn("event=TestProgramEnd&passed=" + FormatBool(unit_test.Passed()));
01553
01554
01555 socket_writer_->CloseConnection();
01556 }
01557
01558 void OnTestIterationStart(const UnitTest& , int iteration) {
01559 SendLn("event=TestIterationStart&iteration=" +
01560 StreamableToString(iteration));
01561 }
01562
01563 void OnTestIterationEnd(const UnitTest& unit_test, int ) {
01564 SendLn("event=TestIterationEnd&passed=" +
01565 FormatBool(unit_test.Passed()) + "&elapsed_time=" +
01566 StreamableToString(unit_test.elapsed_time()) + "ms");
01567 }
01568
01569 void OnTestCaseStart(const TestCase& test_case) {
01570 SendLn(std::string("event=TestCaseStart&name=") + test_case.name());
01571 }
01572
01573 void OnTestCaseEnd(const TestCase& test_case) {
01574 SendLn("event=TestCaseEnd&passed=" + FormatBool(test_case.Passed())
01575 + "&elapsed_time=" + StreamableToString(test_case.elapsed_time())
01576 + "ms");
01577 }
01578
01579 void OnTestStart(const TestInfo& test_info) {
01580 SendLn(std::string("event=TestStart&name=") + test_info.name());
01581 }
01582
01583 void OnTestEnd(const TestInfo& test_info) {
01584 SendLn("event=TestEnd&passed=" +
01585 FormatBool((test_info.result())->Passed()) +
01586 "&elapsed_time=" +
01587 StreamableToString((test_info.result())->elapsed_time()) + "ms");
01588 }
01589
01590 void OnTestPartResult(const TestPartResult& test_part_result) {
01591 const char* file_name = test_part_result.file_name();
01592 if (file_name == NULL)
01593 file_name = "";
01594 SendLn("event=TestPartResult&file=" + UrlEncode(file_name) +
01595 "&line=" + StreamableToString(test_part_result.line_number()) +
01596 "&message=" + UrlEncode(test_part_result.message()));
01597 }
01598
01599 private:
01600
01601 void SendLn(const string& message) { socket_writer_->SendLn(message); }
01602
01603
01604
01605 void Start() { SendLn("gtest_streaming_protocol_version=1.0"); }
01606
01607 string FormatBool(bool value) { return value ? "1" : "0"; }
01608
01609 const scoped_ptr<AbstractSocketWriter> socket_writer_;
01610
01611 GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener);
01612 };
01613
01614 #endif // GTEST_CAN_STREAM_RESULTS_
01615
01616 }
01617 }
01618
01619 #endif // GTEST_SRC_GTEST_INTERNAL_INL_H_
01620 #undef GTEST_IMPLEMENTATION_
01621
01622 #if GTEST_OS_WINDOWS
01623 # define vsnprintf _vsnprintf
01624 #endif // GTEST_OS_WINDOWS
01625
01626 namespace testing {
01627
01628 using internal::CountIf;
01629 using internal::ForEach;
01630 using internal::GetElementOr;
01631 using internal::Shuffle;
01632
01633
01634
01635
01636
01637 static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
01638
01639
01640
01641
01642 static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*";
01643
01644
01645 static const char kUniversalFilter[] = "*";
01646
01647
01648 static const char kDefaultOutputFile[] = "test_detail.xml";
01649
01650
01651 static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
01652
01653 static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
01654
01655 static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
01656
01657 namespace internal {
01658
01659
01660
01661 const char kStackTraceMarker[] = "\nStack trace:\n";
01662
01663
01664
01665 bool g_help_flag = false;
01666
01667 }
01668
01669 static const char* GetDefaultFilter() {
01670 return kUniversalFilter;
01671 }
01672
01673 GTEST_DEFINE_bool_(
01674 also_run_disabled_tests,
01675 internal::BoolFromGTestEnv("also_run_disabled_tests", false),
01676 "Run disabled tests too, in addition to the tests normally being run.");
01677
01678 GTEST_DEFINE_bool_(
01679 break_on_failure,
01680 internal::BoolFromGTestEnv("break_on_failure", false),
01681 "True iff a failed assertion should be a debugger break-point.");
01682
01683 GTEST_DEFINE_bool_(
01684 catch_exceptions,
01685 internal::BoolFromGTestEnv("catch_exceptions", true),
01686 "True iff " GTEST_NAME_
01687 " should catch exceptions and treat them as test failures.");
01688
01689 GTEST_DEFINE_string_(
01690 color,
01691 internal::StringFromGTestEnv("color", "auto"),
01692 "Whether to use colors in the output. Valid values: yes, no, "
01693 "and auto. 'auto' means to use colors if the output is "
01694 "being sent to a terminal and the TERM environment variable "
01695 "is set to a terminal type that supports colors.");
01696
01697 GTEST_DEFINE_string_(
01698 filter,
01699 internal::StringFromGTestEnv("filter", GetDefaultFilter()),
01700 "A colon-separated list of glob (not regex) patterns "
01701 "for filtering the tests to run, optionally followed by a "
01702 "'-' and a : separated list of negative patterns (tests to "
01703 "exclude). A test is run if it matches one of the positive "
01704 "patterns and does not match any of the negative patterns.");
01705
01706 GTEST_DEFINE_bool_(list_tests, false,
01707 "List all tests without running them.");
01708
01709 GTEST_DEFINE_string_(
01710 output,
01711 internal::StringFromGTestEnv("output", ""),
01712 "A format (currently must be \"xml\"), optionally followed "
01713 "by a colon and an output file name or directory. A directory "
01714 "is indicated by a trailing pathname separator. "
01715 "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
01716 "If a directory is specified, output files will be created "
01717 "within that directory, with file-names based on the test "
01718 "executable's name and, if necessary, made unique by adding "
01719 "digits.");
01720
01721 GTEST_DEFINE_bool_(
01722 print_time,
01723 internal::BoolFromGTestEnv("print_time", true),
01724 "True iff " GTEST_NAME_
01725 " should display elapsed time in text output.");
01726
01727 GTEST_DEFINE_int32_(
01728 random_seed,
01729 internal::Int32FromGTestEnv("random_seed", 0),
01730 "Random number seed to use when shuffling test orders. Must be in range "
01731 "[1, 99999], or 0 to use a seed based on the current time.");
01732
01733 GTEST_DEFINE_int32_(
01734 repeat,
01735 internal::Int32FromGTestEnv("repeat", 1),
01736 "How many times to repeat each test. Specify a negative number "
01737 "for repeating forever. Useful for shaking out flaky tests.");
01738
01739 GTEST_DEFINE_bool_(
01740 show_internal_stack_frames, false,
01741 "True iff " GTEST_NAME_ " should include internal stack frames when "
01742 "printing test failure stack traces.");
01743
01744 GTEST_DEFINE_bool_(
01745 shuffle,
01746 internal::BoolFromGTestEnv("shuffle", false),
01747 "True iff " GTEST_NAME_
01748 " should randomize tests' order on every run.");
01749
01750 GTEST_DEFINE_int32_(
01751 stack_trace_depth,
01752 internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
01753 "The maximum number of stack frames to print when an "
01754 "assertion fails. The valid range is 0 through 100, inclusive.");
01755
01756 GTEST_DEFINE_string_(
01757 stream_result_to,
01758 internal::StringFromGTestEnv("stream_result_to", ""),
01759 "This flag specifies the host name and the port number on which to stream "
01760 "test results. Example: \"localhost:555\". The flag is effective only on "
01761 "Linux.");
01762
01763 GTEST_DEFINE_bool_(
01764 throw_on_failure,
01765 internal::BoolFromGTestEnv("throw_on_failure", false),
01766 "When this flag is specified, a failed assertion will throw an exception "
01767 "if exceptions are enabled or exit the program with a non-zero code "
01768 "otherwise.");
01769
01770 namespace internal {
01771
01772
01773
01774
01775 UInt32 Random::Generate(UInt32 range) {
01776
01777 state_ = (1103515245U*state_ + 12345U) % kMaxRange;
01778
01779 GTEST_CHECK_(range > 0)
01780 << "Cannot generate a number in the range [0, 0).";
01781 GTEST_CHECK_(range <= kMaxRange)
01782 << "Generation of a number in [0, " << range << ") was requested, "
01783 << "but this can only generate numbers in [0, " << kMaxRange << ").";
01784
01785
01786
01787
01788 return state_ % range;
01789 }
01790
01791
01792
01793
01794
01795
01796
01797
01798
01799 GTEST_API_ int g_init_gtest_count = 0;
01800 static bool GTestIsInitialized() { return g_init_gtest_count != 0; }
01801
01802
01803
01804
01805 static int SumOverTestCaseList(const std::vector<TestCase*>& case_list,
01806 int (TestCase::*method)() const) {
01807 int sum = 0;
01808 for (size_t i = 0; i < case_list.size(); i++) {
01809 sum += (case_list[i]->*method)();
01810 }
01811 return sum;
01812 }
01813
01814
01815 static bool TestCasePassed(const TestCase* test_case) {
01816 return test_case->should_run() && test_case->Passed();
01817 }
01818
01819
01820 static bool TestCaseFailed(const TestCase* test_case) {
01821 return test_case->should_run() && test_case->Failed();
01822 }
01823
01824
01825
01826 static bool ShouldRunTestCase(const TestCase* test_case) {
01827 return test_case->should_run();
01828 }
01829
01830
01831 AssertHelper::AssertHelper(TestPartResult::Type type,
01832 const char* file,
01833 int line,
01834 const char* message)
01835 : data_(new AssertHelperData(type, file, line, message)) {
01836 }
01837
01838 AssertHelper::~AssertHelper() {
01839 delete data_;
01840 }
01841
01842
01843 void AssertHelper::operator=(const Message& message) const {
01844 UnitTest::GetInstance()->
01845 AddTestPartResult(data_->type, data_->file, data_->line,
01846 AppendUserMessage(data_->message, message),
01847 UnitTest::GetInstance()->impl()
01848 ->CurrentOsStackTraceExceptTop(1)
01849
01850 );
01851 }
01852
01853
01854 GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex);
01855
01856
01857 std::string g_executable_path;
01858
01859
01860
01861 FilePath GetCurrentExecutableName() {
01862 FilePath result;
01863
01864 #if GTEST_OS_WINDOWS
01865 result.Set(FilePath(g_executable_path).RemoveExtension("exe"));
01866 #else
01867 result.Set(FilePath(g_executable_path));
01868 #endif // GTEST_OS_WINDOWS
01869
01870 return result.RemoveDirectoryName();
01871 }
01872
01873
01874
01875
01876 std::string UnitTestOptions::GetOutputFormat() {
01877 const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
01878 if (gtest_output_flag == NULL) return std::string("");
01879
01880 const char* const colon = strchr(gtest_output_flag, ':');
01881 return (colon == NULL) ?
01882 std::string(gtest_output_flag) :
01883 std::string(gtest_output_flag, colon - gtest_output_flag);
01884 }
01885
01886
01887
01888 std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
01889 const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
01890 if (gtest_output_flag == NULL)
01891 return "";
01892
01893 const char* const colon = strchr(gtest_output_flag, ':');
01894 if (colon == NULL)
01895 return internal::FilePath::ConcatPaths(
01896 internal::FilePath(
01897 UnitTest::GetInstance()->original_working_dir()),
01898 internal::FilePath(kDefaultOutputFile)).string();
01899
01900 internal::FilePath output_name(colon + 1);
01901 if (!output_name.IsAbsolutePath())
01902
01903
01904
01905
01906 output_name = internal::FilePath::ConcatPaths(
01907 internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
01908 internal::FilePath(colon + 1));
01909
01910 if (!output_name.IsDirectory())
01911 return output_name.string();
01912
01913 internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
01914 output_name, internal::GetCurrentExecutableName(),
01915 GetOutputFormat().c_str()));
01916 return result.string();
01917 }
01918
01919
01920
01921
01922
01923
01924 bool UnitTestOptions::PatternMatchesString(const char *pattern,
01925 const char *str) {
01926 switch (*pattern) {
01927 case '\0':
01928 case ':':
01929 return *str == '\0';
01930 case '?':
01931 return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);
01932 case '*':
01933 return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||
01934 PatternMatchesString(pattern + 1, str);
01935 default:
01936 return *pattern == *str &&
01937 PatternMatchesString(pattern + 1, str + 1);
01938 }
01939 }
01940
01941 bool UnitTestOptions::MatchesFilter(
01942 const std::string& name, const char* filter) {
01943 const char *cur_pattern = filter;
01944 for (;;) {
01945 if (PatternMatchesString(cur_pattern, name.c_str())) {
01946 return true;
01947 }
01948
01949
01950 cur_pattern = strchr(cur_pattern, ':');
01951
01952
01953 if (cur_pattern == NULL) {
01954 return false;
01955 }
01956
01957
01958 cur_pattern++;
01959 }
01960 }
01961
01962
01963
01964 bool UnitTestOptions::FilterMatchesTest(const std::string &test_case_name,
01965 const std::string &test_name) {
01966 const std::string& full_name = test_case_name + "." + test_name.c_str();
01967
01968
01969
01970 const char* const p = GTEST_FLAG(filter).c_str();
01971 const char* const dash = strchr(p, '-');
01972 std::string positive;
01973 std::string negative;
01974 if (dash == NULL) {
01975 positive = GTEST_FLAG(filter).c_str();
01976 negative = "";
01977 } else {
01978 positive = std::string(p, dash);
01979 negative = std::string(dash + 1);
01980 if (positive.empty()) {
01981
01982 positive = kUniversalFilter;
01983 }
01984 }
01985
01986
01987
01988 return (MatchesFilter(full_name, positive.c_str()) &&
01989 !MatchesFilter(full_name, negative.c_str()));
01990 }
01991
01992 #if GTEST_HAS_SEH
01993
01994
01995
01996 int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
01997
01998
01999
02000
02001
02002
02003
02004
02005 const DWORD kCxxExceptionCode = 0xe06d7363;
02006
02007 bool should_handle = true;
02008
02009 if (!GTEST_FLAG(catch_exceptions))
02010 should_handle = false;
02011 else if (exception_code == EXCEPTION_BREAKPOINT)
02012 should_handle = false;
02013 else if (exception_code == kCxxExceptionCode)
02014 should_handle = false;
02015
02016 return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
02017 }
02018 #endif // GTEST_HAS_SEH
02019
02020 }
02021
02022
02023
02024
02025 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
02026 TestPartResultArray* result)
02027 : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
02028 result_(result) {
02029 Init();
02030 }
02031
02032
02033
02034
02035 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
02036 InterceptMode intercept_mode, TestPartResultArray* result)
02037 : intercept_mode_(intercept_mode),
02038 result_(result) {
02039 Init();
02040 }
02041
02042 void ScopedFakeTestPartResultReporter::Init() {
02043 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
02044 if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
02045 old_reporter_ = impl->GetGlobalTestPartResultReporter();
02046 impl->SetGlobalTestPartResultReporter(this);
02047 } else {
02048 old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
02049 impl->SetTestPartResultReporterForCurrentThread(this);
02050 }
02051 }
02052
02053
02054
02055 ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
02056 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
02057 if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
02058 impl->SetGlobalTestPartResultReporter(old_reporter_);
02059 } else {
02060 impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
02061 }
02062 }
02063
02064
02065
02066 void ScopedFakeTestPartResultReporter::ReportTestPartResult(
02067 const TestPartResult& result) {
02068 result_->Append(result);
02069 }
02070
02071 namespace internal {
02072
02073
02074
02075
02076
02077
02078
02079
02080
02081
02082 TypeId GetTestTypeId() {
02083 return GetTypeId<Test>();
02084 }
02085
02086
02087
02088 extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
02089
02090
02091
02092
02093 AssertionResult HasOneFailure(const char* ,
02094 const char* ,
02095 const char* ,
02096 const TestPartResultArray& results,
02097 TestPartResult::Type type,
02098 const string& substr) {
02099 const std::string expected(type == TestPartResult::kFatalFailure ?
02100 "1 fatal failure" :
02101 "1 non-fatal failure");
02102 Message msg;
02103 if (results.size() != 1) {
02104 msg << "Expected: " << expected << "\n"
02105 << " Actual: " << results.size() << " failures";
02106 for (int i = 0; i < results.size(); i++) {
02107 msg << "\n" << results.GetTestPartResult(i);
02108 }
02109 return AssertionFailure() << msg;
02110 }
02111
02112 const TestPartResult& r = results.GetTestPartResult(0);
02113 if (r.type() != type) {
02114 return AssertionFailure() << "Expected: " << expected << "\n"
02115 << " Actual:\n"
02116 << r;
02117 }
02118
02119 if (strstr(r.message(), substr.c_str()) == NULL) {
02120 return AssertionFailure() << "Expected: " << expected << " containing \""
02121 << substr << "\"\n"
02122 << " Actual:\n"
02123 << r;
02124 }
02125
02126 return AssertionSuccess();
02127 }
02128
02129
02130
02131
02132 SingleFailureChecker:: SingleFailureChecker(
02133 const TestPartResultArray* results,
02134 TestPartResult::Type type,
02135 const string& substr)
02136 : results_(results),
02137 type_(type),
02138 substr_(substr) {}
02139
02140
02141
02142
02143
02144 SingleFailureChecker::~SingleFailureChecker() {
02145 EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_);
02146 }
02147
02148 DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
02149 UnitTestImpl* unit_test) : unit_test_(unit_test) {}
02150
02151 void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
02152 const TestPartResult& result) {
02153 unit_test_->current_test_result()->AddTestPartResult(result);
02154 unit_test_->listeners()->repeater()->OnTestPartResult(result);
02155 }
02156
02157 DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
02158 UnitTestImpl* unit_test) : unit_test_(unit_test) {}
02159
02160 void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
02161 const TestPartResult& result) {
02162 unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
02163 }
02164
02165
02166 TestPartResultReporterInterface*
02167 UnitTestImpl::GetGlobalTestPartResultReporter() {
02168 internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
02169 return global_test_part_result_repoter_;
02170 }
02171
02172
02173 void UnitTestImpl::SetGlobalTestPartResultReporter(
02174 TestPartResultReporterInterface* reporter) {
02175 internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
02176 global_test_part_result_repoter_ = reporter;
02177 }
02178
02179
02180 TestPartResultReporterInterface*
02181 UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
02182 return per_thread_test_part_result_reporter_.get();
02183 }
02184
02185
02186 void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
02187 TestPartResultReporterInterface* reporter) {
02188 per_thread_test_part_result_reporter_.set(reporter);
02189 }
02190
02191
02192 int UnitTestImpl::successful_test_case_count() const {
02193 return CountIf(test_cases_, TestCasePassed);
02194 }
02195
02196
02197 int UnitTestImpl::failed_test_case_count() const {
02198 return CountIf(test_cases_, TestCaseFailed);
02199 }
02200
02201
02202 int UnitTestImpl::total_test_case_count() const {
02203 return static_cast<int>(test_cases_.size());
02204 }
02205
02206
02207
02208 int UnitTestImpl::test_case_to_run_count() const {
02209 return CountIf(test_cases_, ShouldRunTestCase);
02210 }
02211
02212
02213 int UnitTestImpl::successful_test_count() const {
02214 return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count);
02215 }
02216
02217
02218 int UnitTestImpl::failed_test_count() const {
02219 return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count);
02220 }
02221
02222
02223 int UnitTestImpl::reportable_disabled_test_count() const {
02224 return SumOverTestCaseList(test_cases_,
02225 &TestCase::reportable_disabled_test_count);
02226 }
02227
02228
02229 int UnitTestImpl::disabled_test_count() const {
02230 return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count);
02231 }
02232
02233
02234 int UnitTestImpl::reportable_test_count() const {
02235 return SumOverTestCaseList(test_cases_, &TestCase::reportable_test_count);
02236 }
02237
02238
02239 int UnitTestImpl::total_test_count() const {
02240 return SumOverTestCaseList(test_cases_, &TestCase::total_test_count);
02241 }
02242
02243
02244 int UnitTestImpl::test_to_run_count() const {
02245 return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count);
02246 }
02247
02248
02249
02250
02251
02252
02253
02254
02255
02256
02257
02258 std::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
02259 (void)skip_count;
02260 return "";
02261 }
02262
02263
02264 TimeInMillis GetTimeInMillis() {
02265 #if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__)
02266
02267
02268 const TimeInMillis kJavaEpochToWinFileTimeDelta =
02269 static_cast<TimeInMillis>(116444736UL) * 100000UL;
02270 const DWORD kTenthMicrosInMilliSecond = 10000;
02271
02272 SYSTEMTIME now_systime;
02273 FILETIME now_filetime;
02274 ULARGE_INTEGER now_int64;
02275
02276
02277 GetSystemTime(&now_systime);
02278 if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
02279 now_int64.LowPart = now_filetime.dwLowDateTime;
02280 now_int64.HighPart = now_filetime.dwHighDateTime;
02281 now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
02282 kJavaEpochToWinFileTimeDelta;
02283 return now_int64.QuadPart;
02284 }
02285 return 0;
02286 #elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_
02287 __timeb64 now;
02288
02289 # ifdef _MSC_VER
02290
02291
02292
02293
02294
02295 # pragma warning(push) // Saves the current warning state.
02296 # pragma warning(disable:4996) // Temporarily disables warning 4996.
02297 _ftime64(&now);
02298 # pragma warning(pop) // Restores the warning state.
02299 # else
02300
02301 _ftime64(&now);
02302
02303 # endif // _MSC_VER
02304
02305 return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
02306 #elif GTEST_HAS_GETTIMEOFDAY_
02307 struct timeval now;
02308 gettimeofday(&now, NULL);
02309 return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
02310 #else
02311 # error "Don't know how to get the current time on your system."
02312 #endif
02313 }
02314
02315
02316
02317
02318
02319 #if GTEST_OS_WINDOWS_MOBILE
02320
02321
02322
02323
02324 LPCWSTR String::AnsiToUtf16(const char* ansi) {
02325 if (!ansi) return NULL;
02326 const int length = strlen(ansi);
02327 const int unicode_length =
02328 MultiByteToWideChar(CP_ACP, 0, ansi, length,
02329 NULL, 0);
02330 WCHAR* unicode = new WCHAR[unicode_length + 1];
02331 MultiByteToWideChar(CP_ACP, 0, ansi, length,
02332 unicode, unicode_length);
02333 unicode[unicode_length] = 0;
02334 return unicode;
02335 }
02336
02337
02338
02339
02340
02341 const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
02342 if (!utf16_str) return NULL;
02343 const int ansi_length =
02344 WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
02345 NULL, 0, NULL, NULL);
02346 char* ansi = new char[ansi_length + 1];
02347 WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
02348 ansi, ansi_length, NULL, NULL);
02349 ansi[ansi_length] = 0;
02350 return ansi;
02351 }
02352
02353 #endif // GTEST_OS_WINDOWS_MOBILE
02354
02355
02356
02357
02358
02359
02360 bool String::CStringEquals(const char * lhs, const char * rhs) {
02361 if ( lhs == NULL ) return rhs == NULL;
02362
02363 if ( rhs == NULL ) return false;
02364
02365 return strcmp(lhs, rhs) == 0;
02366 }
02367
02368 #if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
02369
02370
02371
02372 static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
02373 Message* msg) {
02374 for (size_t i = 0; i != length; ) {
02375 if (wstr[i] != L'\0') {
02376 *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
02377 while (i != length && wstr[i] != L'\0')
02378 i++;
02379 } else {
02380 *msg << '\0';
02381 i++;
02382 }
02383 }
02384 }
02385
02386 #endif // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
02387
02388 }
02389
02390
02391
02392
02393
02394
02395 Message::Message() : ss_(new ::std::stringstream) {
02396
02397
02398 *ss_ << std::setprecision(std::numeric_limits<double>::digits10 + 2);
02399 }
02400
02401
02402
02403 Message& Message::operator <<(const wchar_t* wide_c_str) {
02404 return *this << internal::String::ShowWideCString(wide_c_str);
02405 }
02406 Message& Message::operator <<(wchar_t* wide_c_str) {
02407 return *this << internal::String::ShowWideCString(wide_c_str);
02408 }
02409
02410 #if GTEST_HAS_STD_WSTRING
02411
02412
02413 Message& Message::operator <<(const ::std::wstring& wstr) {
02414 internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
02415 return *this;
02416 }
02417 #endif // GTEST_HAS_STD_WSTRING
02418
02419 #if GTEST_HAS_GLOBAL_WSTRING
02420
02421
02422 Message& Message::operator <<(const ::wstring& wstr) {
02423 internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
02424 return *this;
02425 }
02426 #endif // GTEST_HAS_GLOBAL_WSTRING
02427
02428
02429
02430 std::string Message::GetString() const {
02431 return internal::StringStreamToString(ss_.get());
02432 }
02433
02434
02435
02436 AssertionResult::AssertionResult(const AssertionResult& other)
02437 : success_(other.success_),
02438 message_(other.message_.get() != NULL ?
02439 new ::std::string(*other.message_) :
02440 static_cast< ::std::string*>(NULL)) {
02441 }
02442
02443
02444 AssertionResult AssertionResult::operator!() const {
02445 AssertionResult negation(!success_);
02446 if (message_.get() != NULL)
02447 negation << *message_;
02448 return negation;
02449 }
02450
02451
02452 AssertionResult AssertionSuccess() {
02453 return AssertionResult(true);
02454 }
02455
02456
02457 AssertionResult AssertionFailure() {
02458 return AssertionResult(false);
02459 }
02460
02461
02462
02463 AssertionResult AssertionFailure(const Message& message) {
02464 return AssertionFailure() << message;
02465 }
02466
02467 namespace internal {
02468
02469
02470
02471
02472
02473
02474
02475
02476
02477
02478
02479
02480
02481
02482
02483
02484 AssertionResult EqFailure(const char* expected_expression,
02485 const char* actual_expression,
02486 const std::string& expected_value,
02487 const std::string& actual_value,
02488 bool ignoring_case) {
02489 Message msg;
02490 msg << "Value of: " << actual_expression;
02491 if (actual_value != actual_expression) {
02492 msg << "\n Actual: " << actual_value;
02493 }
02494
02495 msg << "\nExpected: " << expected_expression;
02496 if (ignoring_case) {
02497 msg << " (ignoring case)";
02498 }
02499 if (expected_value != expected_expression) {
02500 msg << "\nWhich is: " << expected_value;
02501 }
02502
02503 return AssertionFailure() << msg;
02504 }
02505
02506
02507 std::string GetBoolAssertionFailureMessage(
02508 const AssertionResult& assertion_result,
02509 const char* expression_text,
02510 const char* actual_predicate_value,
02511 const char* expected_predicate_value) {
02512 const char* actual_message = assertion_result.message();
02513 Message msg;
02514 msg << "Value of: " << expression_text
02515 << "\n Actual: " << actual_predicate_value;
02516 if (actual_message[0] != '\0')
02517 msg << " (" << actual_message << ")";
02518 msg << "\nExpected: " << expected_predicate_value;
02519 return msg.GetString();
02520 }
02521
02522
02523 AssertionResult DoubleNearPredFormat(const char* expr1,
02524 const char* expr2,
02525 const char* abs_error_expr,
02526 double val1,
02527 double val2,
02528 double abs_error) {
02529 const double diff = fabs(val1 - val2);
02530 if (diff <= abs_error) return AssertionSuccess();
02531
02532
02533
02534 return AssertionFailure()
02535 << "The difference between " << expr1 << " and " << expr2
02536 << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"
02537 << expr1 << " evaluates to " << val1 << ",\n"
02538 << expr2 << " evaluates to " << val2 << ", and\n"
02539 << abs_error_expr << " evaluates to " << abs_error << ".";
02540 }
02541
02542
02543
02544 template <typename RawType>
02545 AssertionResult FloatingPointLE(const char* expr1,
02546 const char* expr2,
02547 RawType val1,
02548 RawType val2) {
02549
02550 if (val1 < val2) {
02551 return AssertionSuccess();
02552 }
02553
02554
02555 const FloatingPoint<RawType> lhs(val1), rhs(val2);
02556 if (lhs.AlmostEquals(rhs)) {
02557 return AssertionSuccess();
02558 }
02559
02560
02561
02562
02563
02564 ::std::stringstream val1_ss;
02565 val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
02566 << val1;
02567
02568 ::std::stringstream val2_ss;
02569 val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
02570 << val2;
02571
02572 return AssertionFailure()
02573 << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
02574 << " Actual: " << StringStreamToString(&val1_ss) << " vs "
02575 << StringStreamToString(&val2_ss);
02576 }
02577
02578 }
02579
02580
02581
02582 AssertionResult FloatLE(const char* expr1, const char* expr2,
02583 float val1, float val2) {
02584 return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
02585 }
02586
02587
02588
02589 AssertionResult DoubleLE(const char* expr1, const char* expr2,
02590 double val1, double val2) {
02591 return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
02592 }
02593
02594 namespace internal {
02595
02596
02597
02598 AssertionResult CmpHelperEQ(const char* expected_expression,
02599 const char* actual_expression,
02600 BiggestInt expected,
02601 BiggestInt actual) {
02602 if (expected == actual) {
02603 return AssertionSuccess();
02604 }
02605
02606 return EqFailure(expected_expression,
02607 actual_expression,
02608 FormatForComparisonFailureMessage(expected, actual),
02609 FormatForComparisonFailureMessage(actual, expected),
02610 false);
02611 }
02612
02613
02614
02615
02616 #define GTEST_IMPL_CMP_HELPER_(op_name, op)\
02617 AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
02618 BiggestInt val1, BiggestInt val2) {\
02619 if (val1 op val2) {\
02620 return AssertionSuccess();\
02621 } else {\
02622 return AssertionFailure() \
02623 << "Expected: (" << expr1 << ") " #op " (" << expr2\
02624 << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
02625 << " vs " << FormatForComparisonFailureMessage(val2, val1);\
02626 }\
02627 }
02628
02629
02630
02631 GTEST_IMPL_CMP_HELPER_(NE, !=)
02632
02633
02634 GTEST_IMPL_CMP_HELPER_(LE, <=)
02635
02636
02637 GTEST_IMPL_CMP_HELPER_(LT, < )
02638
02639
02640 GTEST_IMPL_CMP_HELPER_(GE, >=)
02641
02642
02643 GTEST_IMPL_CMP_HELPER_(GT, > )
02644
02645 #undef GTEST_IMPL_CMP_HELPER_
02646
02647
02648 AssertionResult CmpHelperSTREQ(const char* expected_expression,
02649 const char* actual_expression,
02650 const char* expected,
02651 const char* actual) {
02652 if (String::CStringEquals(expected, actual)) {
02653 return AssertionSuccess();
02654 }
02655
02656 return EqFailure(expected_expression,
02657 actual_expression,
02658 PrintToString(expected),
02659 PrintToString(actual),
02660 false);
02661 }
02662
02663
02664 AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression,
02665 const char* actual_expression,
02666 const char* expected,
02667 const char* actual) {
02668 if (String::CaseInsensitiveCStringEquals(expected, actual)) {
02669 return AssertionSuccess();
02670 }
02671
02672 return EqFailure(expected_expression,
02673 actual_expression,
02674 PrintToString(expected),
02675 PrintToString(actual),
02676 true);
02677 }
02678
02679
02680 AssertionResult CmpHelperSTRNE(const char* s1_expression,
02681 const char* s2_expression,
02682 const char* s1,
02683 const char* s2) {
02684 if (!String::CStringEquals(s1, s2)) {
02685 return AssertionSuccess();
02686 } else {
02687 return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
02688 << s2_expression << "), actual: \""
02689 << s1 << "\" vs \"" << s2 << "\"";
02690 }
02691 }
02692
02693
02694 AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
02695 const char* s2_expression,
02696 const char* s1,
02697 const char* s2) {
02698 if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
02699 return AssertionSuccess();
02700 } else {
02701 return AssertionFailure()
02702 << "Expected: (" << s1_expression << ") != ("
02703 << s2_expression << ") (ignoring case), actual: \""
02704 << s1 << "\" vs \"" << s2 << "\"";
02705 }
02706 }
02707
02708 }
02709
02710 namespace {
02711
02712
02713
02714
02715
02716
02717
02718 bool IsSubstringPred(const char* needle, const char* haystack) {
02719 if (needle == NULL || haystack == NULL)
02720 return needle == haystack;
02721
02722 return strstr(haystack, needle) != NULL;
02723 }
02724
02725 bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
02726 if (needle == NULL || haystack == NULL)
02727 return needle == haystack;
02728
02729 return wcsstr(haystack, needle) != NULL;
02730 }
02731
02732
02733 template <typename StringType>
02734 bool IsSubstringPred(const StringType& needle,
02735 const StringType& haystack) {
02736 return haystack.find(needle) != StringType::npos;
02737 }
02738
02739
02740
02741
02742
02743 template <typename StringType>
02744 AssertionResult IsSubstringImpl(
02745 bool expected_to_be_substring,
02746 const char* needle_expr, const char* haystack_expr,
02747 const StringType& needle, const StringType& haystack) {
02748 if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
02749 return AssertionSuccess();
02750
02751 const bool is_wide_string = sizeof(needle[0]) > 1;
02752 const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
02753 return AssertionFailure()
02754 << "Value of: " << needle_expr << "\n"
02755 << " Actual: " << begin_string_quote << needle << "\"\n"
02756 << "Expected: " << (expected_to_be_substring ? "" : "not ")
02757 << "a substring of " << haystack_expr << "\n"
02758 << "Which is: " << begin_string_quote << haystack << "\"";
02759 }
02760
02761 }
02762
02763
02764
02765
02766
02767 AssertionResult IsSubstring(
02768 const char* needle_expr, const char* haystack_expr,
02769 const char* needle, const char* haystack) {
02770 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
02771 }
02772
02773 AssertionResult IsSubstring(
02774 const char* needle_expr, const char* haystack_expr,
02775 const wchar_t* needle, const wchar_t* haystack) {
02776 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
02777 }
02778
02779 AssertionResult IsNotSubstring(
02780 const char* needle_expr, const char* haystack_expr,
02781 const char* needle, const char* haystack) {
02782 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
02783 }
02784
02785 AssertionResult IsNotSubstring(
02786 const char* needle_expr, const char* haystack_expr,
02787 const wchar_t* needle, const wchar_t* haystack) {
02788 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
02789 }
02790
02791 AssertionResult IsSubstring(
02792 const char* needle_expr, const char* haystack_expr,
02793 const ::std::string& needle, const ::std::string& haystack) {
02794 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
02795 }
02796
02797 AssertionResult IsNotSubstring(
02798 const char* needle_expr, const char* haystack_expr,
02799 const ::std::string& needle, const ::std::string& haystack) {
02800 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
02801 }
02802
02803 #if GTEST_HAS_STD_WSTRING
02804 AssertionResult IsSubstring(
02805 const char* needle_expr, const char* haystack_expr,
02806 const ::std::wstring& needle, const ::std::wstring& haystack) {
02807 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
02808 }
02809
02810 AssertionResult IsNotSubstring(
02811 const char* needle_expr, const char* haystack_expr,
02812 const ::std::wstring& needle, const ::std::wstring& haystack) {
02813 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
02814 }
02815 #endif // GTEST_HAS_STD_WSTRING
02816
02817 namespace internal {
02818
02819 #if GTEST_OS_WINDOWS
02820
02821 namespace {
02822
02823
02824 AssertionResult HRESULTFailureHelper(const char* expr,
02825 const char* expected,
02826 long hr) {
02827 # if GTEST_OS_WINDOWS_MOBILE
02828
02829
02830 const char error_text[] = "";
02831
02832 # else
02833
02834
02835
02836
02837 const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
02838 FORMAT_MESSAGE_IGNORE_INSERTS;
02839 const DWORD kBufSize = 4096;
02840
02841 char error_text[kBufSize] = { '\0' };
02842 DWORD message_length = ::FormatMessageA(kFlags,
02843 0,
02844 hr,
02845 0,
02846 error_text,
02847 kBufSize,
02848 NULL);
02849
02850 for (; message_length && IsSpace(error_text[message_length - 1]);
02851 --message_length) {
02852 error_text[message_length - 1] = '\0';
02853 }
02854
02855 # endif // GTEST_OS_WINDOWS_MOBILE
02856
02857 const std::string error_hex("0x" + String::FormatHexInt(hr));
02858 return ::testing::AssertionFailure()
02859 << "Expected: " << expr << " " << expected << ".\n"
02860 << " Actual: " << error_hex << " " << error_text << "\n";
02861 }
02862
02863 }
02864
02865 AssertionResult IsHRESULTSuccess(const char* expr, long hr) {
02866 if (SUCCEEDED(hr)) {
02867 return AssertionSuccess();
02868 }
02869 return HRESULTFailureHelper(expr, "succeeds", hr);
02870 }
02871
02872 AssertionResult IsHRESULTFailure(const char* expr, long hr) {
02873 if (FAILED(hr)) {
02874 return AssertionSuccess();
02875 }
02876 return HRESULTFailureHelper(expr, "fails", hr);
02877 }
02878
02879 #endif // GTEST_OS_WINDOWS
02880
02881
02882
02883
02884
02885
02886
02887
02888
02889
02890
02891
02892
02893
02894 const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) << 7) - 1;
02895
02896
02897 const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1;
02898
02899
02900 const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2*6)) - 1;
02901
02902
02903 const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3*6)) - 1;
02904
02905
02906
02907
02908 inline UInt32 ChopLowBits(UInt32* bits, int n) {
02909 const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1);
02910 *bits >>= n;
02911 return low_bits;
02912 }
02913
02914
02915
02916
02917
02918
02919
02920 std::string CodePointToUtf8(UInt32 code_point) {
02921 if (code_point > kMaxCodePoint4) {
02922 return "(Invalid Unicode 0x" + String::FormatHexInt(code_point) + ")";
02923 }
02924
02925 char str[5];
02926 if (code_point <= kMaxCodePoint1) {
02927 str[1] = '\0';
02928 str[0] = static_cast<char>(code_point);
02929 } else if (code_point <= kMaxCodePoint2) {
02930 str[2] = '\0';
02931 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));
02932 str[0] = static_cast<char>(0xC0 | code_point);
02933 } else if (code_point <= kMaxCodePoint3) {
02934 str[3] = '\0';
02935 str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));
02936 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));
02937 str[0] = static_cast<char>(0xE0 | code_point);
02938 } else {
02939 str[4] = '\0';
02940 str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));
02941 str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));
02942 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));
02943 str[0] = static_cast<char>(0xF0 | code_point);
02944 }
02945 return str;
02946 }
02947
02948
02949
02950
02951
02952
02953
02954
02955 inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
02956 return sizeof(wchar_t) == 2 &&
02957 (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;
02958 }
02959
02960
02961 inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first,
02962 wchar_t second) {
02963 const UInt32 mask = (1 << 10) - 1;
02964 return (sizeof(wchar_t) == 2) ?
02965 (((first & mask) << 10) | (second & mask)) + 0x10000 :
02966
02967
02968 static_cast<UInt32>(first);
02969 }
02970
02971
02972
02973
02974
02975
02976
02977
02978
02979
02980
02981
02982
02983
02984 std::string WideStringToUtf8(const wchar_t* str, int num_chars) {
02985 if (num_chars == -1)
02986 num_chars = static_cast<int>(wcslen(str));
02987
02988 ::std::stringstream stream;
02989 for (int i = 0; i < num_chars; ++i) {
02990 UInt32 unicode_code_point;
02991
02992 if (str[i] == L'\0') {
02993 break;
02994 } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
02995 unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i],
02996 str[i + 1]);
02997 i++;
02998 } else {
02999 unicode_code_point = static_cast<UInt32>(str[i]);
03000 }
03001
03002 stream << CodePointToUtf8(unicode_code_point);
03003 }
03004 return StringStreamToString(&stream);
03005 }
03006
03007
03008
03009 std::string String::ShowWideCString(const wchar_t * wide_c_str) {
03010 if (wide_c_str == NULL) return "(null)";
03011
03012 return internal::WideStringToUtf8(wide_c_str, -1);
03013 }
03014
03015
03016
03017
03018
03019
03020
03021 bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {
03022 if (lhs == NULL) return rhs == NULL;
03023
03024 if (rhs == NULL) return false;
03025
03026 return wcscmp(lhs, rhs) == 0;
03027 }
03028
03029
03030 AssertionResult CmpHelperSTREQ(const char* expected_expression,
03031 const char* actual_expression,
03032 const wchar_t* expected,
03033 const wchar_t* actual) {
03034 if (String::WideCStringEquals(expected, actual)) {
03035 return AssertionSuccess();
03036 }
03037
03038 return EqFailure(expected_expression,
03039 actual_expression,
03040 PrintToString(expected),
03041 PrintToString(actual),
03042 false);
03043 }
03044
03045
03046 AssertionResult CmpHelperSTRNE(const char* s1_expression,
03047 const char* s2_expression,
03048 const wchar_t* s1,
03049 const wchar_t* s2) {
03050 if (!String::WideCStringEquals(s1, s2)) {
03051 return AssertionSuccess();
03052 }
03053
03054 return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
03055 << s2_expression << "), actual: "
03056 << PrintToString(s1)
03057 << " vs " << PrintToString(s2);
03058 }
03059
03060
03061
03062
03063
03064
03065
03066 bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) {
03067 if (lhs == NULL)
03068 return rhs == NULL;
03069 if (rhs == NULL)
03070 return false;
03071 return posix::StrCaseCmp(lhs, rhs) == 0;
03072 }
03073
03074
03075
03076
03077
03078
03079
03080
03081
03082
03083
03084
03085
03086 bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
03087 const wchar_t* rhs) {
03088 if (lhs == NULL) return rhs == NULL;
03089
03090 if (rhs == NULL) return false;
03091
03092 #if GTEST_OS_WINDOWS
03093 return _wcsicmp(lhs, rhs) == 0;
03094 #elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID
03095 return wcscasecmp(lhs, rhs) == 0;
03096 #else
03097
03098
03099 wint_t left, right;
03100 do {
03101 left = towlower(*lhs++);
03102 right = towlower(*rhs++);
03103 } while (left && left == right);
03104 return left == right;
03105 #endif // OS selector
03106 }
03107
03108
03109
03110 bool String::EndsWithCaseInsensitive(
03111 const std::string& str, const std::string& suffix) {
03112 const size_t str_len = str.length();
03113 const size_t suffix_len = suffix.length();
03114 return (str_len >= suffix_len) &&
03115 CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len,
03116 suffix.c_str());
03117 }
03118
03119
03120 std::string String::FormatIntWidth2(int value) {
03121 std::stringstream ss;
03122 ss << std::setfill('0') << std::setw(2) << value;
03123 return ss.str();
03124 }
03125
03126
03127 std::string String::FormatHexInt(int value) {
03128 std::stringstream ss;
03129 ss << std::hex << std::uppercase << value;
03130 return ss.str();
03131 }
03132
03133
03134 std::string String::FormatByte(unsigned char value) {
03135 std::stringstream ss;
03136 ss << std::setfill('0') << std::setw(2) << std::hex << std::uppercase
03137 << static_cast<unsigned int>(value);
03138 return ss.str();
03139 }
03140
03141
03142
03143 std::string StringStreamToString(::std::stringstream* ss) {
03144 const ::std::string& str = ss->str();
03145 const char* const start = str.c_str();
03146 const char* const end = start + str.length();
03147
03148 std::string result;
03149 result.reserve(2 * (end - start));
03150 for (const char* ch = start; ch != end; ++ch) {
03151 if (*ch == '\0') {
03152 result += "\\0";
03153 } else {
03154 result += *ch;
03155 }
03156 }
03157
03158 return result;
03159 }
03160
03161
03162 std::string AppendUserMessage(const std::string& gtest_msg,
03163 const Message& user_msg) {
03164
03165 const std::string user_msg_string = user_msg.GetString();
03166 if (user_msg_string.empty()) {
03167 return gtest_msg;
03168 }
03169
03170 return gtest_msg + "\n" + user_msg_string;
03171 }
03172
03173 }
03174
03175
03176
03177
03178 TestResult::TestResult()
03179 : death_test_count_(0),
03180 elapsed_time_(0) {
03181 }
03182
03183
03184 TestResult::~TestResult() {
03185 }
03186
03187
03188
03189
03190 const TestPartResult& TestResult::GetTestPartResult(int i) const {
03191 if (i < 0 || i >= total_part_count())
03192 internal::posix::Abort();
03193 return test_part_results_.at(i);
03194 }
03195
03196
03197
03198
03199 const TestProperty& TestResult::GetTestProperty(int i) const {
03200 if (i < 0 || i >= test_property_count())
03201 internal::posix::Abort();
03202 return test_properties_.at(i);
03203 }
03204
03205
03206 void TestResult::ClearTestPartResults() {
03207 test_part_results_.clear();
03208 }
03209
03210
03211 void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
03212 test_part_results_.push_back(test_part_result);
03213 }
03214
03215
03216
03217
03218 void TestResult::RecordProperty(const std::string& xml_element,
03219 const TestProperty& test_property) {
03220 if (!ValidateTestProperty(xml_element, test_property)) {
03221 return;
03222 }
03223 internal::MutexLock lock(&test_properites_mutex_);
03224 const std::vector<TestProperty>::iterator property_with_matching_key =
03225 std::find_if(test_properties_.begin(), test_properties_.end(),
03226 internal::TestPropertyKeyIs(test_property.key()));
03227 if (property_with_matching_key == test_properties_.end()) {
03228 test_properties_.push_back(test_property);
03229 return;
03230 }
03231 property_with_matching_key->SetValue(test_property.value());
03232 }
03233
03234
03235
03236 static const char* const kReservedTestSuitesAttributes[] = {
03237 "disabled",
03238 "errors",
03239 "failures",
03240 "name",
03241 "random_seed",
03242 "tests",
03243 "time",
03244 "timestamp"
03245 };
03246
03247
03248
03249 static const char* const kReservedTestSuiteAttributes[] = {
03250 "disabled",
03251 "errors",
03252 "failures",
03253 "name",
03254 "tests",
03255 "time"
03256 };
03257
03258
03259 static const char* const kReservedTestCaseAttributes[] = {
03260 "classname",
03261 "name",
03262 "status",
03263 "time",
03264 "type_param",
03265 "value_param"
03266 };
03267
03268 template <int kSize>
03269 std::vector<std::string> ArrayAsVector(const char* const (&array)[kSize]) {
03270 return std::vector<std::string>(array, array + kSize);
03271 }
03272
03273 static std::vector<std::string> GetReservedAttributesForElement(
03274 const std::string& xml_element) {
03275 if (xml_element == "testsuites") {
03276 return ArrayAsVector(kReservedTestSuitesAttributes);
03277 } else if (xml_element == "testsuite") {
03278 return ArrayAsVector(kReservedTestSuiteAttributes);
03279 } else if (xml_element == "testcase") {
03280 return ArrayAsVector(kReservedTestCaseAttributes);
03281 } else {
03282 GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element;
03283 }
03284
03285 return std::vector<std::string>();
03286 }
03287
03288 static std::string FormatWordList(const std::vector<std::string>& words) {
03289 Message word_list;
03290 for (size_t i = 0; i < words.size(); ++i) {
03291 if (i > 0 && words.size() > 2) {
03292 word_list << ", ";
03293 }
03294 if (i == words.size() - 1) {
03295 word_list << "and ";
03296 }
03297 word_list << "'" << words[i] << "'";
03298 }
03299 return word_list.GetString();
03300 }
03301
03302 bool ValidateTestPropertyName(const std::string& property_name,
03303 const std::vector<std::string>& reserved_names) {
03304 if (std::find(reserved_names.begin(), reserved_names.end(), property_name) !=
03305 reserved_names.end()) {
03306 ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name
03307 << " (" << FormatWordList(reserved_names)
03308 << " are reserved by " << GTEST_NAME_ << ")";
03309 return false;
03310 }
03311 return true;
03312 }
03313
03314
03315
03316 bool TestResult::ValidateTestProperty(const std::string& xml_element,
03317 const TestProperty& test_property) {
03318 return ValidateTestPropertyName(test_property.key(),
03319 GetReservedAttributesForElement(xml_element));
03320 }
03321
03322
03323 void TestResult::Clear() {
03324 test_part_results_.clear();
03325 test_properties_.clear();
03326 death_test_count_ = 0;
03327 elapsed_time_ = 0;
03328 }
03329
03330
03331 bool TestResult::Failed() const {
03332 for (int i = 0; i < total_part_count(); ++i) {
03333 if (GetTestPartResult(i).failed())
03334 return true;
03335 }
03336 return false;
03337 }
03338
03339
03340 static bool TestPartFatallyFailed(const TestPartResult& result) {
03341 return result.fatally_failed();
03342 }
03343
03344
03345 bool TestResult::HasFatalFailure() const {
03346 return CountIf(test_part_results_, TestPartFatallyFailed) > 0;
03347 }
03348
03349
03350 static bool TestPartNonfatallyFailed(const TestPartResult& result) {
03351 return result.nonfatally_failed();
03352 }
03353
03354
03355 bool TestResult::HasNonfatalFailure() const {
03356 return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0;
03357 }
03358
03359
03360
03361 int TestResult::total_part_count() const {
03362 return static_cast<int>(test_part_results_.size());
03363 }
03364
03365
03366 int TestResult::test_property_count() const {
03367 return static_cast<int>(test_properties_.size());
03368 }
03369
03370
03371
03372
03373
03374
03375 Test::Test()
03376 : gtest_flag_saver_(new internal::GTestFlagSaver) {
03377 }
03378
03379
03380 Test::~Test() {
03381 delete gtest_flag_saver_;
03382 }
03383
03384
03385
03386
03387 void Test::SetUp() {
03388 }
03389
03390
03391
03392
03393 void Test::TearDown() {
03394 }
03395
03396
03397 void Test::RecordProperty(const std::string& key, const std::string& value) {
03398 UnitTest::GetInstance()->RecordProperty(key, value);
03399 }
03400
03401
03402 void Test::RecordProperty(const std::string& key, int value) {
03403 Message value_message;
03404 value_message << value;
03405 RecordProperty(key, value_message.GetString().c_str());
03406 }
03407
03408 namespace internal {
03409
03410 void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
03411 const std::string& message) {
03412
03413
03414 UnitTest::GetInstance()->AddTestPartResult(
03415 result_type,
03416 NULL,
03417 -1,
03418 message,
03419 "");
03420 }
03421
03422 }
03423
03424
03425
03426
03427
03428
03429 bool Test::HasSameFixtureClass() {
03430 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
03431 const TestCase* const test_case = impl->current_test_case();
03432
03433
03434 const TestInfo* const first_test_info = test_case->test_info_list()[0];
03435 const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_;
03436 const char* const first_test_name = first_test_info->name();
03437
03438
03439 const TestInfo* const this_test_info = impl->current_test_info();
03440 const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_;
03441 const char* const this_test_name = this_test_info->name();
03442
03443 if (this_fixture_id != first_fixture_id) {
03444
03445 const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();
03446
03447 const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();
03448
03449 if (first_is_TEST || this_is_TEST) {
03450
03451
03452
03453
03454
03455
03456 const char* const TEST_name =
03457 first_is_TEST ? first_test_name : this_test_name;
03458 const char* const TEST_F_name =
03459 first_is_TEST ? this_test_name : first_test_name;
03460
03461 ADD_FAILURE()
03462 << "All tests in the same test case must use the same test fixture\n"
03463 << "class, so mixing TEST_F and TEST in the same test case is\n"
03464 << "illegal. In test case " << this_test_info->test_case_name()
03465 << ",\n"
03466 << "test " << TEST_F_name << " is defined using TEST_F but\n"
03467 << "test " << TEST_name << " is defined using TEST. You probably\n"
03468 << "want to change the TEST to TEST_F or move it to another test\n"
03469 << "case.";
03470 } else {
03471
03472
03473 ADD_FAILURE()
03474 << "All tests in the same test case must use the same test fixture\n"
03475 << "class. However, in test case "
03476 << this_test_info->test_case_name() << ",\n"
03477 << "you defined test " << first_test_name
03478 << " and test " << this_test_name << "\n"
03479 << "using two different test fixture classes. This can happen if\n"
03480 << "the two classes are from different namespaces or translation\n"
03481 << "units and have the same name. You should probably rename one\n"
03482 << "of the classes to put the tests into different test cases.";
03483 }
03484 return false;
03485 }
03486
03487 return true;
03488 }
03489
03490 #if GTEST_HAS_SEH
03491
03492
03493
03494
03495
03496 static std::string* FormatSehExceptionMessage(DWORD exception_code,
03497 const char* location) {
03498 Message message;
03499 message << "SEH exception with code 0x" << std::setbase(16) <<
03500 exception_code << std::setbase(10) << " thrown in " << location << ".";
03501
03502 return new std::string(message.GetString());
03503 }
03504
03505 #endif // GTEST_HAS_SEH
03506
03507 namespace internal {
03508
03509 #if GTEST_HAS_EXCEPTIONS
03510
03511
03512 static std::string FormatCxxExceptionMessage(const char* description,
03513 const char* location) {
03514 Message message;
03515 if (description != NULL) {
03516 message << "C++ exception with description \"" << description << "\"";
03517 } else {
03518 message << "Unknown C++ exception";
03519 }
03520 message << " thrown in " << location << ".";
03521
03522 return message.GetString();
03523 }
03524
03525 static std::string PrintTestPartResultToString(
03526 const TestPartResult& test_part_result);
03527
03528 GoogleTestFailureException::GoogleTestFailureException(
03529 const TestPartResult& failure)
03530 : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
03531
03532 #endif // GTEST_HAS_EXCEPTIONS
03533
03534
03535
03536
03537
03538
03539
03540
03541
03542 template <class T, typename Result>
03543 Result HandleSehExceptionsInMethodIfSupported(
03544 T* object, Result (T::*method)(), const char* location) {
03545 #if GTEST_HAS_SEH
03546 __try {
03547 return (object->*method)();
03548 } __except (internal::UnitTestOptions::GTestShouldProcessSEH(
03549 GetExceptionCode())) {
03550
03551
03552
03553 std::string* exception_message = FormatSehExceptionMessage(
03554 GetExceptionCode(), location);
03555 internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
03556 *exception_message);
03557 delete exception_message;
03558 return static_cast<Result>(0);
03559 }
03560 #else
03561 (void)location;
03562 return (object->*method)();
03563 #endif // GTEST_HAS_SEH
03564 }
03565
03566
03567
03568
03569 template <class T, typename Result>
03570 Result HandleExceptionsInMethodIfSupported(
03571 T* object, Result (T::*method)(), const char* location) {
03572
03573
03574
03575
03576
03577
03578
03579
03580
03581
03582
03583
03584
03585
03586
03587
03588
03589
03590
03591
03592
03593
03594
03595 if (internal::GetUnitTestImpl()->catch_exceptions()) {
03596 #if GTEST_HAS_EXCEPTIONS
03597 try {
03598 return HandleSehExceptionsInMethodIfSupported(object, method, location);
03599 } catch (const internal::GoogleTestFailureException&) {
03600
03601
03602
03603 throw;
03604 } catch (const std::exception& e) {
03605 internal::ReportFailureInUnknownLocation(
03606 TestPartResult::kFatalFailure,
03607 FormatCxxExceptionMessage(e.what(), location));
03608 } catch (...) {
03609 internal::ReportFailureInUnknownLocation(
03610 TestPartResult::kFatalFailure,
03611 FormatCxxExceptionMessage(NULL, location));
03612 }
03613 return static_cast<Result>(0);
03614 #else
03615 return HandleSehExceptionsInMethodIfSupported(object, method, location);
03616 #endif // GTEST_HAS_EXCEPTIONS
03617 } else {
03618 return (object->*method)();
03619 }
03620 }
03621
03622 }
03623
03624
03625 void Test::Run() {
03626 if (!HasSameFixtureClass()) return;
03627
03628 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
03629 impl->os_stack_trace_getter()->UponLeavingGTest();
03630 internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()");
03631
03632 if (!HasFatalFailure()) {
03633 impl->os_stack_trace_getter()->UponLeavingGTest();
03634 internal::HandleExceptionsInMethodIfSupported(
03635 this, &Test::TestBody, "the test body");
03636 }
03637
03638
03639
03640
03641 impl->os_stack_trace_getter()->UponLeavingGTest();
03642 internal::HandleExceptionsInMethodIfSupported(
03643 this, &Test::TearDown, "TearDown()");
03644 }
03645
03646
03647 bool Test::HasFatalFailure() {
03648 return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
03649 }
03650
03651
03652 bool Test::HasNonfatalFailure() {
03653 return internal::GetUnitTestImpl()->current_test_result()->
03654 HasNonfatalFailure();
03655 }
03656
03657
03658
03659
03660
03661 TestInfo::TestInfo(const std::string& a_test_case_name,
03662 const std::string& a_name,
03663 const char* a_type_param,
03664 const char* a_value_param,
03665 internal::TypeId fixture_class_id,
03666 internal::TestFactoryBase* factory)
03667 : test_case_name_(a_test_case_name),
03668 name_(a_name),
03669 type_param_(a_type_param ? new std::string(a_type_param) : NULL),
03670 value_param_(a_value_param ? new std::string(a_value_param) : NULL),
03671 fixture_class_id_(fixture_class_id),
03672 should_run_(false),
03673 is_disabled_(false),
03674 matches_filter_(false),
03675 factory_(factory),
03676 result_() {}
03677
03678
03679 TestInfo::~TestInfo() { delete factory_; }
03680
03681 namespace internal {
03682
03683
03684
03685
03686
03687
03688
03689
03690
03691
03692
03693
03694
03695
03696
03697
03698
03699
03700 TestInfo* MakeAndRegisterTestInfo(
03701 const char* test_case_name,
03702 const char* name,
03703 const char* type_param,
03704 const char* value_param,
03705 TypeId fixture_class_id,
03706 SetUpTestCaseFunc set_up_tc,
03707 TearDownTestCaseFunc tear_down_tc,
03708 TestFactoryBase* factory) {
03709 TestInfo* const test_info =
03710 new TestInfo(test_case_name, name, type_param, value_param,
03711 fixture_class_id, factory);
03712 GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
03713 return test_info;
03714 }
03715
03716 #if GTEST_HAS_PARAM_TEST
03717 void ReportInvalidTestCaseType(const char* test_case_name,
03718 const char* file, int line) {
03719 Message errors;
03720 errors
03721 << "Attempted redefinition of test case " << test_case_name << ".\n"
03722 << "All tests in the same test case must use the same test fixture\n"
03723 << "class. However, in test case " << test_case_name << ", you tried\n"
03724 << "to define a test using a fixture class different from the one\n"
03725 << "used earlier. This can happen if the two fixture classes are\n"
03726 << "from different namespaces and have the same name. You should\n"
03727 << "probably rename one of the classes to put the tests into different\n"
03728 << "test cases.";
03729
03730 fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
03731 errors.GetString().c_str());
03732 }
03733 #endif // GTEST_HAS_PARAM_TEST
03734
03735 }
03736
03737 namespace {
03738
03739
03740
03741
03742
03743
03744
03745
03746
03747 class TestNameIs {
03748 public:
03749
03750
03751
03752 explicit TestNameIs(const char* name)
03753 : name_(name) {}
03754
03755
03756 bool operator()(const TestInfo * test_info) const {
03757 return test_info && test_info->name() == name_;
03758 }
03759
03760 private:
03761 std::string name_;
03762 };
03763
03764 }
03765
03766 namespace internal {
03767
03768
03769
03770
03771 void UnitTestImpl::RegisterParameterizedTests() {
03772 #if GTEST_HAS_PARAM_TEST
03773 if (!parameterized_tests_registered_) {
03774 parameterized_test_registry_.RegisterTests();
03775 parameterized_tests_registered_ = true;
03776 }
03777 #endif
03778 }
03779
03780 }
03781
03782
03783
03784 void TestInfo::Run() {
03785 if (!should_run_) return;
03786
03787
03788 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
03789 impl->set_current_test_info(this);
03790
03791 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
03792
03793
03794 repeater->OnTestStart(*this);
03795
03796 const TimeInMillis start = internal::GetTimeInMillis();
03797
03798 impl->os_stack_trace_getter()->UponLeavingGTest();
03799
03800
03801 Test* const test = internal::HandleExceptionsInMethodIfSupported(
03802 factory_, &internal::TestFactoryBase::CreateTest,
03803 "the test fixture's constructor");
03804
03805
03806
03807 if ((test != NULL) && !Test::HasFatalFailure()) {
03808
03809
03810 test->Run();
03811 }
03812
03813
03814 impl->os_stack_trace_getter()->UponLeavingGTest();
03815 internal::HandleExceptionsInMethodIfSupported(
03816 test, &Test::DeleteSelf_, "the test fixture's destructor");
03817
03818 result_.set_elapsed_time(internal::GetTimeInMillis() - start);
03819
03820
03821 repeater->OnTestEnd(*this);
03822
03823
03824
03825 impl->set_current_test_info(NULL);
03826 }
03827
03828
03829
03830
03831 int TestCase::successful_test_count() const {
03832 return CountIf(test_info_list_, TestPassed);
03833 }
03834
03835
03836 int TestCase::failed_test_count() const {
03837 return CountIf(test_info_list_, TestFailed);
03838 }
03839
03840
03841 int TestCase::reportable_disabled_test_count() const {
03842 return CountIf(test_info_list_, TestReportableDisabled);
03843 }
03844
03845
03846 int TestCase::disabled_test_count() const {
03847 return CountIf(test_info_list_, TestDisabled);
03848 }
03849
03850
03851 int TestCase::reportable_test_count() const {
03852 return CountIf(test_info_list_, TestReportable);
03853 }
03854
03855
03856 int TestCase::test_to_run_count() const {
03857 return CountIf(test_info_list_, ShouldRunTest);
03858 }
03859
03860
03861 int TestCase::total_test_count() const {
03862 return static_cast<int>(test_info_list_.size());
03863 }
03864
03865
03866
03867
03868
03869
03870
03871
03872
03873
03874 TestCase::TestCase(const char* a_name, const char* a_type_param,
03875 Test::SetUpTestCaseFunc set_up_tc,
03876 Test::TearDownTestCaseFunc tear_down_tc)
03877 : name_(a_name),
03878 type_param_(a_type_param ? new std::string(a_type_param) : NULL),
03879 set_up_tc_(set_up_tc),
03880 tear_down_tc_(tear_down_tc),
03881 should_run_(false),
03882 elapsed_time_(0) {
03883 }
03884
03885
03886 TestCase::~TestCase() {
03887
03888 ForEach(test_info_list_, internal::Delete<TestInfo>);
03889 }
03890
03891
03892
03893 const TestInfo* TestCase::GetTestInfo(int i) const {
03894 const int index = GetElementOr(test_indices_, i, -1);
03895 return index < 0 ? NULL : test_info_list_[index];
03896 }
03897
03898
03899
03900 TestInfo* TestCase::GetMutableTestInfo(int i) {
03901 const int index = GetElementOr(test_indices_, i, -1);
03902 return index < 0 ? NULL : test_info_list_[index];
03903 }
03904
03905
03906
03907 void TestCase::AddTestInfo(TestInfo * test_info) {
03908 test_info_list_.push_back(test_info);
03909 test_indices_.push_back(static_cast<int>(test_indices_.size()));
03910 }
03911
03912
03913 void TestCase::Run() {
03914 if (!should_run_) return;
03915
03916 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
03917 impl->set_current_test_case(this);
03918
03919 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
03920
03921 repeater->OnTestCaseStart(*this);
03922 impl->os_stack_trace_getter()->UponLeavingGTest();
03923 internal::HandleExceptionsInMethodIfSupported(
03924 this, &TestCase::RunSetUpTestCase, "SetUpTestCase()");
03925
03926 const internal::TimeInMillis start = internal::GetTimeInMillis();
03927 for (int i = 0; i < total_test_count(); i++) {
03928 GetMutableTestInfo(i)->Run();
03929 }
03930 elapsed_time_ = internal::GetTimeInMillis() - start;
03931
03932 impl->os_stack_trace_getter()->UponLeavingGTest();
03933 internal::HandleExceptionsInMethodIfSupported(
03934 this, &TestCase::RunTearDownTestCase, "TearDownTestCase()");
03935
03936 repeater->OnTestCaseEnd(*this);
03937 impl->set_current_test_case(NULL);
03938 }
03939
03940
03941 void TestCase::ClearResult() {
03942 ad_hoc_test_result_.Clear();
03943 ForEach(test_info_list_, TestInfo::ClearTestResult);
03944 }
03945
03946
03947 void TestCase::ShuffleTests(internal::Random* random) {
03948 Shuffle(random, &test_indices_);
03949 }
03950
03951
03952 void TestCase::UnshuffleTests() {
03953 for (size_t i = 0; i < test_indices_.size(); i++) {
03954 test_indices_[i] = static_cast<int>(i);
03955 }
03956 }
03957
03958
03959
03960
03961
03962
03963 static std::string FormatCountableNoun(int count,
03964 const char * singular_form,
03965 const char * plural_form) {
03966 return internal::StreamableToString(count) + " " +
03967 (count == 1 ? singular_form : plural_form);
03968 }
03969
03970
03971 static std::string FormatTestCount(int test_count) {
03972 return FormatCountableNoun(test_count, "test", "tests");
03973 }
03974
03975
03976 static std::string FormatTestCaseCount(int test_case_count) {
03977 return FormatCountableNoun(test_case_count, "test case", "test cases");
03978 }
03979
03980
03981
03982
03983
03984 static const char * TestPartResultTypeToString(TestPartResult::Type type) {
03985 switch (type) {
03986 case TestPartResult::kSuccess:
03987 return "Success";
03988
03989 case TestPartResult::kNonFatalFailure:
03990 case TestPartResult::kFatalFailure:
03991 #ifdef _MSC_VER
03992 return "error: ";
03993 #else
03994 return "Failure\n";
03995 #endif
03996 default:
03997 return "Unknown result type";
03998 }
03999 }
04000
04001 namespace internal {
04002
04003
04004 static std::string PrintTestPartResultToString(
04005 const TestPartResult& test_part_result) {
04006 return (Message()
04007 << internal::FormatFileLocation(test_part_result.file_name(),
04008 test_part_result.line_number())
04009 << " " << TestPartResultTypeToString(test_part_result.type())
04010 << test_part_result.message()).GetString();
04011 }
04012
04013
04014 static void PrintTestPartResult(const TestPartResult& test_part_result) {
04015 const std::string& result =
04016 PrintTestPartResultToString(test_part_result);
04017 printf("%s\n", result.c_str());
04018 fflush(stdout);
04019
04020
04021
04022
04023 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
04024
04025
04026
04027 ::OutputDebugStringA(result.c_str());
04028 ::OutputDebugStringA("\n");
04029 #endif
04030 }
04031
04032
04033
04034 enum GTestColor {
04035 COLOR_DEFAULT,
04036 COLOR_RED,
04037 COLOR_GREEN,
04038 COLOR_YELLOW
04039 };
04040
04041 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
04042
04043
04044 WORD GetColorAttribute(GTestColor color) {
04045 switch (color) {
04046 case COLOR_RED: return FOREGROUND_RED;
04047 case COLOR_GREEN: return FOREGROUND_GREEN;
04048 case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
04049 default: return 0;
04050 }
04051 }
04052
04053 #else
04054
04055
04056
04057 const char* GetAnsiColorCode(GTestColor color) {
04058 switch (color) {
04059 case COLOR_RED: return "1";
04060 case COLOR_GREEN: return "2";
04061 case COLOR_YELLOW: return "3";
04062 default: return NULL;
04063 };
04064 }
04065
04066 #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
04067
04068
04069 bool ShouldUseColor(bool stdout_is_tty) {
04070 const char* const gtest_color = GTEST_FLAG(color).c_str();
04071
04072 if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
04073 #if GTEST_OS_WINDOWS
04074
04075
04076 return stdout_is_tty;
04077 #else
04078
04079 const char* const term = posix::GetEnv("TERM");
04080 const bool term_supports_color =
04081 String::CStringEquals(term, "xterm") ||
04082 String::CStringEquals(term, "xterm-color") ||
04083 String::CStringEquals(term, "xterm-256color") ||
04084 String::CStringEquals(term, "screen") ||
04085 String::CStringEquals(term, "screen-256color") ||
04086 String::CStringEquals(term, "linux") ||
04087 String::CStringEquals(term, "cygwin");
04088 return stdout_is_tty && term_supports_color;
04089 #endif // GTEST_OS_WINDOWS
04090 }
04091
04092 return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
04093 String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
04094 String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
04095 String::CStringEquals(gtest_color, "1");
04096
04097
04098
04099 }
04100
04101
04102
04103
04104
04105 void ColoredPrintf(GTestColor color, const char* fmt, ...) {
04106 va_list args;
04107 va_start(args, fmt);
04108
04109 #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS || GTEST_OS_IOS
04110 const bool use_color = false;
04111 #else
04112 static const bool in_color_mode =
04113 ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
04114 const bool use_color = in_color_mode && (color != COLOR_DEFAULT);
04115 #endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
04116
04117
04118 if (!use_color) {
04119 vprintf(fmt, args);
04120 va_end(args);
04121 return;
04122 }
04123
04124 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
04125 const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
04126
04127
04128 CONSOLE_SCREEN_BUFFER_INFO buffer_info;
04129 GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
04130 const WORD old_color_attrs = buffer_info.wAttributes;
04131
04132
04133
04134
04135 fflush(stdout);
04136 SetConsoleTextAttribute(stdout_handle,
04137 GetColorAttribute(color) | FOREGROUND_INTENSITY);
04138 vprintf(fmt, args);
04139
04140 fflush(stdout);
04141
04142 SetConsoleTextAttribute(stdout_handle, old_color_attrs);
04143 #else
04144 printf("\033[0;3%sm", GetAnsiColorCode(color));
04145 vprintf(fmt, args);
04146 printf("\033[m");
04147 #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
04148 va_end(args);
04149 }
04150
04151
04152
04153 static const char kTypeParamLabel[] = "TypeParam";
04154 static const char kValueParamLabel[] = "GetParam()";
04155
04156 void PrintFullTestCommentIfPresent(const TestInfo& test_info) {
04157 const char* const type_param = test_info.type_param();
04158 const char* const value_param = test_info.value_param();
04159
04160 if (type_param != NULL || value_param != NULL) {
04161 printf(", where ");
04162 if (type_param != NULL) {
04163 printf("%s = %s", kTypeParamLabel, type_param);
04164 if (value_param != NULL)
04165 printf(" and ");
04166 }
04167 if (value_param != NULL) {
04168 printf("%s = %s", kValueParamLabel, value_param);
04169 }
04170 }
04171 }
04172
04173
04174
04175
04176 class PrettyUnitTestResultPrinter : public TestEventListener {
04177 public:
04178 PrettyUnitTestResultPrinter() {}
04179 static void PrintTestName(const char * test_case, const char * test) {
04180 printf("%s.%s", test_case, test);
04181 }
04182
04183
04184 virtual void OnTestProgramStart(const UnitTest& ) {}
04185 virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
04186 virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
04187 virtual void OnEnvironmentsSetUpEnd(const UnitTest& ) {}
04188 virtual void OnTestCaseStart(const TestCase& test_case);
04189 virtual void OnTestStart(const TestInfo& test_info);
04190 virtual void OnTestPartResult(const TestPartResult& result);
04191 virtual void OnTestEnd(const TestInfo& test_info);
04192 virtual void OnTestCaseEnd(const TestCase& test_case);
04193 virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
04194 virtual void OnEnvironmentsTearDownEnd(const UnitTest& ) {}
04195 virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
04196 virtual void OnTestProgramEnd(const UnitTest& ) {}
04197
04198 private:
04199 static void PrintFailedTests(const UnitTest& unit_test);
04200 };
04201
04202
04203 void PrettyUnitTestResultPrinter::OnTestIterationStart(
04204 const UnitTest& unit_test, int iteration) {
04205 if (GTEST_FLAG(repeat) != 1)
04206 printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
04207
04208 const char* const filter = GTEST_FLAG(filter).c_str();
04209
04210
04211
04212 if (!String::CStringEquals(filter, kUniversalFilter)) {
04213 ColoredPrintf(COLOR_YELLOW,
04214 "Note: %s filter = %s\n", GTEST_NAME_, filter);
04215 }
04216
04217 if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
04218 const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
04219 ColoredPrintf(COLOR_YELLOW,
04220 "Note: This is test shard %d of %s.\n",
04221 static_cast<int>(shard_index) + 1,
04222 internal::posix::GetEnv(kTestTotalShards));
04223 }
04224
04225 if (GTEST_FLAG(shuffle)) {
04226 ColoredPrintf(COLOR_YELLOW,
04227 "Note: Randomizing tests' orders with a seed of %d .\n",
04228 unit_test.random_seed());
04229 }
04230
04231 ColoredPrintf(COLOR_GREEN, "[==========] ");
04232 printf("Running %s from %s.\n",
04233 FormatTestCount(unit_test.test_to_run_count()).c_str(),
04234 FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
04235 fflush(stdout);
04236 }
04237
04238 void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
04239 const UnitTest& ) {
04240 ColoredPrintf(COLOR_GREEN, "[----------] ");
04241 printf("Global test environment set-up.\n");
04242 fflush(stdout);
04243 }
04244
04245 void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {
04246 const std::string counts =
04247 FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
04248 ColoredPrintf(COLOR_GREEN, "[----------] ");
04249 printf("%s from %s", counts.c_str(), test_case.name());
04250 if (test_case.type_param() == NULL) {
04251 printf("\n");
04252 } else {
04253 printf(", where %s = %s\n", kTypeParamLabel, test_case.type_param());
04254 }
04255 fflush(stdout);
04256 }
04257
04258 void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
04259 ColoredPrintf(COLOR_GREEN, "[ RUN ] ");
04260 PrintTestName(test_info.test_case_name(), test_info.name());
04261 printf("\n");
04262 fflush(stdout);
04263 }
04264
04265
04266 void PrettyUnitTestResultPrinter::OnTestPartResult(
04267 const TestPartResult& result) {
04268
04269 if (result.type() == TestPartResult::kSuccess)
04270 return;
04271
04272
04273 PrintTestPartResult(result);
04274 fflush(stdout);
04275 }
04276
04277 void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
04278 if (test_info.result()->Passed()) {
04279 ColoredPrintf(COLOR_GREEN, "[ OK ] ");
04280 } else {
04281 ColoredPrintf(COLOR_RED, "[ FAILED ] ");
04282 }
04283 PrintTestName(test_info.test_case_name(), test_info.name());
04284 if (test_info.result()->Failed())
04285 PrintFullTestCommentIfPresent(test_info);
04286
04287 if (GTEST_FLAG(print_time)) {
04288 printf(" (%s ms)\n", internal::StreamableToString(
04289 test_info.result()->elapsed_time()).c_str());
04290 } else {
04291 printf("\n");
04292 }
04293 fflush(stdout);
04294 }
04295
04296 void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {
04297 if (!GTEST_FLAG(print_time)) return;
04298
04299 const std::string counts =
04300 FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
04301 ColoredPrintf(COLOR_GREEN, "[----------] ");
04302 printf("%s from %s (%s ms total)\n\n",
04303 counts.c_str(), test_case.name(),
04304 internal::StreamableToString(test_case.elapsed_time()).c_str());
04305 fflush(stdout);
04306 }
04307
04308 void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
04309 const UnitTest& ) {
04310 ColoredPrintf(COLOR_GREEN, "[----------] ");
04311 printf("Global test environment tear-down\n");
04312 fflush(stdout);
04313 }
04314
04315
04316 void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
04317 const int failed_test_count = unit_test.failed_test_count();
04318 if (failed_test_count == 0) {
04319 return;
04320 }
04321
04322 for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
04323 const TestCase& test_case = *unit_test.GetTestCase(i);
04324 if (!test_case.should_run() || (test_case.failed_test_count() == 0)) {
04325 continue;
04326 }
04327 for (int j = 0; j < test_case.total_test_count(); ++j) {
04328 const TestInfo& test_info = *test_case.GetTestInfo(j);
04329 if (!test_info.should_run() || test_info.result()->Passed()) {
04330 continue;
04331 }
04332 ColoredPrintf(COLOR_RED, "[ FAILED ] ");
04333 printf("%s.%s", test_case.name(), test_info.name());
04334 PrintFullTestCommentIfPresent(test_info);
04335 printf("\n");
04336 }
04337 }
04338 }
04339
04340 void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
04341 int ) {
04342 ColoredPrintf(COLOR_GREEN, "[==========] ");
04343 printf("%s from %s ran.",
04344 FormatTestCount(unit_test.test_to_run_count()).c_str(),
04345 FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
04346 if (GTEST_FLAG(print_time)) {
04347 printf(" (%s ms total)",
04348 internal::StreamableToString(unit_test.elapsed_time()).c_str());
04349 }
04350 printf("\n");
04351 ColoredPrintf(COLOR_GREEN, "[ PASSED ] ");
04352 printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
04353
04354 int num_failures = unit_test.failed_test_count();
04355 if (!unit_test.Passed()) {
04356 const int failed_test_count = unit_test.failed_test_count();
04357 ColoredPrintf(COLOR_RED, "[ FAILED ] ");
04358 printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
04359 PrintFailedTests(unit_test);
04360 printf("\n%2d FAILED %s\n", num_failures,
04361 num_failures == 1 ? "TEST" : "TESTS");
04362 }
04363
04364 int num_disabled = unit_test.reportable_disabled_test_count();
04365 if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
04366 if (!num_failures) {
04367 printf("\n");
04368 }
04369 ColoredPrintf(COLOR_YELLOW,
04370 " YOU HAVE %d DISABLED %s\n\n",
04371 num_disabled,
04372 num_disabled == 1 ? "TEST" : "TESTS");
04373 }
04374
04375 fflush(stdout);
04376 }
04377
04378
04379
04380
04381
04382
04383 class TestEventRepeater : public TestEventListener {
04384 public:
04385 TestEventRepeater() : forwarding_enabled_(true) {}
04386 virtual ~TestEventRepeater();
04387 void Append(TestEventListener *listener);
04388 TestEventListener* Release(TestEventListener* listener);
04389
04390
04391
04392 bool forwarding_enabled() const { return forwarding_enabled_; }
04393 void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }
04394
04395 virtual void OnTestProgramStart(const UnitTest& unit_test);
04396 virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
04397 virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
04398 virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test);
04399 virtual void OnTestCaseStart(const TestCase& test_case);
04400 virtual void OnTestStart(const TestInfo& test_info);
04401 virtual void OnTestPartResult(const TestPartResult& result);
04402 virtual void OnTestEnd(const TestInfo& test_info);
04403 virtual void OnTestCaseEnd(const TestCase& test_case);
04404 virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
04405 virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test);
04406 virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
04407 virtual void OnTestProgramEnd(const UnitTest& unit_test);
04408
04409 private:
04410
04411
04412 bool forwarding_enabled_;
04413
04414 std::vector<TestEventListener*> listeners_;
04415
04416 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater);
04417 };
04418
04419 TestEventRepeater::~TestEventRepeater() {
04420 ForEach(listeners_, Delete<TestEventListener>);
04421 }
04422
04423 void TestEventRepeater::Append(TestEventListener *listener) {
04424 listeners_.push_back(listener);
04425 }
04426
04427
04428 TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {
04429 for (size_t i = 0; i < listeners_.size(); ++i) {
04430 if (listeners_[i] == listener) {
04431 listeners_.erase(listeners_.begin() + i);
04432 return listener;
04433 }
04434 }
04435
04436 return NULL;
04437 }
04438
04439
04440
04441 #define GTEST_REPEATER_METHOD_(Name, Type) \
04442 void TestEventRepeater::Name(const Type& parameter) { \
04443 if (forwarding_enabled_) { \
04444 for (size_t i = 0; i < listeners_.size(); i++) { \
04445 listeners_[i]->Name(parameter); \
04446 } \
04447 } \
04448 }
04449
04450
04451 #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
04452 void TestEventRepeater::Name(const Type& parameter) { \
04453 if (forwarding_enabled_) { \
04454 for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \
04455 listeners_[i]->Name(parameter); \
04456 } \
04457 } \
04458 }
04459
04460 GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)
04461 GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)
04462 GTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase)
04463 GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
04464 GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)
04465 GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)
04466 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)
04467 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)
04468 GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)
04469 GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestCase)
04470 GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)
04471
04472 #undef GTEST_REPEATER_METHOD_
04473 #undef GTEST_REVERSE_REPEATER_METHOD_
04474
04475 void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,
04476 int iteration) {
04477 if (forwarding_enabled_) {
04478 for (size_t i = 0; i < listeners_.size(); i++) {
04479 listeners_[i]->OnTestIterationStart(unit_test, iteration);
04480 }
04481 }
04482 }
04483
04484 void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,
04485 int iteration) {
04486 if (forwarding_enabled_) {
04487 for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) {
04488 listeners_[i]->OnTestIterationEnd(unit_test, iteration);
04489 }
04490 }
04491 }
04492
04493
04494
04495
04496 class XmlUnitTestResultPrinter : public EmptyTestEventListener {
04497 public:
04498 explicit XmlUnitTestResultPrinter(const char* output_file);
04499
04500 virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
04501
04502 private:
04503
04504
04505 static bool IsNormalizableWhitespace(char c) {
04506 return c == 0x9 || c == 0xA || c == 0xD;
04507 }
04508
04509
04510 static bool IsValidXmlCharacter(char c) {
04511 return IsNormalizableWhitespace(c) || c >= 0x20;
04512 }
04513
04514
04515
04516
04517
04518 static std::string EscapeXml(const std::string& str, bool is_attribute);
04519
04520
04521 static std::string RemoveInvalidXmlCharacters(const std::string& str);
04522
04523
04524 static std::string EscapeXmlAttribute(const std::string& str) {
04525 return EscapeXml(str, true);
04526 }
04527
04528
04529 static std::string EscapeXmlText(const char* str) {
04530 return EscapeXml(str, false);
04531 }
04532
04533
04534
04535 static void OutputXmlAttribute(std::ostream* stream,
04536 const std::string& element_name,
04537 const std::string& name,
04538 const std::string& value);
04539
04540
04541 static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
04542
04543
04544 static void OutputXmlTestInfo(::std::ostream* stream,
04545 const char* test_case_name,
04546 const TestInfo& test_info);
04547
04548
04549 static void PrintXmlTestCase(::std::ostream* stream,
04550 const TestCase& test_case);
04551
04552
04553 static void PrintXmlUnitTest(::std::ostream* stream,
04554 const UnitTest& unit_test);
04555
04556
04557
04558
04559
04560 static std::string TestPropertiesAsXmlAttributes(const TestResult& result);
04561
04562
04563 const std::string output_file_;
04564
04565 GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);
04566 };
04567
04568
04569 XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
04570 : output_file_(output_file) {
04571 if (output_file_.c_str() == NULL || output_file_.empty()) {
04572 fprintf(stderr, "XML output file may not be null\n");
04573 fflush(stderr);
04574 exit(EXIT_FAILURE);
04575 }
04576 }
04577
04578
04579 void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
04580 int ) {
04581 FILE* xmlout = NULL;
04582 FilePath output_file(output_file_);
04583 FilePath output_dir(output_file.RemoveFileName());
04584
04585 if (output_dir.CreateDirectoriesRecursively()) {
04586 xmlout = posix::FOpen(output_file_.c_str(), "w");
04587 }
04588 if (xmlout == NULL) {
04589
04590
04591
04592
04593
04594
04595
04596
04597
04598
04599 fprintf(stderr,
04600 "Unable to open file \"%s\"\n",
04601 output_file_.c_str());
04602 fflush(stderr);
04603 exit(EXIT_FAILURE);
04604 }
04605 std::stringstream stream;
04606 PrintXmlUnitTest(&stream, unit_test);
04607 fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
04608 fclose(xmlout);
04609 }
04610
04611
04612
04613
04614
04615
04616
04617
04618
04619
04620
04621
04622
04623 std::string XmlUnitTestResultPrinter::EscapeXml(
04624 const std::string& str, bool is_attribute) {
04625 Message m;
04626
04627 for (size_t i = 0; i < str.size(); ++i) {
04628 const char ch = str[i];
04629 switch (ch) {
04630 case '<':
04631 m << "<";
04632 break;
04633 case '>':
04634 m << ">";
04635 break;
04636 case '&':
04637 m << "&";
04638 break;
04639 case '\'':
04640 if (is_attribute)
04641 m << "'";
04642 else
04643 m << '\'';
04644 break;
04645 case '"':
04646 if (is_attribute)
04647 m << """;
04648 else
04649 m << '"';
04650 break;
04651 default:
04652 if (IsValidXmlCharacter(ch)) {
04653 if (is_attribute && IsNormalizableWhitespace(ch))
04654 m << "&#x" << String::FormatByte(static_cast<unsigned char>(ch))
04655 << ";";
04656 else
04657 m << ch;
04658 }
04659 break;
04660 }
04661 }
04662
04663 return m.GetString();
04664 }
04665
04666
04667
04668
04669 std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(
04670 const std::string& str) {
04671 std::string output;
04672 output.reserve(str.size());
04673 for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
04674 if (IsValidXmlCharacter(*it))
04675 output.push_back(*it);
04676
04677 return output;
04678 }
04679
04680
04681
04682
04683
04684
04685
04686
04687
04688
04689
04690
04691
04692
04693
04694
04695
04696
04697 std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {
04698 ::std::stringstream ss;
04699 ss << ms/1000.0;
04700 return ss.str();
04701 }
04702
04703
04704
04705 std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) {
04706
04707 time_t seconds = static_cast<time_t>(ms / 1000);
04708 #ifdef _MSC_VER
04709 # pragma warning(push) // Saves the current warning state.
04710 # pragma warning(disable:4996) // Temporarily disables warning 4996
04711
04712 const struct tm* const time_struct = localtime(&seconds);
04713 # pragma warning(pop) // Restores the warning state again.
04714 #else
04715 const struct tm* const time_struct = localtime(&seconds);
04716 #endif
04717 if (time_struct == NULL)
04718 return "";
04719
04720
04721 return StreamableToString(time_struct->tm_year + 1900) + "-" +
04722 String::FormatIntWidth2(time_struct->tm_mon + 1) + "-" +
04723 String::FormatIntWidth2(time_struct->tm_mday) + "T" +
04724 String::FormatIntWidth2(time_struct->tm_hour) + ":" +
04725 String::FormatIntWidth2(time_struct->tm_min) + ":" +
04726 String::FormatIntWidth2(time_struct->tm_sec);
04727 }
04728
04729
04730 void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
04731 const char* data) {
04732 const char* segment = data;
04733 *stream << "<![CDATA[";
04734 for (;;) {
04735 const char* const next_segment = strstr(segment, "]]>");
04736 if (next_segment != NULL) {
04737 stream->write(
04738 segment, static_cast<std::streamsize>(next_segment - segment));
04739 *stream << "]]>]]><![CDATA[";
04740 segment = next_segment + strlen("]]>");
04741 } else {
04742 *stream << segment;
04743 break;
04744 }
04745 }
04746 *stream << "]]>";
04747 }
04748
04749 void XmlUnitTestResultPrinter::OutputXmlAttribute(
04750 std::ostream* stream,
04751 const std::string& element_name,
04752 const std::string& name,
04753 const std::string& value) {
04754 const std::vector<std::string>& allowed_names =
04755 GetReservedAttributesForElement(element_name);
04756
04757 GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
04758 allowed_names.end())
04759 << "Attribute " << name << " is not allowed for element <" << element_name
04760 << ">.";
04761
04762 *stream << " " << name << "=\"" << EscapeXmlAttribute(value) << "\"";
04763 }
04764
04765
04766
04767 void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
04768 const char* test_case_name,
04769 const TestInfo& test_info) {
04770 const TestResult& result = *test_info.result();
04771 const std::string kTestcase = "testcase";
04772
04773 *stream << " <testcase";
04774 OutputXmlAttribute(stream, kTestcase, "name", test_info.name());
04775
04776 if (test_info.value_param() != NULL) {
04777 OutputXmlAttribute(stream, kTestcase, "value_param",
04778 test_info.value_param());
04779 }
04780 if (test_info.type_param() != NULL) {
04781 OutputXmlAttribute(stream, kTestcase, "type_param", test_info.type_param());
04782 }
04783
04784 OutputXmlAttribute(stream, kTestcase, "status",
04785 test_info.should_run() ? "run" : "notrun");
04786 OutputXmlAttribute(stream, kTestcase, "time",
04787 FormatTimeInMillisAsSeconds(result.elapsed_time()));
04788 OutputXmlAttribute(stream, kTestcase, "classname", test_case_name);
04789 *stream << TestPropertiesAsXmlAttributes(result);
04790
04791 int failures = 0;
04792 for (int i = 0; i < result.total_part_count(); ++i) {
04793 const TestPartResult& part = result.GetTestPartResult(i);
04794 if (part.failed()) {
04795 if (++failures == 1) {
04796 *stream << ">\n";
04797 }
04798 const string location = internal::FormatCompilerIndependentFileLocation(
04799 part.file_name(), part.line_number());
04800 const string summary = location + "\n" + part.summary();
04801 *stream << " <failure message=\""
04802 << EscapeXmlAttribute(summary.c_str())
04803 << "\" type=\"\">";
04804 const string detail = location + "\n" + part.message();
04805 OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
04806 *stream << "</failure>\n";
04807 }
04808 }
04809
04810 if (failures == 0)
04811 *stream << " />\n";
04812 else
04813 *stream << " </testcase>\n";
04814 }
04815
04816
04817 void XmlUnitTestResultPrinter::PrintXmlTestCase(std::ostream* stream,
04818 const TestCase& test_case) {
04819 const std::string kTestsuite = "testsuite";
04820 *stream << " <" << kTestsuite;
04821 OutputXmlAttribute(stream, kTestsuite, "name", test_case.name());
04822 OutputXmlAttribute(stream, kTestsuite, "tests",
04823 StreamableToString(test_case.reportable_test_count()));
04824 OutputXmlAttribute(stream, kTestsuite, "failures",
04825 StreamableToString(test_case.failed_test_count()));
04826 OutputXmlAttribute(
04827 stream, kTestsuite, "disabled",
04828 StreamableToString(test_case.reportable_disabled_test_count()));
04829 OutputXmlAttribute(stream, kTestsuite, "errors", "0");
04830 OutputXmlAttribute(stream, kTestsuite, "time",
04831 FormatTimeInMillisAsSeconds(test_case.elapsed_time()));
04832 *stream << TestPropertiesAsXmlAttributes(test_case.ad_hoc_test_result())
04833 << ">\n";
04834
04835 for (int i = 0; i < test_case.total_test_count(); ++i) {
04836 if (test_case.GetTestInfo(i)->is_reportable())
04837 OutputXmlTestInfo(stream, test_case.name(), *test_case.GetTestInfo(i));
04838 }
04839 *stream << " </" << kTestsuite << ">\n";
04840 }
04841
04842
04843 void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream,
04844 const UnitTest& unit_test) {
04845 const std::string kTestsuites = "testsuites";
04846
04847 *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
04848 *stream << "<" << kTestsuites;
04849
04850 OutputXmlAttribute(stream, kTestsuites, "tests",
04851 StreamableToString(unit_test.reportable_test_count()));
04852 OutputXmlAttribute(stream, kTestsuites, "failures",
04853 StreamableToString(unit_test.failed_test_count()));
04854 OutputXmlAttribute(
04855 stream, kTestsuites, "disabled",
04856 StreamableToString(unit_test.reportable_disabled_test_count()));
04857 OutputXmlAttribute(stream, kTestsuites, "errors", "0");
04858 OutputXmlAttribute(
04859 stream, kTestsuites, "timestamp",
04860 FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp()));
04861 OutputXmlAttribute(stream, kTestsuites, "time",
04862 FormatTimeInMillisAsSeconds(unit_test.elapsed_time()));
04863
04864 if (GTEST_FLAG(shuffle)) {
04865 OutputXmlAttribute(stream, kTestsuites, "random_seed",
04866 StreamableToString(unit_test.random_seed()));
04867 }
04868
04869 *stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result());
04870
04871 OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
04872 *stream << ">\n";
04873
04874 for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
04875 if (unit_test.GetTestCase(i)->reportable_test_count() > 0)
04876 PrintXmlTestCase(stream, *unit_test.GetTestCase(i));
04877 }
04878 *stream << "</" << kTestsuites << ">\n";
04879 }
04880
04881
04882
04883 std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
04884 const TestResult& result) {
04885 Message attributes;
04886 for (int i = 0; i < result.test_property_count(); ++i) {
04887 const TestProperty& property = result.GetTestProperty(i);
04888 attributes << " " << property.key() << "="
04889 << "\"" << EscapeXmlAttribute(property.value()) << "\"";
04890 }
04891 return attributes.GetString();
04892 }
04893
04894
04895
04896 #if GTEST_CAN_STREAM_RESULTS_
04897
04898
04899
04900
04901
04902
04903 string StreamingListener::UrlEncode(const char* str) {
04904 string result;
04905 result.reserve(strlen(str) + 1);
04906 for (char ch = *str; ch != '\0'; ch = *++str) {
04907 switch (ch) {
04908 case '%':
04909 case '=':
04910 case '&':
04911 case '\n':
04912 result.append("%" + String::FormatByte(static_cast<unsigned char>(ch)));
04913 break;
04914 default:
04915 result.push_back(ch);
04916 break;
04917 }
04918 }
04919 return result;
04920 }
04921
04922 void StreamingListener::SocketWriter::MakeConnection() {
04923 GTEST_CHECK_(sockfd_ == -1)
04924 << "MakeConnection() can't be called when there is already a connection.";
04925
04926 addrinfo hints;
04927 memset(&hints, 0, sizeof(hints));
04928 hints.ai_family = AF_UNSPEC;
04929 hints.ai_socktype = SOCK_STREAM;
04930 addrinfo* servinfo = NULL;
04931
04932
04933
04934 const int error_num = getaddrinfo(
04935 host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
04936 if (error_num != 0) {
04937 GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: "
04938 << gai_strerror(error_num);
04939 }
04940
04941
04942 for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != NULL;
04943 cur_addr = cur_addr->ai_next) {
04944 sockfd_ = socket(
04945 cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol);
04946 if (sockfd_ != -1) {
04947
04948 if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
04949 close(sockfd_);
04950 sockfd_ = -1;
04951 }
04952 }
04953 }
04954
04955 freeaddrinfo(servinfo);
04956
04957 if (sockfd_ == -1) {
04958 GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to "
04959 << host_name_ << ":" << port_num_;
04960 }
04961 }
04962
04963
04964 #endif // GTEST_CAN_STREAM_RESULTS__
04965
04966
04967
04968
04969
04970 ScopedTrace::ScopedTrace(const char* file, int line, const Message& message)
04971 GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
04972 TraceInfo trace;
04973 trace.file = file;
04974 trace.line = line;
04975 trace.message = message.GetString();
04976
04977 UnitTest::GetInstance()->PushGTestTrace(trace);
04978 }
04979
04980
04981 ScopedTrace::~ScopedTrace()
04982 GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
04983 UnitTest::GetInstance()->PopGTestTrace();
04984 }
04985
04986
04987
04988
04989
04990
04991
04992
04993
04994
04995
04996 string OsStackTraceGetter::CurrentStackTrace(int ,
04997 int )
04998 GTEST_LOCK_EXCLUDED_(mutex_) {
04999 return "";
05000 }
05001
05002 void OsStackTraceGetter::UponLeavingGTest()
05003 GTEST_LOCK_EXCLUDED_(mutex_) {
05004 }
05005
05006 const char* const
05007 OsStackTraceGetter::kElidedFramesMarker =
05008 "... " GTEST_NAME_ " internal frames ...";
05009
05010
05011
05012 class ScopedPrematureExitFile {
05013 public:
05014 explicit ScopedPrematureExitFile(const char* premature_exit_filepath)
05015 : premature_exit_filepath_(premature_exit_filepath) {
05016
05017 if (premature_exit_filepath != NULL && *premature_exit_filepath != '\0') {
05018
05019
05020
05021 FILE* pfile = posix::FOpen(premature_exit_filepath, "w");
05022 fwrite("0", 1, 1, pfile);
05023 fclose(pfile);
05024 }
05025 }
05026
05027 ~ScopedPrematureExitFile() {
05028 if (premature_exit_filepath_ != NULL && *premature_exit_filepath_ != '\0') {
05029 remove(premature_exit_filepath_);
05030 }
05031 }
05032
05033 private:
05034 const char* const premature_exit_filepath_;
05035
05036 GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedPrematureExitFile);
05037 };
05038
05039 }
05040
05041
05042
05043 TestEventListeners::TestEventListeners()
05044 : repeater_(new internal::TestEventRepeater()),
05045 default_result_printer_(NULL),
05046 default_xml_generator_(NULL) {
05047 }
05048
05049 TestEventListeners::~TestEventListeners() { delete repeater_; }
05050
05051
05052
05053
05054
05055 void TestEventListeners::Append(TestEventListener* listener) {
05056 repeater_->Append(listener);
05057 }
05058
05059
05060
05061
05062 TestEventListener* TestEventListeners::Release(TestEventListener* listener) {
05063 if (listener == default_result_printer_)
05064 default_result_printer_ = NULL;
05065 else if (listener == default_xml_generator_)
05066 default_xml_generator_ = NULL;
05067 return repeater_->Release(listener);
05068 }
05069
05070
05071
05072 TestEventListener* TestEventListeners::repeater() { return repeater_; }
05073
05074
05075
05076
05077
05078
05079 void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
05080 if (default_result_printer_ != listener) {
05081
05082
05083 delete Release(default_result_printer_);
05084 default_result_printer_ = listener;
05085 if (listener != NULL)
05086 Append(listener);
05087 }
05088 }
05089
05090
05091
05092
05093
05094
05095 void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
05096 if (default_xml_generator_ != listener) {
05097
05098
05099 delete Release(default_xml_generator_);
05100 default_xml_generator_ = listener;
05101 if (listener != NULL)
05102 Append(listener);
05103 }
05104 }
05105
05106
05107
05108 bool TestEventListeners::EventForwardingEnabled() const {
05109 return repeater_->forwarding_enabled();
05110 }
05111
05112 void TestEventListeners::SuppressEventForwarding() {
05113 repeater_->set_forwarding_enabled(false);
05114 }
05115
05116
05117
05118
05119
05120
05121
05122
05123
05124
05125 UnitTest* UnitTest::GetInstance() {
05126
05127
05128
05129
05130
05131
05132
05133
05134
05135
05136
05137 #if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
05138 static UnitTest* const instance = new UnitTest;
05139 return instance;
05140 #else
05141 static UnitTest instance;
05142 return &instance;
05143 #endif // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
05144 }
05145
05146
05147 int UnitTest::successful_test_case_count() const {
05148 return impl()->successful_test_case_count();
05149 }
05150
05151
05152 int UnitTest::failed_test_case_count() const {
05153 return impl()->failed_test_case_count();
05154 }
05155
05156
05157 int UnitTest::total_test_case_count() const {
05158 return impl()->total_test_case_count();
05159 }
05160
05161
05162
05163 int UnitTest::test_case_to_run_count() const {
05164 return impl()->test_case_to_run_count();
05165 }
05166
05167
05168 int UnitTest::successful_test_count() const {
05169 return impl()->successful_test_count();
05170 }
05171
05172
05173 int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
05174
05175
05176 int UnitTest::reportable_disabled_test_count() const {
05177 return impl()->reportable_disabled_test_count();
05178 }
05179
05180
05181 int UnitTest::disabled_test_count() const {
05182 return impl()->disabled_test_count();
05183 }
05184
05185
05186 int UnitTest::reportable_test_count() const {
05187 return impl()->reportable_test_count();
05188 }
05189
05190
05191 int UnitTest::total_test_count() const { return impl()->total_test_count(); }
05192
05193
05194 int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
05195
05196
05197
05198 internal::TimeInMillis UnitTest::start_timestamp() const {
05199 return impl()->start_timestamp();
05200 }
05201
05202
05203 internal::TimeInMillis UnitTest::elapsed_time() const {
05204 return impl()->elapsed_time();
05205 }
05206
05207
05208 bool UnitTest::Passed() const { return impl()->Passed(); }
05209
05210
05211
05212 bool UnitTest::Failed() const { return impl()->Failed(); }
05213
05214
05215
05216 const TestCase* UnitTest::GetTestCase(int i) const {
05217 return impl()->GetTestCase(i);
05218 }
05219
05220
05221
05222 const TestResult& UnitTest::ad_hoc_test_result() const {
05223 return *impl()->ad_hoc_test_result();
05224 }
05225
05226
05227
05228 TestCase* UnitTest::GetMutableTestCase(int i) {
05229 return impl()->GetMutableTestCase(i);
05230 }
05231
05232
05233
05234 TestEventListeners& UnitTest::listeners() {
05235 return *impl()->listeners();
05236 }
05237
05238
05239
05240
05241
05242
05243
05244
05245
05246
05247
05248 Environment* UnitTest::AddEnvironment(Environment* env) {
05249 if (env == NULL) {
05250 return NULL;
05251 }
05252
05253 impl_->environments().push_back(env);
05254 return env;
05255 }
05256
05257
05258
05259
05260
05261 void UnitTest::AddTestPartResult(
05262 TestPartResult::Type result_type,
05263 const char* file_name,
05264 int line_number,
05265 const std::string& message,
05266 const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_) {
05267 Message msg;
05268 msg << message;
05269
05270 internal::MutexLock lock(&mutex_);
05271 if (impl_->gtest_trace_stack().size() > 0) {
05272 msg << "\n" << GTEST_NAME_ << " trace:";
05273
05274 for (int i = static_cast<int>(impl_->gtest_trace_stack().size());
05275 i > 0; --i) {
05276 const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
05277 msg << "\n" << internal::FormatFileLocation(trace.file, trace.line)
05278 << " " << trace.message;
05279 }
05280 }
05281
05282 if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) {
05283 msg << internal::kStackTraceMarker << os_stack_trace;
05284 }
05285
05286 const TestPartResult result =
05287 TestPartResult(result_type, file_name, line_number,
05288 msg.GetString().c_str());
05289 impl_->GetTestPartResultReporterForCurrentThread()->
05290 ReportTestPartResult(result);
05291
05292 if (result_type != TestPartResult::kSuccess) {
05293
05294
05295
05296
05297
05298 if (GTEST_FLAG(break_on_failure)) {
05299 #if GTEST_OS_WINDOWS
05300
05301
05302
05303 DebugBreak();
05304 #else
05305
05306
05307
05308
05309 *static_cast<volatile int*>(NULL) = 1;
05310 #endif // GTEST_OS_WINDOWS
05311 } else if (GTEST_FLAG(throw_on_failure)) {
05312 #if GTEST_HAS_EXCEPTIONS
05313 throw internal::GoogleTestFailureException(result);
05314 #else
05315
05316
05317 exit(1);
05318 #endif
05319 }
05320 }
05321 }
05322
05323
05324
05325
05326
05327
05328 void UnitTest::RecordProperty(const std::string& key,
05329 const std::string& value) {
05330 impl_->RecordProperty(TestProperty(key, value));
05331 }
05332
05333
05334
05335
05336
05337
05338 int UnitTest::Run() {
05339 const bool in_death_test_child_process =
05340 internal::GTEST_FLAG(internal_run_death_test).length() > 0;
05341
05342
05343
05344
05345
05346
05347
05348
05349
05350
05351
05352
05353
05354
05355
05356
05357
05358
05359
05360
05361
05362
05363 const internal::ScopedPrematureExitFile premature_exit_file(
05364 in_death_test_child_process ?
05365 NULL : internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE"));
05366
05367
05368
05369 impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions));
05370
05371 #if GTEST_HAS_SEH
05372
05373
05374
05375
05376 if (impl()->catch_exceptions() || in_death_test_child_process) {
05377 # if !GTEST_OS_WINDOWS_MOBILE
05378
05379 SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
05380 SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
05381 # endif // !GTEST_OS_WINDOWS_MOBILE
05382
05383 # if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
05384
05385
05386
05387 _set_error_mode(_OUT_TO_STDERR);
05388 # endif
05389
05390 # if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
05391
05392
05393
05394
05395
05396
05397
05398
05399
05400
05401
05402 if (!GTEST_FLAG(break_on_failure))
05403 _set_abort_behavior(
05404 0x0,
05405 _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
05406 # endif
05407 }
05408 #endif // GTEST_HAS_SEH
05409
05410 return internal::HandleExceptionsInMethodIfSupported(
05411 impl(),
05412 &internal::UnitTestImpl::RunAllTests,
05413 "auxiliary test code (environments or event listeners)") ? 0 : 1;
05414 }
05415
05416
05417
05418 const char* UnitTest::original_working_dir() const {
05419 return impl_->original_working_dir_.c_str();
05420 }
05421
05422
05423
05424 const TestCase* UnitTest::current_test_case() const
05425 GTEST_LOCK_EXCLUDED_(mutex_) {
05426 internal::MutexLock lock(&mutex_);
05427 return impl_->current_test_case();
05428 }
05429
05430
05431
05432 const TestInfo* UnitTest::current_test_info() const
05433 GTEST_LOCK_EXCLUDED_(mutex_) {
05434 internal::MutexLock lock(&mutex_);
05435 return impl_->current_test_info();
05436 }
05437
05438
05439 int UnitTest::random_seed() const { return impl_->random_seed(); }
05440
05441 #if GTEST_HAS_PARAM_TEST
05442
05443
05444 internal::ParameterizedTestCaseRegistry&
05445 UnitTest::parameterized_test_registry()
05446 GTEST_LOCK_EXCLUDED_(mutex_) {
05447 return impl_->parameterized_test_registry();
05448 }
05449 #endif // GTEST_HAS_PARAM_TEST
05450
05451
05452 UnitTest::UnitTest() {
05453 impl_ = new internal::UnitTestImpl(this);
05454 }
05455
05456
05457 UnitTest::~UnitTest() {
05458 delete impl_;
05459 }
05460
05461
05462
05463 void UnitTest::PushGTestTrace(const internal::TraceInfo& trace)
05464 GTEST_LOCK_EXCLUDED_(mutex_) {
05465 internal::MutexLock lock(&mutex_);
05466 impl_->gtest_trace_stack().push_back(trace);
05467 }
05468
05469
05470 void UnitTest::PopGTestTrace()
05471 GTEST_LOCK_EXCLUDED_(mutex_) {
05472 internal::MutexLock lock(&mutex_);
05473 impl_->gtest_trace_stack().pop_back();
05474 }
05475
05476 namespace internal {
05477
05478 UnitTestImpl::UnitTestImpl(UnitTest* parent)
05479 : parent_(parent),
05480 #ifdef _MSC_VER
05481 # pragma warning(push)
05482 # pragma warning(disable:4355)
05483
05484 default_global_test_part_result_reporter_(this),
05485 default_per_thread_test_part_result_reporter_(this),
05486 # pragma warning(pop)
05487 #else
05488 default_global_test_part_result_reporter_(this),
05489 default_per_thread_test_part_result_reporter_(this),
05490 #endif
05491 global_test_part_result_repoter_(
05492 &default_global_test_part_result_reporter_),
05493 per_thread_test_part_result_reporter_(
05494 &default_per_thread_test_part_result_reporter_),
05495 #if GTEST_HAS_PARAM_TEST
05496 parameterized_test_registry_(),
05497 parameterized_tests_registered_(false),
05498 #endif
05499 last_death_test_case_(-1),
05500 current_test_case_(NULL),
05501 current_test_info_(NULL),
05502 ad_hoc_test_result_(),
05503 os_stack_trace_getter_(NULL),
05504 post_flag_parse_init_performed_(false),
05505 random_seed_(0),
05506 random_(0),
05507 start_timestamp_(0),
05508 elapsed_time_(0),
05509 #if GTEST_HAS_DEATH_TEST
05510 death_test_factory_(new DefaultDeathTestFactory),
05511 #endif
05512
05513 catch_exceptions_(false) {
05514 listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);
05515 }
05516
05517 UnitTestImpl::~UnitTestImpl() {
05518
05519 ForEach(test_cases_, internal::Delete<TestCase>);
05520
05521
05522 ForEach(environments_, internal::Delete<Environment>);
05523
05524 delete os_stack_trace_getter_;
05525 }
05526
05527
05528
05529
05530
05531
05532 void UnitTestImpl::RecordProperty(const TestProperty& test_property) {
05533 std::string xml_element;
05534 TestResult* test_result;
05535
05536 if (current_test_info_ != NULL) {
05537 xml_element = "testcase";
05538 test_result = &(current_test_info_->result_);
05539 } else if (current_test_case_ != NULL) {
05540 xml_element = "testsuite";
05541 test_result = &(current_test_case_->ad_hoc_test_result_);
05542 } else {
05543 xml_element = "testsuites";
05544 test_result = &ad_hoc_test_result_;
05545 }
05546 test_result->RecordProperty(xml_element, test_property);
05547 }
05548
05549 #if GTEST_HAS_DEATH_TEST
05550
05551
05552 void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
05553 if (internal_run_death_test_flag_.get() != NULL)
05554 listeners()->SuppressEventForwarding();
05555 }
05556 #endif // GTEST_HAS_DEATH_TEST
05557
05558
05559
05560 void UnitTestImpl::ConfigureXmlOutput() {
05561 const std::string& output_format = UnitTestOptions::GetOutputFormat();
05562 if (output_format == "xml") {
05563 listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
05564 UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
05565 } else if (output_format != "") {
05566 printf("WARNING: unrecognized output format \"%s\" ignored.\n",
05567 output_format.c_str());
05568 fflush(stdout);
05569 }
05570 }
05571
05572 #if GTEST_CAN_STREAM_RESULTS_
05573
05574
05575 void UnitTestImpl::ConfigureStreamingOutput() {
05576 const std::string& target = GTEST_FLAG(stream_result_to);
05577 if (!target.empty()) {
05578 const size_t pos = target.find(':');
05579 if (pos != std::string::npos) {
05580 listeners()->Append(new StreamingListener(target.substr(0, pos),
05581 target.substr(pos+1)));
05582 } else {
05583 printf("WARNING: unrecognized streaming target \"%s\" ignored.\n",
05584 target.c_str());
05585 fflush(stdout);
05586 }
05587 }
05588 }
05589 #endif // GTEST_CAN_STREAM_RESULTS_
05590
05591
05592
05593
05594
05595
05596 void UnitTestImpl::PostFlagParsingInit() {
05597
05598 if (!post_flag_parse_init_performed_) {
05599 post_flag_parse_init_performed_ = true;
05600
05601 #if GTEST_HAS_DEATH_TEST
05602 InitDeathTestSubprocessControlInfo();
05603 SuppressTestEventsIfInSubprocess();
05604 #endif // GTEST_HAS_DEATH_TEST
05605
05606
05607
05608
05609 RegisterParameterizedTests();
05610
05611
05612
05613 ConfigureXmlOutput();
05614
05615 #if GTEST_CAN_STREAM_RESULTS_
05616
05617 ConfigureStreamingOutput();
05618 #endif // GTEST_CAN_STREAM_RESULTS_
05619 }
05620 }
05621
05622
05623
05624
05625
05626
05627
05628
05629
05630 class TestCaseNameIs {
05631 public:
05632
05633 explicit TestCaseNameIs(const std::string& name)
05634 : name_(name) {}
05635
05636
05637 bool operator()(const TestCase* test_case) const {
05638 return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0;
05639 }
05640
05641 private:
05642 std::string name_;
05643 };
05644
05645
05646
05647
05648
05649
05650
05651
05652
05653
05654
05655
05656
05657 TestCase* UnitTestImpl::GetTestCase(const char* test_case_name,
05658 const char* type_param,
05659 Test::SetUpTestCaseFunc set_up_tc,
05660 Test::TearDownTestCaseFunc tear_down_tc) {
05661
05662 const std::vector<TestCase*>::const_iterator test_case =
05663 std::find_if(test_cases_.begin(), test_cases_.end(),
05664 TestCaseNameIs(test_case_name));
05665
05666 if (test_case != test_cases_.end())
05667 return *test_case;
05668
05669
05670 TestCase* const new_test_case =
05671 new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc);
05672
05673
05674 if (internal::UnitTestOptions::MatchesFilter(test_case_name,
05675 kDeathTestCaseFilter)) {
05676
05677
05678
05679
05680 ++last_death_test_case_;
05681 test_cases_.insert(test_cases_.begin() + last_death_test_case_,
05682 new_test_case);
05683 } else {
05684
05685 test_cases_.push_back(new_test_case);
05686 }
05687
05688 test_case_indices_.push_back(static_cast<int>(test_case_indices_.size()));
05689 return new_test_case;
05690 }
05691
05692
05693
05694 static void SetUpEnvironment(Environment* env) { env->SetUp(); }
05695 static void TearDownEnvironment(Environment* env) { env->TearDown(); }
05696
05697
05698
05699
05700
05701
05702
05703
05704
05705
05706 bool UnitTestImpl::RunAllTests() {
05707
05708 if (!GTestIsInitialized()) {
05709 printf("%s",
05710 "\nThis test program did NOT call ::testing::InitGoogleTest "
05711 "before calling RUN_ALL_TESTS(). Please fix it.\n");
05712 return false;
05713 }
05714
05715
05716 if (g_help_flag)
05717 return true;
05718
05719
05720
05721 PostFlagParsingInit();
05722
05723
05724
05725
05726 internal::WriteToShardStatusFileIfNeeded();
05727
05728
05729
05730 bool in_subprocess_for_death_test = false;
05731
05732 #if GTEST_HAS_DEATH_TEST
05733 in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL);
05734 #endif // GTEST_HAS_DEATH_TEST
05735
05736 const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
05737 in_subprocess_for_death_test);
05738
05739
05740
05741 const bool has_tests_to_run = FilterTests(should_shard
05742 ? HONOR_SHARDING_PROTOCOL
05743 : IGNORE_SHARDING_PROTOCOL) > 0;
05744
05745
05746 if (GTEST_FLAG(list_tests)) {
05747
05748 ListTestsMatchingFilter();
05749 return true;
05750 }
05751
05752 random_seed_ = GTEST_FLAG(shuffle) ?
05753 GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;
05754
05755
05756 bool failed = false;
05757
05758 TestEventListener* repeater = listeners()->repeater();
05759
05760 start_timestamp_ = GetTimeInMillis();
05761 repeater->OnTestProgramStart(*parent_);
05762
05763
05764
05765 const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);
05766
05767 const bool forever = repeat < 0;
05768 for (int i = 0; forever || i != repeat; i++) {
05769
05770
05771 ClearNonAdHocTestResult();
05772
05773 const TimeInMillis start = GetTimeInMillis();
05774
05775
05776 if (has_tests_to_run && GTEST_FLAG(shuffle)) {
05777 random()->Reseed(random_seed_);
05778
05779
05780
05781 ShuffleTests();
05782 }
05783
05784
05785 repeater->OnTestIterationStart(*parent_, i);
05786
05787
05788 if (has_tests_to_run) {
05789
05790 repeater->OnEnvironmentsSetUpStart(*parent_);
05791 ForEach(environments_, SetUpEnvironment);
05792 repeater->OnEnvironmentsSetUpEnd(*parent_);
05793
05794
05795
05796 if (!Test::HasFatalFailure()) {
05797 for (int test_index = 0; test_index < total_test_case_count();
05798 test_index++) {
05799 GetMutableTestCase(test_index)->Run();
05800 }
05801 }
05802
05803
05804 repeater->OnEnvironmentsTearDownStart(*parent_);
05805 std::for_each(environments_.rbegin(), environments_.rend(),
05806 TearDownEnvironment);
05807 repeater->OnEnvironmentsTearDownEnd(*parent_);
05808 }
05809
05810 elapsed_time_ = GetTimeInMillis() - start;
05811
05812
05813 repeater->OnTestIterationEnd(*parent_, i);
05814
05815
05816 if (!Passed()) {
05817 failed = true;
05818 }
05819
05820
05821
05822
05823
05824
05825
05826 UnshuffleTests();
05827
05828 if (GTEST_FLAG(shuffle)) {
05829
05830 random_seed_ = GetNextRandomSeed(random_seed_);
05831 }
05832 }
05833
05834 repeater->OnTestProgramEnd(*parent_);
05835
05836 return !failed;
05837 }
05838
05839
05840
05841
05842
05843 void WriteToShardStatusFileIfNeeded() {
05844 const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);
05845 if (test_shard_file != NULL) {
05846 FILE* const file = posix::FOpen(test_shard_file, "w");
05847 if (file == NULL) {
05848 ColoredPrintf(COLOR_RED,
05849 "Could not write to the test shard status file \"%s\" "
05850 "specified by the %s environment variable.\n",
05851 test_shard_file, kTestShardStatusFile);
05852 fflush(stdout);
05853 exit(EXIT_FAILURE);
05854 }
05855 fclose(file);
05856 }
05857 }
05858
05859
05860
05861
05862
05863
05864
05865 bool ShouldShard(const char* total_shards_env,
05866 const char* shard_index_env,
05867 bool in_subprocess_for_death_test) {
05868 if (in_subprocess_for_death_test) {
05869 return false;
05870 }
05871
05872 const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1);
05873 const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1);
05874
05875 if (total_shards == -1 && shard_index == -1) {
05876 return false;
05877 } else if (total_shards == -1 && shard_index != -1) {
05878 const Message msg = Message()
05879 << "Invalid environment variables: you have "
05880 << kTestShardIndex << " = " << shard_index
05881 << ", but have left " << kTestTotalShards << " unset.\n";
05882 ColoredPrintf(COLOR_RED, msg.GetString().c_str());
05883 fflush(stdout);
05884 exit(EXIT_FAILURE);
05885 } else if (total_shards != -1 && shard_index == -1) {
05886 const Message msg = Message()
05887 << "Invalid environment variables: you have "
05888 << kTestTotalShards << " = " << total_shards
05889 << ", but have left " << kTestShardIndex << " unset.\n";
05890 ColoredPrintf(COLOR_RED, msg.GetString().c_str());
05891 fflush(stdout);
05892 exit(EXIT_FAILURE);
05893 } else if (shard_index < 0 || shard_index >= total_shards) {
05894 const Message msg = Message()
05895 << "Invalid environment variables: we require 0 <= "
05896 << kTestShardIndex << " < " << kTestTotalShards
05897 << ", but you have " << kTestShardIndex << "=" << shard_index
05898 << ", " << kTestTotalShards << "=" << total_shards << ".\n";
05899 ColoredPrintf(COLOR_RED, msg.GetString().c_str());
05900 fflush(stdout);
05901 exit(EXIT_FAILURE);
05902 }
05903
05904 return total_shards > 1;
05905 }
05906
05907
05908
05909
05910 Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) {
05911 const char* str_val = posix::GetEnv(var);
05912 if (str_val == NULL) {
05913 return default_val;
05914 }
05915
05916 Int32 result;
05917 if (!ParseInt32(Message() << "The value of environment variable " << var,
05918 str_val, &result)) {
05919 exit(EXIT_FAILURE);
05920 }
05921 return result;
05922 }
05923
05924
05925
05926
05927
05928 bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
05929 return (test_id % total_shards) == shard_index;
05930 }
05931
05932
05933
05934
05935
05936
05937
05938
05939 int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
05940 const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?
05941 Int32FromEnvOrDie(kTestTotalShards, -1) : -1;
05942 const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?
05943 Int32FromEnvOrDie(kTestShardIndex, -1) : -1;
05944
05945
05946
05947
05948
05949 int num_runnable_tests = 0;
05950 int num_selected_tests = 0;
05951 for (size_t i = 0; i < test_cases_.size(); i++) {
05952 TestCase* const test_case = test_cases_[i];
05953 const std::string &test_case_name = test_case->name();
05954 test_case->set_should_run(false);
05955
05956 for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
05957 TestInfo* const test_info = test_case->test_info_list()[j];
05958 const std::string test_name(test_info->name());
05959
05960
05961 const bool is_disabled =
05962 internal::UnitTestOptions::MatchesFilter(test_case_name,
05963 kDisableTestFilter) ||
05964 internal::UnitTestOptions::MatchesFilter(test_name,
05965 kDisableTestFilter);
05966 test_info->is_disabled_ = is_disabled;
05967
05968 const bool matches_filter =
05969 internal::UnitTestOptions::FilterMatchesTest(test_case_name,
05970 test_name);
05971 test_info->matches_filter_ = matches_filter;
05972
05973 const bool is_runnable =
05974 (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
05975 matches_filter;
05976
05977 const bool is_selected = is_runnable &&
05978 (shard_tests == IGNORE_SHARDING_PROTOCOL ||
05979 ShouldRunTestOnShard(total_shards, shard_index,
05980 num_runnable_tests));
05981
05982 num_runnable_tests += is_runnable;
05983 num_selected_tests += is_selected;
05984
05985 test_info->should_run_ = is_selected;
05986 test_case->set_should_run(test_case->should_run() || is_selected);
05987 }
05988 }
05989 return num_selected_tests;
05990 }
05991
05992
05993
05994
05995
05996 static void PrintOnOneLine(const char* str, int max_length) {
05997 if (str != NULL) {
05998 for (int i = 0; *str != '\0'; ++str) {
05999 if (i >= max_length) {
06000 printf("...");
06001 break;
06002 }
06003 if (*str == '\n') {
06004 printf("\\n");
06005 i += 2;
06006 } else {
06007 printf("%c", *str);
06008 ++i;
06009 }
06010 }
06011 }
06012 }
06013
06014
06015 void UnitTestImpl::ListTestsMatchingFilter() {
06016
06017 const int kMaxParamLength = 250;
06018
06019 for (size_t i = 0; i < test_cases_.size(); i++) {
06020 const TestCase* const test_case = test_cases_[i];
06021 bool printed_test_case_name = false;
06022
06023 for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
06024 const TestInfo* const test_info =
06025 test_case->test_info_list()[j];
06026 if (test_info->matches_filter_) {
06027 if (!printed_test_case_name) {
06028 printed_test_case_name = true;
06029 printf("%s.", test_case->name());
06030 if (test_case->type_param() != NULL) {
06031 printf(" # %s = ", kTypeParamLabel);
06032
06033
06034 PrintOnOneLine(test_case->type_param(), kMaxParamLength);
06035 }
06036 printf("\n");
06037 }
06038 printf(" %s", test_info->name());
06039 if (test_info->value_param() != NULL) {
06040 printf(" # %s = ", kValueParamLabel);
06041
06042
06043 PrintOnOneLine(test_info->value_param(), kMaxParamLength);
06044 }
06045 printf("\n");
06046 }
06047 }
06048 }
06049 fflush(stdout);
06050 }
06051
06052
06053
06054
06055
06056
06057 void UnitTestImpl::set_os_stack_trace_getter(
06058 OsStackTraceGetterInterface* getter) {
06059 if (os_stack_trace_getter_ != getter) {
06060 delete os_stack_trace_getter_;
06061 os_stack_trace_getter_ = getter;
06062 }
06063 }
06064
06065
06066
06067
06068 OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
06069 if (os_stack_trace_getter_ == NULL) {
06070 os_stack_trace_getter_ = new OsStackTraceGetter;
06071 }
06072
06073 return os_stack_trace_getter_;
06074 }
06075
06076
06077
06078 TestResult* UnitTestImpl::current_test_result() {
06079 return current_test_info_ ?
06080 &(current_test_info_->result_) : &ad_hoc_test_result_;
06081 }
06082
06083
06084
06085 void UnitTestImpl::ShuffleTests() {
06086
06087 ShuffleRange(random(), 0, last_death_test_case_ + 1, &test_case_indices_);
06088
06089
06090 ShuffleRange(random(), last_death_test_case_ + 1,
06091 static_cast<int>(test_cases_.size()), &test_case_indices_);
06092
06093
06094 for (size_t i = 0; i < test_cases_.size(); i++) {
06095 test_cases_[i]->ShuffleTests(random());
06096 }
06097 }
06098
06099
06100 void UnitTestImpl::UnshuffleTests() {
06101 for (size_t i = 0; i < test_cases_.size(); i++) {
06102
06103 test_cases_[i]->UnshuffleTests();
06104
06105 test_case_indices_[i] = static_cast<int>(i);
06106 }
06107 }
06108
06109
06110
06111
06112
06113
06114
06115
06116
06117
06118
06119 std::string GetCurrentOsStackTraceExceptTop(UnitTest* ,
06120 int skip_count) {
06121
06122
06123 return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
06124 }
06125
06126
06127
06128 namespace {
06129 class ClassUniqueToAlwaysTrue {};
06130 }
06131
06132 bool IsTrue(bool condition) { return condition; }
06133
06134 bool AlwaysTrue() {
06135 #if GTEST_HAS_EXCEPTIONS
06136
06137
06138 if (IsTrue(false))
06139 throw ClassUniqueToAlwaysTrue();
06140 #endif // GTEST_HAS_EXCEPTIONS
06141 return true;
06142 }
06143
06144
06145
06146
06147 bool SkipPrefix(const char* prefix, const char** pstr) {
06148 const size_t prefix_len = strlen(prefix);
06149 if (strncmp(*pstr, prefix, prefix_len) == 0) {
06150 *pstr += prefix_len;
06151 return true;
06152 }
06153 return false;
06154 }
06155
06156
06157
06158
06159
06160
06161 const char* ParseFlagValue(const char* str,
06162 const char* flag,
06163 bool def_optional) {
06164
06165 if (str == NULL || flag == NULL) return NULL;
06166
06167
06168 const std::string flag_str = std::string("--") + GTEST_FLAG_PREFIX_ + flag;
06169 const size_t flag_len = flag_str.length();
06170 if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;
06171
06172
06173 const char* flag_end = str + flag_len;
06174
06175
06176 if (def_optional && (flag_end[0] == '\0')) {
06177 return flag_end;
06178 }
06179
06180
06181
06182
06183 if (flag_end[0] != '=') return NULL;
06184
06185
06186 return flag_end + 1;
06187 }
06188
06189
06190
06191
06192
06193
06194
06195
06196
06197
06198
06199 bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
06200
06201 const char* const value_str = ParseFlagValue(str, flag, true);
06202
06203
06204 if (value_str == NULL) return false;
06205
06206
06207 *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
06208 return true;
06209 }
06210
06211
06212
06213
06214
06215
06216 bool ParseInt32Flag(const char* str, const char* flag, Int32* value) {
06217
06218 const char* const value_str = ParseFlagValue(str, flag, false);
06219
06220
06221 if (value_str == NULL) return false;
06222
06223
06224 return ParseInt32(Message() << "The value of flag --" << flag,
06225 value_str, value);
06226 }
06227
06228
06229
06230
06231
06232
06233 bool ParseStringFlag(const char* str, const char* flag, std::string* value) {
06234
06235 const char* const value_str = ParseFlagValue(str, flag, false);
06236
06237
06238 if (value_str == NULL) return false;
06239
06240
06241 *value = value_str;
06242 return true;
06243 }
06244
06245
06246
06247
06248
06249
06250
06251 static bool HasGoogleTestFlagPrefix(const char* str) {
06252 return (SkipPrefix("--", &str) ||
06253 SkipPrefix("-", &str) ||
06254 SkipPrefix("/", &str)) &&
06255 !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
06256 (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
06257 SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str));
06258 }
06259
06260
06261
06262
06263
06264
06265
06266
06267
06268
06269
06270
06271 static void PrintColorEncoded(const char* str) {
06272 GTestColor color = COLOR_DEFAULT;
06273
06274
06275
06276
06277
06278 for (;;) {
06279 const char* p = strchr(str, '@');
06280 if (p == NULL) {
06281 ColoredPrintf(color, "%s", str);
06282 return;
06283 }
06284
06285 ColoredPrintf(color, "%s", std::string(str, p).c_str());
06286
06287 const char ch = p[1];
06288 str = p + 2;
06289 if (ch == '@') {
06290 ColoredPrintf(color, "@");
06291 } else if (ch == 'D') {
06292 color = COLOR_DEFAULT;
06293 } else if (ch == 'R') {
06294 color = COLOR_RED;
06295 } else if (ch == 'G') {
06296 color = COLOR_GREEN;
06297 } else if (ch == 'Y') {
06298 color = COLOR_YELLOW;
06299 } else {
06300 --str;
06301 }
06302 }
06303 }
06304
06305 static const char kColorEncodedHelpMessage[] =
06306 "This program contains tests written using " GTEST_NAME_ ". You can use the\n"
06307 "following command line flags to control its behavior:\n"
06308 "\n"
06309 "Test Selection:\n"
06310 " @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n"
06311 " List the names of all tests instead of running them. The name of\n"
06312 " TEST(Foo, Bar) is \"Foo.Bar\".\n"
06313 " @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS"
06314 "[@G-@YNEGATIVE_PATTERNS]@D\n"
06315 " Run only the tests whose name matches one of the positive patterns but\n"
06316 " none of the negative patterns. '?' matches any single character; '*'\n"
06317 " matches any substring; ':' separates two patterns.\n"
06318 " @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n"
06319 " Run all disabled tests too.\n"
06320 "\n"
06321 "Test Execution:\n"
06322 " @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n"
06323 " Run the tests repeatedly; use a negative count to repeat forever.\n"
06324 " @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n"
06325 " Randomize tests' orders on every iteration.\n"
06326 " @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n"
06327 " Random number seed to use for shuffling test orders (between 1 and\n"
06328 " 99999, or 0 to use a seed based on the current time).\n"
06329 "\n"
06330 "Test Output:\n"
06331 " @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
06332 " Enable/disable colored output. The default is @Gauto@D.\n"
06333 " -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n"
06334 " Don't print the elapsed time of each test.\n"
06335 " @G--" GTEST_FLAG_PREFIX_ "output=xml@Y[@G:@YDIRECTORY_PATH@G"
06336 GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n"
06337 " Generate an XML report in the given directory or with the given file\n"
06338 " name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n"
06339 #if GTEST_CAN_STREAM_RESULTS_
06340 " @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n"
06341 " Stream test results to the given server.\n"
06342 #endif // GTEST_CAN_STREAM_RESULTS_
06343 "\n"
06344 "Assertion Behavior:\n"
06345 #if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
06346 " @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
06347 " Set the default death test style.\n"
06348 #endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
06349 " @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n"
06350 " Turn assertion failures into debugger break-points.\n"
06351 " @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n"
06352 " Turn assertion failures into C++ exceptions.\n"
06353 " @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n"
06354 " Do not report exceptions as test failures. Instead, allow them\n"
06355 " to crash the program or throw a pop-up (on Windows).\n"
06356 "\n"
06357 "Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set "
06358 "the corresponding\n"
06359 "environment variable of a flag (all letters in upper-case). For example, to\n"
06360 "disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_
06361 "color=no@D or set\n"
06362 "the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n"
06363 "\n"
06364 "For more information, please read the " GTEST_NAME_ " documentation at\n"
06365 "@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n"
06366 "(not one in your own code or tests), please report it to\n"
06367 "@G<" GTEST_DEV_EMAIL_ ">@D.\n";
06368
06369
06370
06371
06372 template <typename CharType>
06373 void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
06374 for (int i = 1; i < *argc; i++) {
06375 const std::string arg_string = StreamableToString(argv[i]);
06376 const char* const arg = arg_string.c_str();
06377
06378 using internal::ParseBoolFlag;
06379 using internal::ParseInt32Flag;
06380 using internal::ParseStringFlag;
06381
06382
06383 if (ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,
06384 >EST_FLAG(also_run_disabled_tests)) ||
06385 ParseBoolFlag(arg, kBreakOnFailureFlag,
06386 >EST_FLAG(break_on_failure)) ||
06387 ParseBoolFlag(arg, kCatchExceptionsFlag,
06388 >EST_FLAG(catch_exceptions)) ||
06389 ParseStringFlag(arg, kColorFlag, >EST_FLAG(color)) ||
06390 ParseStringFlag(arg, kDeathTestStyleFlag,
06391 >EST_FLAG(death_test_style)) ||
06392 ParseBoolFlag(arg, kDeathTestUseFork,
06393 >EST_FLAG(death_test_use_fork)) ||
06394 ParseStringFlag(arg, kFilterFlag, >EST_FLAG(filter)) ||
06395 ParseStringFlag(arg, kInternalRunDeathTestFlag,
06396 >EST_FLAG(internal_run_death_test)) ||
06397 ParseBoolFlag(arg, kListTestsFlag, >EST_FLAG(list_tests)) ||
06398 ParseStringFlag(arg, kOutputFlag, >EST_FLAG(output)) ||
06399 ParseBoolFlag(arg, kPrintTimeFlag, >EST_FLAG(print_time)) ||
06400 ParseInt32Flag(arg, kRandomSeedFlag, >EST_FLAG(random_seed)) ||
06401 ParseInt32Flag(arg, kRepeatFlag, >EST_FLAG(repeat)) ||
06402 ParseBoolFlag(arg, kShuffleFlag, >EST_FLAG(shuffle)) ||
06403 ParseInt32Flag(arg, kStackTraceDepthFlag,
06404 >EST_FLAG(stack_trace_depth)) ||
06405 ParseStringFlag(arg, kStreamResultToFlag,
06406 >EST_FLAG(stream_result_to)) ||
06407 ParseBoolFlag(arg, kThrowOnFailureFlag,
06408 >EST_FLAG(throw_on_failure))
06409 ) {
06410
06411
06412
06413
06414 for (int j = i; j != *argc; j++) {
06415 argv[j] = argv[j + 1];
06416 }
06417
06418
06419 (*argc)--;
06420
06421
06422
06423 i--;
06424 } else if (arg_string == "--help" || arg_string == "-h" ||
06425 arg_string == "-?" || arg_string == "/?" ||
06426 HasGoogleTestFlagPrefix(arg)) {
06427
06428
06429 g_help_flag = true;
06430 }
06431 }
06432
06433 if (g_help_flag) {
06434
06435
06436
06437 PrintColorEncoded(kColorEncodedHelpMessage);
06438 }
06439 }
06440
06441
06442
06443 void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
06444 ParseGoogleTestFlagsOnlyImpl(argc, argv);
06445 }
06446 void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {
06447 ParseGoogleTestFlagsOnlyImpl(argc, argv);
06448 }
06449
06450
06451
06452
06453
06454 template <typename CharType>
06455 void InitGoogleTestImpl(int* argc, CharType** argv) {
06456 g_init_gtest_count++;
06457
06458
06459 if (g_init_gtest_count != 1) return;
06460
06461 if (*argc <= 0) return;
06462
06463 internal::g_executable_path = internal::StreamableToString(argv[0]);
06464
06465 #if GTEST_HAS_DEATH_TEST
06466
06467 g_argvs.clear();
06468 for (int i = 0; i != *argc; i++) {
06469 g_argvs.push_back(StreamableToString(argv[i]));
06470 }
06471
06472 #endif // GTEST_HAS_DEATH_TEST
06473
06474 ParseGoogleTestFlagsOnly(argc, argv);
06475 GetUnitTestImpl()->PostFlagParsingInit();
06476 }
06477
06478 }
06479
06480
06481
06482
06483
06484
06485
06486
06487
06488
06489 void InitGoogleTest(int* argc, char** argv) {
06490 internal::InitGoogleTestImpl(argc, argv);
06491 }
06492
06493
06494
06495 void InitGoogleTest(int* argc, wchar_t** argv) {
06496 internal::InitGoogleTestImpl(argc, argv);
06497 }
06498
06499 }
06500
06501
06502
06503
06504
06505
06506
06507
06508
06509
06510
06511
06512
06513
06514
06515
06516
06517
06518
06519
06520
06521
06522
06523
06524
06525
06526
06527
06528
06529
06530
06531
06532
06533
06534 #if GTEST_HAS_DEATH_TEST
06535
06536 # if GTEST_OS_MAC
06537 # include <crt_externs.h>
06538 # endif // GTEST_OS_MAC
06539
06540 # include <errno.h>
06541 # include <fcntl.h>
06542 # include <limits.h>
06543
06544 # if GTEST_OS_LINUX
06545 # include <signal.h>
06546 # endif // GTEST_OS_LINUX
06547
06548 # include <stdarg.h>
06549
06550 # if GTEST_OS_WINDOWS
06551 # include <windows.h>
06552 # else
06553 # include <sys/mman.h>
06554 # include <sys/wait.h>
06555 # endif // GTEST_OS_WINDOWS
06556
06557 # if GTEST_OS_QNX
06558 # include <spawn.h>
06559 # endif // GTEST_OS_QNX
06560
06561 #endif // GTEST_HAS_DEATH_TEST
06562
06563
06564
06565
06566
06567
06568
06569 #define GTEST_IMPLEMENTATION_ 1
06570 #undef GTEST_IMPLEMENTATION_
06571
06572 namespace testing {
06573
06574
06575
06576
06577 static const char kDefaultDeathTestStyle[] = "fast";
06578
06579 GTEST_DEFINE_string_(
06580 death_test_style,
06581 internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle),
06582 "Indicates how to run a death test in a forked child process: "
06583 "\"threadsafe\" (child process re-executes the test binary "
06584 "from the beginning, running only the specific death test) or "
06585 "\"fast\" (child process runs the death test immediately "
06586 "after forking).");
06587
06588 GTEST_DEFINE_bool_(
06589 death_test_use_fork,
06590 internal::BoolFromGTestEnv("death_test_use_fork", false),
06591 "Instructs to use fork()/_exit() instead of clone() in death tests. "
06592 "Ignored and always uses fork() on POSIX systems where clone() is not "
06593 "implemented. Useful when running under valgrind or similar tools if "
06594 "those do not support clone(). Valgrind 3.3.1 will just fail if "
06595 "it sees an unsupported combination of clone() flags. "
06596 "It is not recommended to use this flag w/o valgrind though it will "
06597 "work in 99% of the cases. Once valgrind is fixed, this flag will "
06598 "most likely be removed.");
06599
06600 namespace internal {
06601 GTEST_DEFINE_string_(
06602 internal_run_death_test, "",
06603 "Indicates the file, line number, temporal index of "
06604 "the single death test to run, and a file descriptor to "
06605 "which a success code may be sent, all separated by "
06606 "the '|' characters. This flag is specified if and only if the current "
06607 "process is a sub-process launched for running a thread-safe "
06608 "death test. FOR INTERNAL USE ONLY.");
06609 }
06610
06611 #if GTEST_HAS_DEATH_TEST
06612
06613 namespace internal {
06614
06615
06616
06617 static bool g_in_fast_death_test_child = false;
06618
06619
06620
06621
06622
06623
06624 bool InDeathTestChild() {
06625 # if GTEST_OS_WINDOWS
06626
06627
06628
06629 return !GTEST_FLAG(internal_run_death_test).empty();
06630
06631 # else
06632
06633 if (GTEST_FLAG(death_test_style) == "threadsafe")
06634 return !GTEST_FLAG(internal_run_death_test).empty();
06635 else
06636 return g_in_fast_death_test_child;
06637 #endif
06638 }
06639
06640 }
06641
06642
06643 ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {
06644 }
06645
06646
06647 bool ExitedWithCode::operator()(int exit_status) const {
06648 # if GTEST_OS_WINDOWS
06649
06650 return exit_status == exit_code_;
06651
06652 # else
06653
06654 return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;
06655
06656 # endif // GTEST_OS_WINDOWS
06657 }
06658
06659 # if !GTEST_OS_WINDOWS
06660
06661 KilledBySignal::KilledBySignal(int signum) : signum_(signum) {
06662 }
06663
06664
06665 bool KilledBySignal::operator()(int exit_status) const {
06666 return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;
06667 }
06668 # endif // !GTEST_OS_WINDOWS
06669
06670 namespace internal {
06671
06672
06673
06674
06675
06676 static std::string ExitSummary(int exit_code) {
06677 Message m;
06678
06679 # if GTEST_OS_WINDOWS
06680
06681 m << "Exited with exit status " << exit_code;
06682
06683 # else
06684
06685 if (WIFEXITED(exit_code)) {
06686 m << "Exited with exit status " << WEXITSTATUS(exit_code);
06687 } else if (WIFSIGNALED(exit_code)) {
06688 m << "Terminated by signal " << WTERMSIG(exit_code);
06689 }
06690 # ifdef WCOREDUMP
06691 if (WCOREDUMP(exit_code)) {
06692 m << " (core dumped)";
06693 }
06694 # endif
06695 # endif // GTEST_OS_WINDOWS
06696
06697 return m.GetString();
06698 }
06699
06700
06701
06702 bool ExitedUnsuccessfully(int exit_status) {
06703 return !ExitedWithCode(0)(exit_status);
06704 }
06705
06706 # if !GTEST_OS_WINDOWS
06707
06708
06709
06710
06711 static std::string DeathTestThreadWarning(size_t thread_count) {
06712 Message msg;
06713 msg << "Death tests use fork(), which is unsafe particularly"
06714 << " in a threaded context. For this test, " << GTEST_NAME_ << " ";
06715 if (thread_count == 0)
06716 msg << "couldn't detect the number of threads.";
06717 else
06718 msg << "detected " << thread_count << " threads.";
06719 return msg.GetString();
06720 }
06721 # endif // !GTEST_OS_WINDOWS
06722
06723
06724 static const char kDeathTestLived = 'L';
06725 static const char kDeathTestReturned = 'R';
06726 static const char kDeathTestThrew = 'T';
06727 static const char kDeathTestInternalError = 'I';
06728
06729
06730
06731
06732
06733
06734
06735
06736
06737
06738 enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW };
06739
06740
06741
06742
06743
06744
06745 void DeathTestAbort(const std::string& message) {
06746
06747
06748
06749 const InternalRunDeathTestFlag* const flag =
06750 GetUnitTestImpl()->internal_run_death_test_flag();
06751 if (flag != NULL) {
06752 FILE* parent = posix::FDOpen(flag->write_fd(), "w");
06753 fputc(kDeathTestInternalError, parent);
06754 fprintf(parent, "%s", message.c_str());
06755 fflush(parent);
06756 _exit(1);
06757 } else {
06758 fprintf(stderr, "%s", message.c_str());
06759 fflush(stderr);
06760 posix::Abort();
06761 }
06762 }
06763
06764
06765
06766 # define GTEST_DEATH_TEST_CHECK_(expression) \
06767 do { \
06768 if (!::testing::internal::IsTrue(expression)) { \
06769 DeathTestAbort( \
06770 ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
06771 + ::testing::internal::StreamableToString(__LINE__) + ": " \
06772 + #expression); \
06773 } \
06774 } while (::testing::internal::AlwaysFalse())
06775
06776
06777
06778
06779
06780
06781
06782
06783 # define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
06784 do { \
06785 int gtest_retval; \
06786 do { \
06787 gtest_retval = (expression); \
06788 } while (gtest_retval == -1 && errno == EINTR); \
06789 if (gtest_retval == -1) { \
06790 DeathTestAbort( \
06791 ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
06792 + ::testing::internal::StreamableToString(__LINE__) + ": " \
06793 + #expression + " != -1"); \
06794 } \
06795 } while (::testing::internal::AlwaysFalse())
06796
06797
06798 std::string GetLastErrnoDescription() {
06799 return errno == 0 ? "" : posix::StrError(errno);
06800 }
06801
06802
06803
06804
06805
06806 static void FailFromInternalError(int fd) {
06807 Message error;
06808 char buffer[256];
06809 int num_read;
06810
06811 do {
06812 while ((num_read = posix::Read(fd, buffer, 255)) > 0) {
06813 buffer[num_read] = '\0';
06814 error << buffer;
06815 }
06816 } while (num_read == -1 && errno == EINTR);
06817
06818 if (num_read == 0) {
06819 GTEST_LOG_(FATAL) << error.GetString();
06820 } else {
06821 const int last_error = errno;
06822 GTEST_LOG_(FATAL) << "Error while reading death test internal: "
06823 << GetLastErrnoDescription() << " [" << last_error << "]";
06824 }
06825 }
06826
06827
06828
06829 DeathTest::DeathTest() {
06830 TestInfo* const info = GetUnitTestImpl()->current_test_info();
06831 if (info == NULL) {
06832 DeathTestAbort("Cannot run a death test outside of a TEST or "
06833 "TEST_F construct");
06834 }
06835 }
06836
06837
06838
06839 bool DeathTest::Create(const char* statement, const RE* regex,
06840 const char* file, int line, DeathTest** test) {
06841 return GetUnitTestImpl()->death_test_factory()->Create(
06842 statement, regex, file, line, test);
06843 }
06844
06845 const char* DeathTest::LastMessage() {
06846 return last_death_test_message_.c_str();
06847 }
06848
06849 void DeathTest::set_last_death_test_message(const std::string& message) {
06850 last_death_test_message_ = message;
06851 }
06852
06853 std::string DeathTest::last_death_test_message_;
06854
06855
06856 class DeathTestImpl : public DeathTest {
06857 protected:
06858 DeathTestImpl(const char* a_statement, const RE* a_regex)
06859 : statement_(a_statement),
06860 regex_(a_regex),
06861 spawned_(false),
06862 status_(-1),
06863 outcome_(IN_PROGRESS),
06864 read_fd_(-1),
06865 write_fd_(-1) {}
06866
06867
06868 ~DeathTestImpl() { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); }
06869
06870 void Abort(AbortReason reason);
06871 virtual bool Passed(bool status_ok);
06872
06873 const char* statement() const { return statement_; }
06874 const RE* regex() const { return regex_; }
06875 bool spawned() const { return spawned_; }
06876 void set_spawned(bool is_spawned) { spawned_ = is_spawned; }
06877 int status() const { return status_; }
06878 void set_status(int a_status) { status_ = a_status; }
06879 DeathTestOutcome outcome() const { return outcome_; }
06880 void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; }
06881 int read_fd() const { return read_fd_; }
06882 void set_read_fd(int fd) { read_fd_ = fd; }
06883 int write_fd() const { return write_fd_; }
06884 void set_write_fd(int fd) { write_fd_ = fd; }
06885
06886
06887
06888
06889
06890 void ReadAndInterpretStatusByte();
06891
06892 private:
06893
06894
06895 const char* const statement_;
06896
06897
06898 const RE* const regex_;
06899
06900 bool spawned_;
06901
06902 int status_;
06903
06904 DeathTestOutcome outcome_;
06905
06906
06907
06908 int read_fd_;
06909
06910
06911
06912 int write_fd_;
06913 };
06914
06915
06916
06917
06918
06919 void DeathTestImpl::ReadAndInterpretStatusByte() {
06920 char flag;
06921 int bytes_read;
06922
06923
06924
06925
06926
06927 do {
06928 bytes_read = posix::Read(read_fd(), &flag, 1);
06929 } while (bytes_read == -1 && errno == EINTR);
06930
06931 if (bytes_read == 0) {
06932 set_outcome(DIED);
06933 } else if (bytes_read == 1) {
06934 switch (flag) {
06935 case kDeathTestReturned:
06936 set_outcome(RETURNED);
06937 break;
06938 case kDeathTestThrew:
06939 set_outcome(THREW);
06940 break;
06941 case kDeathTestLived:
06942 set_outcome(LIVED);
06943 break;
06944 case kDeathTestInternalError:
06945 FailFromInternalError(read_fd());
06946 break;
06947 default:
06948 GTEST_LOG_(FATAL) << "Death test child process reported "
06949 << "unexpected status byte ("
06950 << static_cast<unsigned int>(flag) << ")";
06951 }
06952 } else {
06953 GTEST_LOG_(FATAL) << "Read from death test child process failed: "
06954 << GetLastErrnoDescription();
06955 }
06956 GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd()));
06957 set_read_fd(-1);
06958 }
06959
06960
06961
06962
06963
06964 void DeathTestImpl::Abort(AbortReason reason) {
06965
06966
06967
06968 const char status_ch =
06969 reason == TEST_DID_NOT_DIE ? kDeathTestLived :
06970 reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned;
06971
06972 GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1));
06973
06974
06975
06976
06977
06978
06979
06980
06981 _exit(1);
06982 }
06983
06984
06985
06986
06987 static ::std::string FormatDeathTestOutput(const ::std::string& output) {
06988 ::std::string ret;
06989 for (size_t at = 0; ; ) {
06990 const size_t line_end = output.find('\n', at);
06991 ret += "[ DEATH ] ";
06992 if (line_end == ::std::string::npos) {
06993 ret += output.substr(at);
06994 break;
06995 }
06996 ret += output.substr(at, line_end + 1 - at);
06997 at = line_end + 1;
06998 }
06999 return ret;
07000 }
07001
07002
07003
07004
07005
07006
07007
07008
07009
07010
07011
07012
07013
07014
07015
07016
07017
07018
07019
07020
07021
07022
07023
07024 bool DeathTestImpl::Passed(bool status_ok) {
07025 if (!spawned())
07026 return false;
07027
07028 const std::string error_message = GetCapturedStderr();
07029
07030 bool success = false;
07031 Message buffer;
07032
07033 buffer << "Death test: " << statement() << "\n";
07034 switch (outcome()) {
07035 case LIVED:
07036 buffer << " Result: failed to die.\n"
07037 << " Error msg:\n" << FormatDeathTestOutput(error_message);
07038 break;
07039 case THREW:
07040 buffer << " Result: threw an exception.\n"
07041 << " Error msg:\n" << FormatDeathTestOutput(error_message);
07042 break;
07043 case RETURNED:
07044 buffer << " Result: illegal return in test statement.\n"
07045 << " Error msg:\n" << FormatDeathTestOutput(error_message);
07046 break;
07047 case DIED:
07048 if (status_ok) {
07049 const bool matched = RE::PartialMatch(error_message.c_str(), *regex());
07050 if (matched) {
07051 success = true;
07052 } else {
07053 buffer << " Result: died but not with expected error.\n"
07054 << " Expected: " << regex()->pattern() << "\n"
07055 << "Actual msg:\n" << FormatDeathTestOutput(error_message);
07056 }
07057 } else {
07058 buffer << " Result: died but not with expected exit code:\n"
07059 << " " << ExitSummary(status()) << "\n"
07060 << "Actual msg:\n" << FormatDeathTestOutput(error_message);
07061 }
07062 break;
07063 case IN_PROGRESS:
07064 default:
07065 GTEST_LOG_(FATAL)
07066 << "DeathTest::Passed somehow called before conclusion of test";
07067 }
07068
07069 DeathTest::set_last_death_test_message(buffer.GetString());
07070 return success;
07071 }
07072
07073 # if GTEST_OS_WINDOWS
07074
07075
07076
07077
07078
07079
07080
07081
07082
07083
07084
07085
07086
07087
07088
07089
07090
07091
07092
07093
07094
07095
07096
07097
07098
07099
07100
07101
07102 class WindowsDeathTest : public DeathTestImpl {
07103 public:
07104 WindowsDeathTest(const char* a_statement,
07105 const RE* a_regex,
07106 const char* file,
07107 int line)
07108 : DeathTestImpl(a_statement, a_regex), file_(file), line_(line) {}
07109
07110
07111 virtual int Wait();
07112 virtual TestRole AssumeRole();
07113
07114 private:
07115
07116 const char* const file_;
07117
07118 const int line_;
07119
07120 AutoHandle write_handle_;
07121
07122 AutoHandle child_handle_;
07123
07124
07125
07126
07127 AutoHandle event_handle_;
07128 };
07129
07130
07131
07132
07133 int WindowsDeathTest::Wait() {
07134 if (!spawned())
07135 return 0;
07136
07137
07138
07139 const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() };
07140 switch (::WaitForMultipleObjects(2,
07141 wait_handles,
07142 FALSE,
07143 INFINITE)) {
07144 case WAIT_OBJECT_0:
07145 case WAIT_OBJECT_0 + 1:
07146 break;
07147 default:
07148 GTEST_DEATH_TEST_CHECK_(false);
07149 }
07150
07151
07152
07153 write_handle_.Reset();
07154 event_handle_.Reset();
07155
07156 ReadAndInterpretStatusByte();
07157
07158
07159
07160
07161
07162 GTEST_DEATH_TEST_CHECK_(
07163 WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(),
07164 INFINITE));
07165 DWORD status_code;
07166 GTEST_DEATH_TEST_CHECK_(
07167 ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE);
07168 child_handle_.Reset();
07169 set_status(static_cast<int>(status_code));
07170 return status();
07171 }
07172
07173
07174
07175
07176
07177
07178 DeathTest::TestRole WindowsDeathTest::AssumeRole() {
07179 const UnitTestImpl* const impl = GetUnitTestImpl();
07180 const InternalRunDeathTestFlag* const flag =
07181 impl->internal_run_death_test_flag();
07182 const TestInfo* const info = impl->current_test_info();
07183 const int death_test_index = info->result()->death_test_count();
07184
07185 if (flag != NULL) {
07186
07187
07188 set_write_fd(flag->write_fd());
07189 return EXECUTE_TEST;
07190 }
07191
07192
07193
07194 SECURITY_ATTRIBUTES handles_are_inheritable = {
07195 sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };
07196 HANDLE read_handle, write_handle;
07197 GTEST_DEATH_TEST_CHECK_(
07198 ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable,
07199 0)
07200 != FALSE);
07201 set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle),
07202 O_RDONLY));
07203 write_handle_.Reset(write_handle);
07204 event_handle_.Reset(::CreateEvent(
07205 &handles_are_inheritable,
07206 TRUE,
07207 FALSE,
07208 NULL));
07209 GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL);
07210 const std::string filter_flag =
07211 std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "=" +
07212 info->test_case_name() + "." + info->name();
07213 const std::string internal_flag =
07214 std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag +
07215 "=" + file_ + "|" + StreamableToString(line_) + "|" +
07216 StreamableToString(death_test_index) + "|" +
07217 StreamableToString(static_cast<unsigned int>(::GetCurrentProcessId())) +
07218
07219
07220
07221 "|" + StreamableToString(reinterpret_cast<size_t>(write_handle)) +
07222 "|" + StreamableToString(reinterpret_cast<size_t>(event_handle_.Get()));
07223
07224 char executable_path[_MAX_PATH + 1];
07225 GTEST_DEATH_TEST_CHECK_(
07226 _MAX_PATH + 1 != ::GetModuleFileNameA(NULL,
07227 executable_path,
07228 _MAX_PATH));
07229
07230 std::string command_line =
07231 std::string(::GetCommandLineA()) + " " + filter_flag + " \"" +
07232 internal_flag + "\"";
07233
07234 DeathTest::set_last_death_test_message("");
07235
07236 CaptureStderr();
07237
07238 FlushInfoLog();
07239
07240
07241 STARTUPINFOA startup_info;
07242 memset(&startup_info, 0, sizeof(STARTUPINFO));
07243 startup_info.dwFlags = STARTF_USESTDHANDLES;
07244 startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE);
07245 startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE);
07246 startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE);
07247
07248 PROCESS_INFORMATION process_info;
07249 GTEST_DEATH_TEST_CHECK_(::CreateProcessA(
07250 executable_path,
07251 const_cast<char*>(command_line.c_str()),
07252 NULL,
07253 NULL,
07254 TRUE,
07255 0x0,
07256 NULL,
07257 UnitTest::GetInstance()->original_working_dir(),
07258 &startup_info,
07259 &process_info) != FALSE);
07260 child_handle_.Reset(process_info.hProcess);
07261 ::CloseHandle(process_info.hThread);
07262 set_spawned(true);
07263 return OVERSEE_TEST;
07264 }
07265 # else // We are not on Windows.
07266
07267
07268
07269
07270 class ForkingDeathTest : public DeathTestImpl {
07271 public:
07272 ForkingDeathTest(const char* statement, const RE* regex);
07273
07274
07275 virtual int Wait();
07276
07277 protected:
07278 void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; }
07279
07280 private:
07281
07282 pid_t child_pid_;
07283 };
07284
07285
07286 ForkingDeathTest::ForkingDeathTest(const char* a_statement, const RE* a_regex)
07287 : DeathTestImpl(a_statement, a_regex),
07288 child_pid_(-1) {}
07289
07290
07291
07292
07293 int ForkingDeathTest::Wait() {
07294 if (!spawned())
07295 return 0;
07296
07297 ReadAndInterpretStatusByte();
07298
07299 int status_value;
07300 GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0));
07301 set_status(status_value);
07302 return status_value;
07303 }
07304
07305
07306
07307 class NoExecDeathTest : public ForkingDeathTest {
07308 public:
07309 NoExecDeathTest(const char* a_statement, const RE* a_regex) :
07310 ForkingDeathTest(a_statement, a_regex) { }
07311 virtual TestRole AssumeRole();
07312 };
07313
07314
07315
07316 DeathTest::TestRole NoExecDeathTest::AssumeRole() {
07317 const size_t thread_count = GetThreadCount();
07318 if (thread_count != 1) {
07319 GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count);
07320 }
07321
07322 int pipe_fd[2];
07323 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
07324
07325 DeathTest::set_last_death_test_message("");
07326 CaptureStderr();
07327
07328
07329
07330
07331
07332
07333
07334 FlushInfoLog();
07335
07336 const pid_t child_pid = fork();
07337 GTEST_DEATH_TEST_CHECK_(child_pid != -1);
07338 set_child_pid(child_pid);
07339 if (child_pid == 0) {
07340 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0]));
07341 set_write_fd(pipe_fd[1]);
07342
07343
07344
07345 LogToStderr();
07346
07347
07348 GetUnitTestImpl()->listeners()->SuppressEventForwarding();
07349 g_in_fast_death_test_child = true;
07350 return EXECUTE_TEST;
07351 } else {
07352 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
07353 set_read_fd(pipe_fd[0]);
07354 set_spawned(true);
07355 return OVERSEE_TEST;
07356 }
07357 }
07358
07359
07360
07361
07362 class ExecDeathTest : public ForkingDeathTest {
07363 public:
07364 ExecDeathTest(const char* a_statement, const RE* a_regex,
07365 const char* file, int line) :
07366 ForkingDeathTest(a_statement, a_regex), file_(file), line_(line) { }
07367 virtual TestRole AssumeRole();
07368 private:
07369 static ::std::vector<testing::internal::string>
07370 GetArgvsForDeathTestChildProcess() {
07371 ::std::vector<testing::internal::string> args = GetInjectableArgvs();
07372 return args;
07373 }
07374
07375 const char* const file_;
07376
07377 const int line_;
07378 };
07379
07380
07381 class Arguments {
07382 public:
07383 Arguments() {
07384 args_.push_back(NULL);
07385 }
07386
07387 ~Arguments() {
07388 for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
07389 ++i) {
07390 free(*i);
07391 }
07392 }
07393 void AddArgument(const char* argument) {
07394 args_.insert(args_.end() - 1, posix::StrDup(argument));
07395 }
07396
07397 template <typename Str>
07398 void AddArguments(const ::std::vector<Str>& arguments) {
07399 for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
07400 i != arguments.end();
07401 ++i) {
07402 args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
07403 }
07404 }
07405 char* const* Argv() {
07406 return &args_[0];
07407 }
07408
07409 private:
07410 std::vector<char*> args_;
07411 };
07412
07413
07414
07415 struct ExecDeathTestArgs {
07416 char* const* argv;
07417 int close_fd;
07418 };
07419
07420 # if GTEST_OS_MAC
07421 inline char** GetEnviron() {
07422
07423
07424
07425 return *_NSGetEnviron();
07426 }
07427 # else
07428
07429
07430 extern "C" char** environ;
07431 inline char** GetEnviron() { return environ; }
07432 # endif // GTEST_OS_MAC
07433
07434 # if !GTEST_OS_QNX
07435
07436
07437
07438 static int ExecDeathTestChildMain(void* child_arg) {
07439 ExecDeathTestArgs* const args = static_cast<ExecDeathTestArgs*>(child_arg);
07440 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd));
07441
07442
07443
07444
07445 const char* const original_dir =
07446 UnitTest::GetInstance()->original_working_dir();
07447
07448 if (chdir(original_dir) != 0) {
07449 DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
07450 GetLastErrnoDescription());
07451 return EXIT_FAILURE;
07452 }
07453
07454
07455
07456
07457
07458
07459 execve(args->argv[0], args->argv, GetEnviron());
07460 DeathTestAbort(std::string("execve(") + args->argv[0] + ", ...) in " +
07461 original_dir + " failed: " +
07462 GetLastErrnoDescription());
07463 return EXIT_FAILURE;
07464 }
07465 # endif // !GTEST_OS_QNX
07466
07467
07468
07469
07470
07471
07472
07473
07474
07475
07476 void StackLowerThanAddress(const void* ptr, bool* result) GTEST_NO_INLINE_;
07477 void StackLowerThanAddress(const void* ptr, bool* result) {
07478 int dummy;
07479 *result = (&dummy < ptr);
07480 }
07481
07482 bool StackGrowsDown() {
07483 int dummy;
07484 bool result;
07485 StackLowerThanAddress(&dummy, &result);
07486 return result;
07487 }
07488
07489
07490
07491
07492
07493
07494
07495
07496 static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
07497 ExecDeathTestArgs args = { argv, close_fd };
07498 pid_t child_pid = -1;
07499
07500 # if GTEST_OS_QNX
07501
07502
07503 const int cwd_fd = open(".", O_RDONLY);
07504 GTEST_DEATH_TEST_CHECK_(cwd_fd != -1);
07505 GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC));
07506
07507
07508
07509 const char* const original_dir =
07510 UnitTest::GetInstance()->original_working_dir();
07511
07512 if (chdir(original_dir) != 0) {
07513 DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
07514 GetLastErrnoDescription());
07515 return EXIT_FAILURE;
07516 }
07517
07518 int fd_flags;
07519
07520 GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD));
07521 GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD,
07522 fd_flags | FD_CLOEXEC));
07523 struct inheritance inherit = {0};
07524
07525 child_pid = spawn(args.argv[0], 0, NULL, &inherit, args.argv, GetEnviron());
07526
07527 GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1);
07528 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));
07529
07530 # else // GTEST_OS_QNX
07531 # if GTEST_OS_LINUX
07532
07533
07534
07535 struct sigaction saved_sigprof_action;
07536 struct sigaction ignore_sigprof_action;
07537 memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action));
07538 sigemptyset(&ignore_sigprof_action.sa_mask);
07539 ignore_sigprof_action.sa_handler = SIG_IGN;
07540 GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction(
07541 SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));
07542 # endif // GTEST_OS_LINUX
07543
07544 # if GTEST_HAS_CLONE
07545 const bool use_fork = GTEST_FLAG(death_test_use_fork);
07546
07547 if (!use_fork) {
07548 static const bool stack_grows_down = StackGrowsDown();
07549 const size_t stack_size = getpagesize();
07550
07551 void* const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE,
07552 MAP_ANON | MAP_PRIVATE, -1, 0);
07553 GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED);
07554
07555
07556
07557
07558
07559
07560
07561 const size_t kMaxStackAlignment = 64;
07562 void* const stack_top =
07563 static_cast<char*>(stack) +
07564 (stack_grows_down ? stack_size - kMaxStackAlignment : 0);
07565 GTEST_DEATH_TEST_CHECK_(stack_size > kMaxStackAlignment &&
07566 reinterpret_cast<intptr_t>(stack_top) % kMaxStackAlignment == 0);
07567
07568 child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args);
07569
07570 GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);
07571 }
07572 # else
07573 const bool use_fork = true;
07574 # endif // GTEST_HAS_CLONE
07575
07576 if (use_fork && (child_pid = fork()) == 0) {
07577 ExecDeathTestChildMain(&args);
07578 _exit(0);
07579 }
07580 # endif // GTEST_OS_QNX
07581 # if GTEST_OS_LINUX
07582 GTEST_DEATH_TEST_CHECK_SYSCALL_(
07583 sigaction(SIGPROF, &saved_sigprof_action, NULL));
07584 # endif // GTEST_OS_LINUX
07585
07586 GTEST_DEATH_TEST_CHECK_(child_pid != -1);
07587 return child_pid;
07588 }
07589
07590
07591
07592
07593
07594 DeathTest::TestRole ExecDeathTest::AssumeRole() {
07595 const UnitTestImpl* const impl = GetUnitTestImpl();
07596 const InternalRunDeathTestFlag* const flag =
07597 impl->internal_run_death_test_flag();
07598 const TestInfo* const info = impl->current_test_info();
07599 const int death_test_index = info->result()->death_test_count();
07600
07601 if (flag != NULL) {
07602 set_write_fd(flag->write_fd());
07603 return EXECUTE_TEST;
07604 }
07605
07606 int pipe_fd[2];
07607 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
07608
07609
07610 GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
07611
07612 const std::string filter_flag =
07613 std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "="
07614 + info->test_case_name() + "." + info->name();
07615 const std::string internal_flag =
07616 std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "="
07617 + file_ + "|" + StreamableToString(line_) + "|"
07618 + StreamableToString(death_test_index) + "|"
07619 + StreamableToString(pipe_fd[1]);
07620 Arguments args;
07621 args.AddArguments(GetArgvsForDeathTestChildProcess());
07622 args.AddArgument(filter_flag.c_str());
07623 args.AddArgument(internal_flag.c_str());
07624
07625 DeathTest::set_last_death_test_message("");
07626
07627 CaptureStderr();
07628
07629
07630 FlushInfoLog();
07631
07632 const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]);
07633 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
07634 set_child_pid(child_pid);
07635 set_read_fd(pipe_fd[0]);
07636 set_spawned(true);
07637 return OVERSEE_TEST;
07638 }
07639
07640 # endif // !GTEST_OS_WINDOWS
07641
07642
07643
07644
07645
07646
07647 bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex,
07648 const char* file, int line,
07649 DeathTest** test) {
07650 UnitTestImpl* const impl = GetUnitTestImpl();
07651 const InternalRunDeathTestFlag* const flag =
07652 impl->internal_run_death_test_flag();
07653 const int death_test_index = impl->current_test_info()
07654 ->increment_death_test_count();
07655
07656 if (flag != NULL) {
07657 if (death_test_index > flag->index()) {
07658 DeathTest::set_last_death_test_message(
07659 "Death test count (" + StreamableToString(death_test_index)
07660 + ") somehow exceeded expected maximum ("
07661 + StreamableToString(flag->index()) + ")");
07662 return false;
07663 }
07664
07665 if (!(flag->file() == file && flag->line() == line &&
07666 flag->index() == death_test_index)) {
07667 *test = NULL;
07668 return true;
07669 }
07670 }
07671
07672 # if GTEST_OS_WINDOWS
07673
07674 if (GTEST_FLAG(death_test_style) == "threadsafe" ||
07675 GTEST_FLAG(death_test_style) == "fast") {
07676 *test = new WindowsDeathTest(statement, regex, file, line);
07677 }
07678
07679 # else
07680
07681 if (GTEST_FLAG(death_test_style) == "threadsafe") {
07682 *test = new ExecDeathTest(statement, regex, file, line);
07683 } else if (GTEST_FLAG(death_test_style) == "fast") {
07684 *test = new NoExecDeathTest(statement, regex);
07685 }
07686
07687 # endif // GTEST_OS_WINDOWS
07688
07689 else {
07690 DeathTest::set_last_death_test_message(
07691 "Unknown death test style \"" + GTEST_FLAG(death_test_style)
07692 + "\" encountered");
07693 return false;
07694 }
07695
07696 return true;
07697 }
07698
07699
07700
07701
07702 static void SplitString(const ::std::string& str, char delimiter,
07703 ::std::vector< ::std::string>* dest) {
07704 ::std::vector< ::std::string> parsed;
07705 ::std::string::size_type pos = 0;
07706 while (::testing::internal::AlwaysTrue()) {
07707 const ::std::string::size_type colon = str.find(delimiter, pos);
07708 if (colon == ::std::string::npos) {
07709 parsed.push_back(str.substr(pos));
07710 break;
07711 } else {
07712 parsed.push_back(str.substr(pos, colon - pos));
07713 pos = colon + 1;
07714 }
07715 }
07716 dest->swap(parsed);
07717 }
07718
07719 # if GTEST_OS_WINDOWS
07720
07721
07722
07723 int GetStatusFileDescriptor(unsigned int parent_process_id,
07724 size_t write_handle_as_size_t,
07725 size_t event_handle_as_size_t) {
07726 AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,
07727 FALSE,
07728 parent_process_id));
07729 if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {
07730 DeathTestAbort("Unable to open parent process " +
07731 StreamableToString(parent_process_id));
07732 }
07733
07734
07735
07736 GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t));
07737
07738 const HANDLE write_handle =
07739 reinterpret_cast<HANDLE>(write_handle_as_size_t);
07740 HANDLE dup_write_handle;
07741
07742
07743
07744
07745 if (!::DuplicateHandle(parent_process_handle.Get(), write_handle,
07746 ::GetCurrentProcess(), &dup_write_handle,
07747 0x0,
07748
07749 FALSE,
07750 DUPLICATE_SAME_ACCESS)) {
07751 DeathTestAbort("Unable to duplicate the pipe handle " +
07752 StreamableToString(write_handle_as_size_t) +
07753 " from the parent process " +
07754 StreamableToString(parent_process_id));
07755 }
07756
07757 const HANDLE event_handle = reinterpret_cast<HANDLE>(event_handle_as_size_t);
07758 HANDLE dup_event_handle;
07759
07760 if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,
07761 ::GetCurrentProcess(), &dup_event_handle,
07762 0x0,
07763 FALSE,
07764 DUPLICATE_SAME_ACCESS)) {
07765 DeathTestAbort("Unable to duplicate the event handle " +
07766 StreamableToString(event_handle_as_size_t) +
07767 " from the parent process " +
07768 StreamableToString(parent_process_id));
07769 }
07770
07771 const int write_fd =
07772 ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND);
07773 if (write_fd == -1) {
07774 DeathTestAbort("Unable to convert pipe handle " +
07775 StreamableToString(write_handle_as_size_t) +
07776 " to a file descriptor");
07777 }
07778
07779
07780
07781 ::SetEvent(dup_event_handle);
07782
07783 return write_fd;
07784 }
07785 # endif // GTEST_OS_WINDOWS
07786
07787
07788
07789
07790 InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
07791 if (GTEST_FLAG(internal_run_death_test) == "") return NULL;
07792
07793
07794
07795 int line = -1;
07796 int index = -1;
07797 ::std::vector< ::std::string> fields;
07798 SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields);
07799 int write_fd = -1;
07800
07801 # if GTEST_OS_WINDOWS
07802
07803 unsigned int parent_process_id = 0;
07804 size_t write_handle_as_size_t = 0;
07805 size_t event_handle_as_size_t = 0;
07806
07807 if (fields.size() != 6
07808 || !ParseNaturalNumber(fields[1], &line)
07809 || !ParseNaturalNumber(fields[2], &index)
07810 || !ParseNaturalNumber(fields[3], &parent_process_id)
07811 || !ParseNaturalNumber(fields[4], &write_handle_as_size_t)
07812 || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
07813 DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
07814 GTEST_FLAG(internal_run_death_test));
07815 }
07816 write_fd = GetStatusFileDescriptor(parent_process_id,
07817 write_handle_as_size_t,
07818 event_handle_as_size_t);
07819 # else
07820
07821 if (fields.size() != 4
07822 || !ParseNaturalNumber(fields[1], &line)
07823 || !ParseNaturalNumber(fields[2], &index)
07824 || !ParseNaturalNumber(fields[3], &write_fd)) {
07825 DeathTestAbort("Bad --gtest_internal_run_death_test flag: "
07826 + GTEST_FLAG(internal_run_death_test));
07827 }
07828
07829 # endif // GTEST_OS_WINDOWS
07830
07831 return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);
07832 }
07833
07834 }
07835
07836 #endif // GTEST_HAS_DEATH_TEST
07837
07838 }
07839
07840
07841
07842
07843
07844
07845
07846
07847
07848
07849
07850
07851
07852
07853
07854
07855
07856
07857
07858
07859
07860
07861
07862
07863
07864
07865
07866
07867
07868
07869
07870
07871 #include <stdlib.h>
07872
07873 #if GTEST_OS_WINDOWS_MOBILE
07874 # include <windows.h>
07875 #elif GTEST_OS_WINDOWS
07876 # include <direct.h>
07877 # include <io.h>
07878 #elif GTEST_OS_SYMBIAN
07879
07880 # include <sys/syslimits.h>
07881 #else
07882 # include <limits.h>
07883 # include <climits>
07884 #endif // GTEST_OS_WINDOWS_MOBILE
07885
07886 #if GTEST_OS_WINDOWS
07887 # define GTEST_PATH_MAX_ _MAX_PATH
07888 #elif defined(PATH_MAX)
07889 # define GTEST_PATH_MAX_ PATH_MAX
07890 #elif defined(_XOPEN_PATH_MAX)
07891 # define GTEST_PATH_MAX_ _XOPEN_PATH_MAX
07892 #else
07893 # define GTEST_PATH_MAX_ _POSIX_PATH_MAX
07894 #endif // GTEST_OS_WINDOWS
07895
07896
07897 namespace testing {
07898 namespace internal {
07899
07900 #if GTEST_OS_WINDOWS
07901
07902
07903
07904
07905 const char kPathSeparator = '\\';
07906 const char kAlternatePathSeparator = '/';
07907 const char kPathSeparatorString[] = "\\";
07908 const char kAlternatePathSeparatorString[] = "/";
07909 # if GTEST_OS_WINDOWS_MOBILE
07910
07911
07912
07913 const char kCurrentDirectoryString[] = "\\";
07914
07915 const DWORD kInvalidFileAttributes = 0xffffffff;
07916 # else
07917 const char kCurrentDirectoryString[] = ".\\";
07918 # endif // GTEST_OS_WINDOWS_MOBILE
07919 #else
07920 const char kPathSeparator = '/';
07921 const char kPathSeparatorString[] = "/";
07922 const char kCurrentDirectoryString[] = "./";
07923 #endif // GTEST_OS_WINDOWS
07924
07925
07926 static bool IsPathSeparator(char c) {
07927 #if GTEST_HAS_ALT_PATH_SEP_
07928 return (c == kPathSeparator) || (c == kAlternatePathSeparator);
07929 #else
07930 return c == kPathSeparator;
07931 #endif
07932 }
07933
07934
07935 FilePath FilePath::GetCurrentDir() {
07936 #if GTEST_OS_WINDOWS_MOBILE
07937
07938
07939 return FilePath(kCurrentDirectoryString);
07940 #elif GTEST_OS_WINDOWS
07941 char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
07942 return FilePath(_getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
07943 #else
07944 char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
07945 return FilePath(getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
07946 #endif // GTEST_OS_WINDOWS_MOBILE
07947 }
07948
07949
07950
07951
07952
07953 FilePath FilePath::RemoveExtension(const char* extension) const {
07954 const std::string dot_extension = std::string(".") + extension;
07955 if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) {
07956 return FilePath(pathname_.substr(
07957 0, pathname_.length() - dot_extension.length()));
07958 }
07959 return *this;
07960 }
07961
07962
07963
07964
07965 const char* FilePath::FindLastPathSeparator() const {
07966 const char* const last_sep = strrchr(c_str(), kPathSeparator);
07967 #if GTEST_HAS_ALT_PATH_SEP_
07968 const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator);
07969
07970 if (last_alt_sep != NULL &&
07971 (last_sep == NULL || last_alt_sep > last_sep)) {
07972 return last_alt_sep;
07973 }
07974 #endif
07975 return last_sep;
07976 }
07977
07978
07979
07980
07981
07982
07983
07984 FilePath FilePath::RemoveDirectoryName() const {
07985 const char* const last_sep = FindLastPathSeparator();
07986 return last_sep ? FilePath(last_sep + 1) : *this;
07987 }
07988
07989
07990
07991
07992
07993
07994
07995 FilePath FilePath::RemoveFileName() const {
07996 const char* const last_sep = FindLastPathSeparator();
07997 std::string dir;
07998 if (last_sep) {
07999 dir = std::string(c_str(), last_sep + 1 - c_str());
08000 } else {
08001 dir = kCurrentDirectoryString;
08002 }
08003 return FilePath(dir);
08004 }
08005
08006
08007
08008
08009
08010
08011
08012 FilePath FilePath::MakeFileName(const FilePath& directory,
08013 const FilePath& base_name,
08014 int number,
08015 const char* extension) {
08016 std::string file;
08017 if (number == 0) {
08018 file = base_name.string() + "." + extension;
08019 } else {
08020 file = base_name.string() + "_" + StreamableToString(number)
08021 + "." + extension;
08022 }
08023 return ConcatPaths(directory, FilePath(file));
08024 }
08025
08026
08027
08028 FilePath FilePath::ConcatPaths(const FilePath& directory,
08029 const FilePath& relative_path) {
08030 if (directory.IsEmpty())
08031 return relative_path;
08032 const FilePath dir(directory.RemoveTrailingPathSeparator());
08033 return FilePath(dir.string() + kPathSeparator + relative_path.string());
08034 }
08035
08036
08037
08038 bool FilePath::FileOrDirectoryExists() const {
08039 #if GTEST_OS_WINDOWS_MOBILE
08040 LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());
08041 const DWORD attributes = GetFileAttributes(unicode);
08042 delete [] unicode;
08043 return attributes != kInvalidFileAttributes;
08044 #else
08045 posix::StatStruct file_stat;
08046 return posix::Stat(pathname_.c_str(), &file_stat) == 0;
08047 #endif // GTEST_OS_WINDOWS_MOBILE
08048 }
08049
08050
08051
08052 bool FilePath::DirectoryExists() const {
08053 bool result = false;
08054 #if GTEST_OS_WINDOWS
08055
08056
08057 const FilePath& path(IsRootDirectory() ? *this :
08058 RemoveTrailingPathSeparator());
08059 #else
08060 const FilePath& path(*this);
08061 #endif
08062
08063 #if GTEST_OS_WINDOWS_MOBILE
08064 LPCWSTR unicode = String::AnsiToUtf16(path.c_str());
08065 const DWORD attributes = GetFileAttributes(unicode);
08066 delete [] unicode;
08067 if ((attributes != kInvalidFileAttributes) &&
08068 (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
08069 result = true;
08070 }
08071 #else
08072 posix::StatStruct file_stat;
08073 result = posix::Stat(path.c_str(), &file_stat) == 0 &&
08074 posix::IsDir(file_stat);
08075 #endif // GTEST_OS_WINDOWS_MOBILE
08076
08077 return result;
08078 }
08079
08080
08081
08082 bool FilePath::IsRootDirectory() const {
08083 #if GTEST_OS_WINDOWS
08084
08085
08086
08087 return pathname_.length() == 3 && IsAbsolutePath();
08088 #else
08089 return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]);
08090 #endif
08091 }
08092
08093
08094 bool FilePath::IsAbsolutePath() const {
08095 const char* const name = pathname_.c_str();
08096 #if GTEST_OS_WINDOWS
08097 return pathname_.length() >= 3 &&
08098 ((name[0] >= 'a' && name[0] <= 'z') ||
08099 (name[0] >= 'A' && name[0] <= 'Z')) &&
08100 name[1] == ':' &&
08101 IsPathSeparator(name[2]);
08102 #else
08103 return IsPathSeparator(name[0]);
08104 #endif
08105 }
08106
08107
08108
08109
08110
08111
08112
08113
08114
08115 FilePath FilePath::GenerateUniqueFileName(const FilePath& directory,
08116 const FilePath& base_name,
08117 const char* extension) {
08118 FilePath full_pathname;
08119 int number = 0;
08120 do {
08121 full_pathname.Set(MakeFileName(directory, base_name, number++, extension));
08122 } while (full_pathname.FileOrDirectoryExists());
08123 return full_pathname;
08124 }
08125
08126
08127
08128
08129 bool FilePath::IsDirectory() const {
08130 return !pathname_.empty() &&
08131 IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]);
08132 }
08133
08134
08135
08136
08137 bool FilePath::CreateDirectoriesRecursively() const {
08138 if (!this->IsDirectory()) {
08139 return false;
08140 }
08141
08142 if (pathname_.length() == 0 || this->DirectoryExists()) {
08143 return true;
08144 }
08145
08146 const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName());
08147 return parent.CreateDirectoriesRecursively() && this->CreateFolder();
08148 }
08149
08150
08151
08152
08153
08154 bool FilePath::CreateFolder() const {
08155 #if GTEST_OS_WINDOWS_MOBILE
08156 FilePath removed_sep(this->RemoveTrailingPathSeparator());
08157 LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());
08158 int result = CreateDirectory(unicode, NULL) ? 0 : -1;
08159 delete [] unicode;
08160 #elif GTEST_OS_WINDOWS
08161 int result = _mkdir(pathname_.c_str());
08162 #else
08163 int result = mkdir(pathname_.c_str(), 0777);
08164 #endif // GTEST_OS_WINDOWS_MOBILE
08165
08166 if (result == -1) {
08167 return this->DirectoryExists();
08168 }
08169 return true;
08170 }
08171
08172
08173
08174
08175 FilePath FilePath::RemoveTrailingPathSeparator() const {
08176 return IsDirectory()
08177 ? FilePath(pathname_.substr(0, pathname_.length() - 1))
08178 : *this;
08179 }
08180
08181
08182
08183
08184
08185 void FilePath::Normalize() {
08186 if (pathname_.c_str() == NULL) {
08187 pathname_ = "";
08188 return;
08189 }
08190 const char* src = pathname_.c_str();
08191 char* const dest = new char[pathname_.length() + 1];
08192 char* dest_ptr = dest;
08193 memset(dest_ptr, 0, pathname_.length() + 1);
08194
08195 while (*src != '\0') {
08196 *dest_ptr = *src;
08197 if (!IsPathSeparator(*src)) {
08198 src++;
08199 } else {
08200 #if GTEST_HAS_ALT_PATH_SEP_
08201 if (*dest_ptr == kAlternatePathSeparator) {
08202 *dest_ptr = kPathSeparator;
08203 }
08204 #endif
08205 while (IsPathSeparator(*src))
08206 src++;
08207 }
08208 dest_ptr++;
08209 }
08210 *dest_ptr = '\0';
08211 pathname_ = dest;
08212 delete[] dest;
08213 }
08214
08215 }
08216 }
08217
08218
08219
08220
08221
08222
08223
08224
08225
08226
08227
08228
08229
08230
08231
08232
08233
08234
08235
08236
08237
08238
08239
08240
08241
08242
08243
08244
08245
08246
08247
08248
08249 #include <limits.h>
08250 #include <stdlib.h>
08251 #include <stdio.h>
08252 #include <string.h>
08253
08254 #if GTEST_OS_WINDOWS_MOBILE
08255 # include <windows.h>
08256 #elif GTEST_OS_WINDOWS
08257 # include <io.h>
08258 # include <sys/stat.h>
08259 #else
08260 # include <unistd.h>
08261 #endif // GTEST_OS_WINDOWS_MOBILE
08262
08263 #if GTEST_OS_MAC
08264 # include <mach/mach_init.h>
08265 # include <mach/task.h>
08266 # include <mach/vm_map.h>
08267 #endif // GTEST_OS_MAC
08268
08269 #if GTEST_OS_QNX
08270 # include <devctl.h>
08271 # include <sys/procfs.h>
08272 #endif // GTEST_OS_QNX
08273
08274
08275
08276
08277
08278
08279
08280 #define GTEST_IMPLEMENTATION_ 1
08281 #undef GTEST_IMPLEMENTATION_
08282
08283 namespace testing {
08284 namespace internal {
08285
08286 #if defined(_MSC_VER) || defined(__BORLANDC__)
08287
08288 const int kStdOutFileno = 1;
08289 const int kStdErrFileno = 2;
08290 #else
08291 const int kStdOutFileno = STDOUT_FILENO;
08292 const int kStdErrFileno = STDERR_FILENO;
08293 #endif // _MSC_VER
08294
08295 #if GTEST_OS_MAC
08296
08297
08298
08299 size_t GetThreadCount() {
08300 const task_t task = mach_task_self();
08301 mach_msg_type_number_t thread_count;
08302 thread_act_array_t thread_list;
08303 const kern_return_t status = task_threads(task, &thread_list, &thread_count);
08304 if (status == KERN_SUCCESS) {
08305
08306
08307 vm_deallocate(task,
08308 reinterpret_cast<vm_address_t>(thread_list),
08309 sizeof(thread_t) * thread_count);
08310 return static_cast<size_t>(thread_count);
08311 } else {
08312 return 0;
08313 }
08314 }
08315
08316 #elif GTEST_OS_QNX
08317
08318
08319
08320 size_t GetThreadCount() {
08321 const int fd = open("/proc/self/as", O_RDONLY);
08322 if (fd < 0) {
08323 return 0;
08324 }
08325 procfs_info process_info;
08326 const int status =
08327 devctl(fd, DCMD_PROC_INFO, &process_info, sizeof(process_info), NULL);
08328 close(fd);
08329 if (status == EOK) {
08330 return static_cast<size_t>(process_info.num_threads);
08331 } else {
08332 return 0;
08333 }
08334 }
08335
08336 #else
08337
08338 size_t GetThreadCount() {
08339
08340
08341 return 0;
08342 }
08343
08344 #endif // GTEST_OS_MAC
08345
08346 #if GTEST_USES_POSIX_RE
08347
08348
08349
08350 RE::~RE() {
08351 if (is_valid_) {
08352
08353
08354
08355
08356 regfree(&partial_regex_);
08357 regfree(&full_regex_);
08358 }
08359 free(const_cast<char*>(pattern_));
08360 }
08361
08362
08363 bool RE::FullMatch(const char* str, const RE& re) {
08364 if (!re.is_valid_) return false;
08365
08366 regmatch_t match;
08367 return regexec(&re.full_regex_, str, 1, &match, 0) == 0;
08368 }
08369
08370
08371
08372 bool RE::PartialMatch(const char* str, const RE& re) {
08373 if (!re.is_valid_) return false;
08374
08375 regmatch_t match;
08376 return regexec(&re.partial_regex_, str, 1, &match, 0) == 0;
08377 }
08378
08379
08380 void RE::Init(const char* regex) {
08381 pattern_ = posix::StrDup(regex);
08382
08383
08384
08385 const size_t full_regex_len = strlen(regex) + 10;
08386 char* const full_pattern = new char[full_regex_len];
08387
08388 snprintf(full_pattern, full_regex_len, "^(%s)$", regex);
08389 is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0;
08390
08391
08392
08393
08394
08395
08396
08397
08398 if (is_valid_) {
08399 const char* const partial_regex = (*regex == '\0') ? "()" : regex;
08400 is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0;
08401 }
08402 EXPECT_TRUE(is_valid_)
08403 << "Regular expression \"" << regex
08404 << "\" is not a valid POSIX Extended regular expression.";
08405
08406 delete[] full_pattern;
08407 }
08408
08409 #elif GTEST_USES_SIMPLE_RE
08410
08411
08412
08413 bool IsInSet(char ch, const char* str) {
08414 return ch != '\0' && strchr(str, ch) != NULL;
08415 }
08416
08417
08418
08419
08420 bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; }
08421 bool IsAsciiPunct(char ch) {
08422 return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
08423 }
08424 bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); }
08425 bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); }
08426 bool IsAsciiWordChar(char ch) {
08427 return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') ||
08428 ('0' <= ch && ch <= '9') || ch == '_';
08429 }
08430
08431
08432 bool IsValidEscape(char c) {
08433 return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW"));
08434 }
08435
08436
08437
08438 bool AtomMatchesChar(bool escaped, char pattern_char, char ch) {
08439 if (escaped) {
08440 switch (pattern_char) {
08441 case 'd': return IsAsciiDigit(ch);
08442 case 'D': return !IsAsciiDigit(ch);
08443 case 'f': return ch == '\f';
08444 case 'n': return ch == '\n';
08445 case 'r': return ch == '\r';
08446 case 's': return IsAsciiWhiteSpace(ch);
08447 case 'S': return !IsAsciiWhiteSpace(ch);
08448 case 't': return ch == '\t';
08449 case 'v': return ch == '\v';
08450 case 'w': return IsAsciiWordChar(ch);
08451 case 'W': return !IsAsciiWordChar(ch);
08452 }
08453 return IsAsciiPunct(pattern_char) && pattern_char == ch;
08454 }
08455
08456 return (pattern_char == '.' && ch != '\n') || pattern_char == ch;
08457 }
08458
08459
08460 std::string FormatRegexSyntaxError(const char* regex, int index) {
08461 return (Message() << "Syntax error at index " << index
08462 << " in simple regular expression \"" << regex << "\": ").GetString();
08463 }
08464
08465
08466
08467 bool ValidateRegex(const char* regex) {
08468 if (regex == NULL) {
08469
08470
08471
08472 ADD_FAILURE() << "NULL is not a valid simple regular expression.";
08473 return false;
08474 }
08475
08476 bool is_valid = true;
08477
08478
08479 bool prev_repeatable = false;
08480 for (int i = 0; regex[i]; i++) {
08481 if (regex[i] == '\\') {
08482 i++;
08483 if (regex[i] == '\0') {
08484 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
08485 << "'\\' cannot appear at the end.";
08486 return false;
08487 }
08488
08489 if (!IsValidEscape(regex[i])) {
08490 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
08491 << "invalid escape sequence \"\\" << regex[i] << "\".";
08492 is_valid = false;
08493 }
08494 prev_repeatable = true;
08495 } else {
08496 const char ch = regex[i];
08497
08498 if (ch == '^' && i > 0) {
08499 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
08500 << "'^' can only appear at the beginning.";
08501 is_valid = false;
08502 } else if (ch == '$' && regex[i + 1] != '\0') {
08503 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
08504 << "'$' can only appear at the end.";
08505 is_valid = false;
08506 } else if (IsInSet(ch, "()[]{}|")) {
08507 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
08508 << "'" << ch << "' is unsupported.";
08509 is_valid = false;
08510 } else if (IsRepeat(ch) && !prev_repeatable) {
08511 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
08512 << "'" << ch << "' can only follow a repeatable token.";
08513 is_valid = false;
08514 }
08515
08516 prev_repeatable = !IsInSet(ch, "^$?*+");
08517 }
08518 }
08519
08520 return is_valid;
08521 }
08522
08523
08524
08525
08526
08527
08528
08529
08530 bool MatchRepetitionAndRegexAtHead(
08531 bool escaped, char c, char repeat, const char* regex,
08532 const char* str) {
08533 const size_t min_count = (repeat == '+') ? 1 : 0;
08534 const size_t max_count = (repeat == '?') ? 1 :
08535 static_cast<size_t>(-1) - 1;
08536
08537
08538
08539 for (size_t i = 0; i <= max_count; ++i) {
08540
08541 if (i >= min_count && MatchRegexAtHead(regex, str + i)) {
08542
08543
08544
08545
08546 return true;
08547 }
08548 if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i]))
08549 return false;
08550 }
08551 return false;
08552 }
08553
08554
08555
08556
08557 bool MatchRegexAtHead(const char* regex, const char* str) {
08558 if (*regex == '\0')
08559 return true;
08560
08561
08562
08563 if (*regex == '$')
08564 return *str == '\0';
08565
08566
08567 const bool escaped = *regex == '\\';
08568 if (escaped)
08569 ++regex;
08570 if (IsRepeat(regex[1])) {
08571
08572
08573
08574 return MatchRepetitionAndRegexAtHead(
08575 escaped, regex[0], regex[1], regex + 2, str);
08576 } else {
08577
08578
08579
08580 return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) &&
08581 MatchRegexAtHead(regex + 1, str + 1);
08582 }
08583 }
08584
08585
08586
08587
08588
08589
08590
08591
08592
08593 bool MatchRegexAnywhere(const char* regex, const char* str) {
08594 if (regex == NULL || str == NULL)
08595 return false;
08596
08597 if (*regex == '^')
08598 return MatchRegexAtHead(regex + 1, str);
08599
08600
08601 do {
08602 if (MatchRegexAtHead(regex, str))
08603 return true;
08604 } while (*str++ != '\0');
08605 return false;
08606 }
08607
08608
08609
08610 RE::~RE() {
08611 free(const_cast<char*>(pattern_));
08612 free(const_cast<char*>(full_pattern_));
08613 }
08614
08615
08616 bool RE::FullMatch(const char* str, const RE& re) {
08617 return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);
08618 }
08619
08620
08621
08622 bool RE::PartialMatch(const char* str, const RE& re) {
08623 return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);
08624 }
08625
08626
08627 void RE::Init(const char* regex) {
08628 pattern_ = full_pattern_ = NULL;
08629 if (regex != NULL) {
08630 pattern_ = posix::StrDup(regex);
08631 }
08632
08633 is_valid_ = ValidateRegex(regex);
08634 if (!is_valid_) {
08635
08636 return;
08637 }
08638
08639 const size_t len = strlen(regex);
08640
08641
08642
08643 char* buffer = static_cast<char*>(malloc(len + 3));
08644 full_pattern_ = buffer;
08645
08646 if (*regex != '^')
08647 *buffer++ = '^';
08648
08649
08650
08651 memcpy(buffer, regex, len);
08652 buffer += len;
08653
08654 if (len == 0 || regex[len - 1] != '$')
08655 *buffer++ = '$';
08656
08657 *buffer = '\0';
08658 }
08659
08660 #endif // GTEST_USES_POSIX_RE
08661
08662 const char kUnknownFile[] = "unknown file";
08663
08664
08665
08666 GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) {
08667 const std::string file_name(file == NULL ? kUnknownFile : file);
08668
08669 if (line < 0) {
08670 return file_name + ":";
08671 }
08672 #ifdef _MSC_VER
08673 return file_name + "(" + StreamableToString(line) + "):";
08674 #else
08675 return file_name + ":" + StreamableToString(line) + ":";
08676 #endif // _MSC_VER
08677 }
08678
08679
08680
08681
08682
08683
08684 GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(
08685 const char* file, int line) {
08686 const std::string file_name(file == NULL ? kUnknownFile : file);
08687
08688 if (line < 0)
08689 return file_name;
08690 else
08691 return file_name + ":" + StreamableToString(line);
08692 }
08693
08694
08695 GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line)
08696 : severity_(severity) {
08697 const char* const marker =
08698 severity == GTEST_INFO ? "[ INFO ]" :
08699 severity == GTEST_WARNING ? "[WARNING]" :
08700 severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]";
08701 GetStream() << ::std::endl << marker << " "
08702 << FormatFileLocation(file, line).c_str() << ": ";
08703 }
08704
08705
08706 GTestLog::~GTestLog() {
08707 GetStream() << ::std::endl;
08708 if (severity_ == GTEST_FATAL) {
08709 fflush(stderr);
08710 posix::Abort();
08711 }
08712 }
08713
08714
08715 #ifdef _MSC_VER
08716 # pragma warning(push)
08717 # pragma warning(disable: 4996)
08718 #endif // _MSC_VER
08719
08720 #if GTEST_HAS_STREAM_REDIRECTION
08721
08722
08723 class CapturedStream {
08724 public:
08725
08726 explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {
08727 # if GTEST_OS_WINDOWS
08728 char temp_dir_path[MAX_PATH + 1] = { '\0' };
08729 char temp_file_path[MAX_PATH + 1] = { '\0' };
08730
08731 ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path);
08732 const UINT success = ::GetTempFileNameA(temp_dir_path,
08733 "gtest_redir",
08734 0,
08735 temp_file_path);
08736 GTEST_CHECK_(success != 0)
08737 << "Unable to create a temporary file in " << temp_dir_path;
08738 const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
08739 GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file "
08740 << temp_file_path;
08741 filename_ = temp_file_path;
08742 # else
08743
08744
08745
08746
08747 # if GTEST_OS_LINUX_ANDROID
08748
08749
08750
08751
08752
08753
08754
08755
08756
08757
08758
08759
08760
08761
08762 char name_template[] = "/sdcard/gtest_captured_stream.XXXXXX";
08763 # else
08764 char name_template[] = "/tmp/captured_stream.XXXXXX";
08765 # endif // GTEST_OS_LINUX_ANDROID
08766 const int captured_fd = mkstemp(name_template);
08767 filename_ = name_template;
08768 # endif // GTEST_OS_WINDOWS
08769 fflush(NULL);
08770 dup2(captured_fd, fd_);
08771 close(captured_fd);
08772 }
08773
08774 ~CapturedStream() {
08775 remove(filename_.c_str());
08776 }
08777
08778 std::string GetCapturedString() {
08779 if (uncaptured_fd_ != -1) {
08780
08781 fflush(NULL);
08782 dup2(uncaptured_fd_, fd_);
08783 close(uncaptured_fd_);
08784 uncaptured_fd_ = -1;
08785 }
08786
08787 FILE* const file = posix::FOpen(filename_.c_str(), "r");
08788 const std::string content = ReadEntireFile(file);
08789 posix::FClose(file);
08790 return content;
08791 }
08792
08793 private:
08794
08795 static std::string ReadEntireFile(FILE* file);
08796
08797
08798 static size_t GetFileSize(FILE* file);
08799
08800 const int fd_;
08801 int uncaptured_fd_;
08802
08803 ::std::string filename_;
08804
08805 GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream);
08806 };
08807
08808
08809 size_t CapturedStream::GetFileSize(FILE* file) {
08810 fseek(file, 0, SEEK_END);
08811 return static_cast<size_t>(ftell(file));
08812 }
08813
08814
08815 std::string CapturedStream::ReadEntireFile(FILE* file) {
08816 const size_t file_size = GetFileSize(file);
08817 char* const buffer = new char[file_size];
08818
08819 size_t bytes_last_read = 0;
08820 size_t bytes_read = 0;
08821
08822 fseek(file, 0, SEEK_SET);
08823
08824
08825
08826 do {
08827 bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
08828 bytes_read += bytes_last_read;
08829 } while (bytes_last_read > 0 && bytes_read < file_size);
08830
08831 const std::string content(buffer, bytes_read);
08832 delete[] buffer;
08833
08834 return content;
08835 }
08836
08837 # ifdef _MSC_VER
08838 # pragma warning(pop)
08839 # endif // _MSC_VER
08840
08841 static CapturedStream* g_captured_stderr = NULL;
08842 static CapturedStream* g_captured_stdout = NULL;
08843
08844
08845 void CaptureStream(int fd, const char* stream_name, CapturedStream** stream) {
08846 if (*stream != NULL) {
08847 GTEST_LOG_(FATAL) << "Only one " << stream_name
08848 << " capturer can exist at a time.";
08849 }
08850 *stream = new CapturedStream(fd);
08851 }
08852
08853
08854 std::string GetCapturedStream(CapturedStream** captured_stream) {
08855 const std::string content = (*captured_stream)->GetCapturedString();
08856
08857 delete *captured_stream;
08858 *captured_stream = NULL;
08859
08860 return content;
08861 }
08862
08863
08864 void CaptureStdout() {
08865 CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout);
08866 }
08867
08868
08869 void CaptureStderr() {
08870 CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr);
08871 }
08872
08873
08874 std::string GetCapturedStdout() {
08875 return GetCapturedStream(&g_captured_stdout);
08876 }
08877
08878
08879 std::string GetCapturedStderr() {
08880 return GetCapturedStream(&g_captured_stderr);
08881 }
08882
08883 #endif // GTEST_HAS_STREAM_REDIRECTION
08884
08885 #if GTEST_HAS_DEATH_TEST
08886
08887
08888 ::std::vector<testing::internal::string> g_argvs;
08889
08890 static const ::std::vector<testing::internal::string>* g_injected_test_argvs =
08891 NULL;
08892
08893 void SetInjectableArgvs(const ::std::vector<testing::internal::string>* argvs) {
08894 if (g_injected_test_argvs != argvs)
08895 delete g_injected_test_argvs;
08896 g_injected_test_argvs = argvs;
08897 }
08898
08899 const ::std::vector<testing::internal::string>& GetInjectableArgvs() {
08900 if (g_injected_test_argvs != NULL) {
08901 return *g_injected_test_argvs;
08902 }
08903 return g_argvs;
08904 }
08905 #endif // GTEST_HAS_DEATH_TEST
08906
08907 #if GTEST_OS_WINDOWS_MOBILE
08908 namespace posix {
08909 void Abort() {
08910 DebugBreak();
08911 TerminateProcess(GetCurrentProcess(), 1);
08912 }
08913 }
08914 #endif // GTEST_OS_WINDOWS_MOBILE
08915
08916
08917
08918
08919 static std::string FlagToEnvVar(const char* flag) {
08920 const std::string full_flag =
08921 (Message() << GTEST_FLAG_PREFIX_ << flag).GetString();
08922
08923 Message env_var;
08924 for (size_t i = 0; i != full_flag.length(); i++) {
08925 env_var << ToUpper(full_flag.c_str()[i]);
08926 }
08927
08928 return env_var.GetString();
08929 }
08930
08931
08932
08933
08934 bool ParseInt32(const Message& src_text, const char* str, Int32* value) {
08935
08936 char* end = NULL;
08937 const long long_value = strtol(str, &end, 10);
08938
08939
08940 if (*end != '\0') {
08941
08942 Message msg;
08943 msg << "WARNING: " << src_text
08944 << " is expected to be a 32-bit integer, but actually"
08945 << " has value \"" << str << "\".\n";
08946 printf("%s", msg.GetString().c_str());
08947 fflush(stdout);
08948 return false;
08949 }
08950
08951
08952 const Int32 result = static_cast<Int32>(long_value);
08953 if (long_value == LONG_MAX || long_value == LONG_MIN ||
08954
08955
08956 result != long_value
08957
08958 ) {
08959 Message msg;
08960 msg << "WARNING: " << src_text
08961 << " is expected to be a 32-bit integer, but actually"
08962 << " has value " << str << ", which overflows.\n";
08963 printf("%s", msg.GetString().c_str());
08964 fflush(stdout);
08965 return false;
08966 }
08967
08968 *value = result;
08969 return true;
08970 }
08971
08972
08973
08974
08975
08976 bool BoolFromGTestEnv(const char* flag, bool default_value) {
08977 const std::string env_var = FlagToEnvVar(flag);
08978 const char* const string_value = posix::GetEnv(env_var.c_str());
08979 return string_value == NULL ?
08980 default_value : strcmp(string_value, "0") != 0;
08981 }
08982
08983
08984
08985
08986 Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) {
08987 const std::string env_var = FlagToEnvVar(flag);
08988 const char* const string_value = posix::GetEnv(env_var.c_str());
08989 if (string_value == NULL) {
08990
08991 return default_value;
08992 }
08993
08994 Int32 result = default_value;
08995 if (!ParseInt32(Message() << "Environment variable " << env_var,
08996 string_value, &result)) {
08997 printf("The default value %s is used.\n",
08998 (Message() << default_value).GetString().c_str());
08999 fflush(stdout);
09000 return default_value;
09001 }
09002
09003 return result;
09004 }
09005
09006
09007
09008 const char* StringFromGTestEnv(const char* flag, const char* default_value) {
09009 const std::string env_var = FlagToEnvVar(flag);
09010 const char* const value = posix::GetEnv(env_var.c_str());
09011 return value == NULL ? default_value : value;
09012 }
09013
09014 }
09015 }
09016
09017
09018
09019
09020
09021
09022
09023
09024
09025
09026
09027
09028
09029
09030
09031
09032
09033
09034
09035
09036
09037
09038
09039
09040
09041
09042
09043
09044
09045
09046
09047
09048
09049
09050
09051
09052
09053
09054
09055
09056
09057
09058
09059
09060 #include <ctype.h>
09061 #include <stdio.h>
09062 #include <ostream>
09063 #include <string>
09064
09065 namespace testing {
09066
09067 namespace {
09068
09069 using ::std::ostream;
09070
09071
09072 void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start,
09073 size_t count, ostream* os) {
09074 char text[5] = "";
09075 for (size_t i = 0; i != count; i++) {
09076 const size_t j = start + i;
09077 if (i != 0) {
09078
09079
09080 if ((j % 2) == 0)
09081 *os << ' ';
09082 else
09083 *os << '-';
09084 }
09085 GTEST_SNPRINTF_(text, sizeof(text), "%02X", obj_bytes[j]);
09086 *os << text;
09087 }
09088 }
09089
09090
09091 void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count,
09092 ostream* os) {
09093
09094 *os << count << "-byte object <";
09095
09096 const size_t kThreshold = 132;
09097 const size_t kChunkSize = 64;
09098
09099
09100
09101
09102 if (count < kThreshold) {
09103 PrintByteSegmentInObjectTo(obj_bytes, 0, count, os);
09104 } else {
09105 PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os);
09106 *os << " ... ";
09107
09108 const size_t resume_pos = (count - kChunkSize + 1)/2*2;
09109 PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os);
09110 }
09111 *os << ">";
09112 }
09113
09114 }
09115
09116 namespace internal2 {
09117
09118
09119
09120
09121
09122
09123 void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count,
09124 ostream* os) {
09125 PrintBytesInObjectToImpl(obj_bytes, count, os);
09126 }
09127
09128 }
09129
09130 namespace internal {
09131
09132
09133
09134
09135
09136
09137 enum CharFormat {
09138 kAsIs,
09139 kHexEscape,
09140 kSpecialEscape
09141 };
09142
09143
09144
09145
09146 inline bool IsPrintableAscii(wchar_t c) {
09147 return 0x20 <= c && c <= 0x7E;
09148 }
09149
09150
09151
09152
09153
09154 template <typename UnsignedChar, typename Char>
09155 static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {
09156 switch (static_cast<wchar_t>(c)) {
09157 case L'\0':
09158 *os << "\\0";
09159 break;
09160 case L'\'':
09161 *os << "\\'";
09162 break;
09163 case L'\\':
09164 *os << "\\\\";
09165 break;
09166 case L'\a':
09167 *os << "\\a";
09168 break;
09169 case L'\b':
09170 *os << "\\b";
09171 break;
09172 case L'\f':
09173 *os << "\\f";
09174 break;
09175 case L'\n':
09176 *os << "\\n";
09177 break;
09178 case L'\r':
09179 *os << "\\r";
09180 break;
09181 case L'\t':
09182 *os << "\\t";
09183 break;
09184 case L'\v':
09185 *os << "\\v";
09186 break;
09187 default:
09188 if (IsPrintableAscii(c)) {
09189 *os << static_cast<char>(c);
09190 return kAsIs;
09191 } else {
09192 *os << "\\x" + String::FormatHexInt(static_cast<UnsignedChar>(c));
09193 return kHexEscape;
09194 }
09195 }
09196 return kSpecialEscape;
09197 }
09198
09199
09200
09201 static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) {
09202 switch (c) {
09203 case L'\'':
09204 *os << "'";
09205 return kAsIs;
09206 case L'"':
09207 *os << "\\\"";
09208 return kSpecialEscape;
09209 default:
09210 return PrintAsCharLiteralTo<wchar_t>(c, os);
09211 }
09212 }
09213
09214
09215
09216 static CharFormat PrintAsStringLiteralTo(char c, ostream* os) {
09217 return PrintAsStringLiteralTo(
09218 static_cast<wchar_t>(static_cast<unsigned char>(c)), os);
09219 }
09220
09221
09222
09223
09224
09225 template <typename UnsignedChar, typename Char>
09226 void PrintCharAndCodeTo(Char c, ostream* os) {
09227
09228 *os << ((sizeof(c) > 1) ? "L'" : "'");
09229 const CharFormat format = PrintAsCharLiteralTo<UnsignedChar>(c, os);
09230 *os << "'";
09231
09232
09233
09234
09235 if (c == 0)
09236 return;
09237 *os << " (" << static_cast<int>(c);
09238
09239
09240
09241
09242 if (format == kHexEscape || (1 <= c && c <= 9)) {
09243
09244 } else {
09245 *os << ", 0x" << String::FormatHexInt(static_cast<UnsignedChar>(c));
09246 }
09247 *os << ")";
09248 }
09249
09250 void PrintTo(unsigned char c, ::std::ostream* os) {
09251 PrintCharAndCodeTo<unsigned char>(c, os);
09252 }
09253 void PrintTo(signed char c, ::std::ostream* os) {
09254 PrintCharAndCodeTo<unsigned char>(c, os);
09255 }
09256
09257
09258
09259 void PrintTo(wchar_t wc, ostream* os) {
09260 PrintCharAndCodeTo<wchar_t>(wc, os);
09261 }
09262
09263
09264
09265
09266
09267 template <typename CharType>
09268 static void PrintCharsAsStringTo(
09269 const CharType* begin, size_t len, ostream* os) {
09270 const char* const kQuoteBegin = sizeof(CharType) == 1 ? "\"" : "L\"";
09271 *os << kQuoteBegin;
09272 bool is_previous_hex = false;
09273 for (size_t index = 0; index < len; ++index) {
09274 const CharType cur = begin[index];
09275 if (is_previous_hex && IsXDigit(cur)) {
09276
09277
09278
09279 *os << "\" " << kQuoteBegin;
09280 }
09281 is_previous_hex = PrintAsStringLiteralTo(cur, os) == kHexEscape;
09282 }
09283 *os << "\"";
09284 }
09285
09286
09287
09288 template <typename CharType>
09289 static void UniversalPrintCharArray(
09290 const CharType* begin, size_t len, ostream* os) {
09291
09292
09293
09294
09295
09296
09297
09298 if (len > 0 && begin[len - 1] == '\0') {
09299 PrintCharsAsStringTo(begin, len - 1, os);
09300 return;
09301 }
09302
09303
09304
09305
09306
09307 PrintCharsAsStringTo(begin, len, os);
09308 *os << " (no terminating NUL)";
09309 }
09310
09311
09312 void UniversalPrintArray(const char* begin, size_t len, ostream* os) {
09313 UniversalPrintCharArray(begin, len, os);
09314 }
09315
09316
09317
09318 void UniversalPrintArray(const wchar_t* begin, size_t len, ostream* os) {
09319 UniversalPrintCharArray(begin, len, os);
09320 }
09321
09322
09323 void PrintTo(const char* s, ostream* os) {
09324 if (s == NULL) {
09325 *os << "NULL";
09326 } else {
09327 *os << ImplicitCast_<const void*>(s) << " pointing to ";
09328 PrintCharsAsStringTo(s, strlen(s), os);
09329 }
09330 }
09331
09332
09333
09334
09335
09336
09337
09338 #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
09339
09340 void PrintTo(const wchar_t* s, ostream* os) {
09341 if (s == NULL) {
09342 *os << "NULL";
09343 } else {
09344 *os << ImplicitCast_<const void*>(s) << " pointing to ";
09345 PrintCharsAsStringTo(s, wcslen(s), os);
09346 }
09347 }
09348 #endif // wchar_t is native
09349
09350
09351 #if GTEST_HAS_GLOBAL_STRING
09352 void PrintStringTo(const ::string& s, ostream* os) {
09353 PrintCharsAsStringTo(s.data(), s.size(), os);
09354 }
09355 #endif // GTEST_HAS_GLOBAL_STRING
09356
09357 void PrintStringTo(const ::std::string& s, ostream* os) {
09358 PrintCharsAsStringTo(s.data(), s.size(), os);
09359 }
09360
09361
09362 #if GTEST_HAS_GLOBAL_WSTRING
09363 void PrintWideStringTo(const ::wstring& s, ostream* os) {
09364 PrintCharsAsStringTo(s.data(), s.size(), os);
09365 }
09366 #endif // GTEST_HAS_GLOBAL_WSTRING
09367
09368 #if GTEST_HAS_STD_WSTRING
09369 void PrintWideStringTo(const ::std::wstring& s, ostream* os) {
09370 PrintCharsAsStringTo(s.data(), s.size(), os);
09371 }
09372 #endif // GTEST_HAS_STD_WSTRING
09373
09374 }
09375
09376 }
09377
09378
09379
09380
09381
09382
09383
09384
09385
09386
09387
09388
09389
09390
09391
09392
09393
09394
09395
09396
09397
09398
09399
09400
09401
09402
09403
09404
09405
09406
09407
09408
09409
09410
09411
09412
09413
09414
09415
09416 #define GTEST_IMPLEMENTATION_ 1
09417 #undef GTEST_IMPLEMENTATION_
09418
09419 namespace testing {
09420
09421 using internal::GetUnitTestImpl;
09422
09423
09424
09425 std::string TestPartResult::ExtractSummary(const char* message) {
09426 const char* const stack_trace = strstr(message, internal::kStackTraceMarker);
09427 return stack_trace == NULL ? message :
09428 std::string(message, stack_trace);
09429 }
09430
09431
09432 std::ostream& operator<<(std::ostream& os, const TestPartResult& result) {
09433 return os
09434 << result.file_name() << ":" << result.line_number() << ": "
09435 << (result.type() == TestPartResult::kSuccess ? "Success" :
09436 result.type() == TestPartResult::kFatalFailure ? "Fatal failure" :
09437 "Non-fatal failure") << ":\n"
09438 << result.message() << std::endl;
09439 }
09440
09441
09442 void TestPartResultArray::Append(const TestPartResult& result) {
09443 array_.push_back(result);
09444 }
09445
09446
09447 const TestPartResult& TestPartResultArray::GetTestPartResult(int index) const {
09448 if (index < 0 || index >= size()) {
09449 printf("\nInvalid index (%d) into TestPartResultArray.\n", index);
09450 internal::posix::Abort();
09451 }
09452
09453 return array_[index];
09454 }
09455
09456
09457 int TestPartResultArray::size() const {
09458 return static_cast<int>(array_.size());
09459 }
09460
09461 namespace internal {
09462
09463 HasNewFatalFailureHelper::HasNewFatalFailureHelper()
09464 : has_new_fatal_failure_(false),
09465 original_reporter_(GetUnitTestImpl()->
09466 GetTestPartResultReporterForCurrentThread()) {
09467 GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this);
09468 }
09469
09470 HasNewFatalFailureHelper::~HasNewFatalFailureHelper() {
09471 GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(
09472 original_reporter_);
09473 }
09474
09475 void HasNewFatalFailureHelper::ReportTestPartResult(
09476 const TestPartResult& result) {
09477 if (result.fatally_failed())
09478 has_new_fatal_failure_ = true;
09479 original_reporter_->ReportTestPartResult(result);
09480 }
09481
09482 }
09483
09484 }
09485
09486
09487
09488
09489
09490
09491
09492
09493
09494
09495
09496
09497
09498
09499
09500
09501
09502
09503
09504
09505
09506
09507
09508
09509
09510
09511
09512
09513
09514
09515
09516
09517 namespace testing {
09518 namespace internal {
09519
09520 #if GTEST_HAS_TYPED_TEST_P
09521
09522
09523
09524 static const char* SkipSpaces(const char* str) {
09525 while (IsSpace(*str))
09526 str++;
09527 return str;
09528 }
09529
09530
09531
09532
09533 const char* TypedTestCasePState::VerifyRegisteredTestNames(
09534 const char* file, int line, const char* registered_tests) {
09535 typedef ::std::set<const char*>::const_iterator DefinedTestIter;
09536 registered_ = true;
09537
09538
09539
09540 registered_tests = SkipSpaces(registered_tests);
09541
09542 Message errors;
09543 ::std::set<std::string> tests;
09544 for (const char* names = registered_tests; names != NULL;
09545 names = SkipComma(names)) {
09546 const std::string name = GetPrefixUntilComma(names);
09547 if (tests.count(name) != 0) {
09548 errors << "Test " << name << " is listed more than once.\n";
09549 continue;
09550 }
09551
09552 bool found = false;
09553 for (DefinedTestIter it = defined_test_names_.begin();
09554 it != defined_test_names_.end();
09555 ++it) {
09556 if (name == *it) {
09557 found = true;
09558 break;
09559 }
09560 }
09561
09562 if (found) {
09563 tests.insert(name);
09564 } else {
09565 errors << "No test named " << name
09566 << " can be found in this test case.\n";
09567 }
09568 }
09569
09570 for (DefinedTestIter it = defined_test_names_.begin();
09571 it != defined_test_names_.end();
09572 ++it) {
09573 if (tests.count(*it) == 0) {
09574 errors << "You forgot to list test " << *it << ".\n";
09575 }
09576 }
09577
09578 const std::string& errors_str = errors.GetString();
09579 if (errors_str != "") {
09580 fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
09581 errors_str.c_str());
09582 fflush(stderr);
09583 posix::Abort();
09584 }
09585
09586 return registered_tests;
09587 }
09588
09589 #endif // GTEST_HAS_TYPED_TEST_P
09590
09591 }
09592 }