Home | History | Annotate | Download | only in src
      1 // Copyright 2005, Google Inc.
      2 // All rights reserved.
      3 //
      4 // Redistribution and use in source and binary forms, with or without
      5 // modification, are permitted provided that the following conditions are
      6 // met:
      7 //
      8 //     * Redistributions of source code must retain the above copyright
      9 // notice, this list of conditions and the following disclaimer.
     10 //     * Redistributions in binary form must reproduce the above
     11 // copyright notice, this list of conditions and the following disclaimer
     12 // in the documentation and/or other materials provided with the
     13 // distribution.
     14 //     * Neither the name of Google Inc. nor the names of its
     15 // contributors may be used to endorse or promote products derived from
     16 // this software without specific prior written permission.
     17 //
     18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
     19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
     20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
     21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
     22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
     23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
     24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
     28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     29 //
     30 // Author: wan (at) google.com (Zhanyong Wan)
     31 //
     32 // The Google C++ Testing Framework (Google Test)
     33 
     34 #include "gtest/gtest.h"
     35 #include "gtest/gtest-spi.h"
     36 
     37 #include <ctype.h>
     38 #include <math.h>
     39 #include <stdarg.h>
     40 #include <stdio.h>
     41 #include <stdlib.h>
     42 #include <time.h>
     43 #include <wchar.h>
     44 #include <wctype.h>
     45 
     46 #include <algorithm>
     47 #include <iomanip>
     48 #include <limits>
     49 #include <ostream>  // NOLINT
     50 #include <sstream>
     51 #include <vector>
     52 
     53 #if GTEST_OS_LINUX
     54 
     55 // TODO(kenton (at) google.com): Use autoconf to detect availability of
     56 // gettimeofday().
     57 # define GTEST_HAS_GETTIMEOFDAY_ 1
     58 
     59 # include <fcntl.h>  // NOLINT
     60 # include <limits.h>  // NOLINT
     61 # include <sched.h>  // NOLINT
     62 // Declares vsnprintf().  This header is not available on Windows.
     63 # include <strings.h>  // NOLINT
     64 # include <sys/mman.h>  // NOLINT
     65 # include <sys/time.h>  // NOLINT
     66 # include <unistd.h>  // NOLINT
     67 # include <string>
     68 
     69 #elif GTEST_OS_SYMBIAN
     70 # define GTEST_HAS_GETTIMEOFDAY_ 1
     71 # include <sys/time.h>  // NOLINT
     72 
     73 #elif GTEST_OS_ZOS
     74 # define GTEST_HAS_GETTIMEOFDAY_ 1
     75 # include <sys/time.h>  // NOLINT
     76 
     77 // On z/OS we additionally need strings.h for strcasecmp.
     78 # include <strings.h>  // NOLINT
     79 
     80 #elif GTEST_OS_WINDOWS_MOBILE  // We are on Windows CE.
     81 
     82 # include <windows.h>  // NOLINT
     83 
     84 #elif GTEST_OS_WINDOWS  // We are on Windows proper.
     85 
     86 # include <io.h>  // NOLINT
     87 # include <sys/timeb.h>  // NOLINT
     88 # include <sys/types.h>  // NOLINT
     89 # include <sys/stat.h>  // NOLINT
     90 
     91 # if GTEST_OS_WINDOWS_MINGW
     92 // MinGW has gettimeofday() but not _ftime64().
     93 // TODO(kenton (at) google.com): Use autoconf to detect availability of
     94 //   gettimeofday().
     95 // TODO(kenton (at) google.com): There are other ways to get the time on
     96 //   Windows, like GetTickCount() or GetSystemTimeAsFileTime().  MinGW
     97 //   supports these.  consider using them instead.
     98 #  define GTEST_HAS_GETTIMEOFDAY_ 1
     99 #  include <sys/time.h>  // NOLINT
    100 # endif  // GTEST_OS_WINDOWS_MINGW
    101 
    102 // cpplint thinks that the header is already included, so we want to
    103 // silence it.
    104 # include <windows.h>  // NOLINT
    105 
    106 #else
    107 
    108 // Assume other platforms have gettimeofday().
    109 // TODO(kenton (at) google.com): Use autoconf to detect availability of
    110 //   gettimeofday().
    111 # define GTEST_HAS_GETTIMEOFDAY_ 1
    112 
    113 // cpplint thinks that the header is already included, so we want to
    114 // silence it.
    115 # include <sys/time.h>  // NOLINT
    116 # include <unistd.h>  // NOLINT
    117 
    118 #endif  // GTEST_OS_LINUX
    119 
    120 #if GTEST_HAS_EXCEPTIONS
    121 # include <stdexcept>
    122 #endif
    123 
    124 #if GTEST_CAN_STREAM_RESULTS_
    125 # include <arpa/inet.h>  // NOLINT
    126 # include <netdb.h>  // NOLINT
    127 #endif
    128 
    129 // Indicates that this translation unit is part of Google Test's
    130 // implementation.  It must come before gtest-internal-inl.h is
    131 // included, or there will be a compiler error.  This trick is to
    132 // prevent a user from accidentally including gtest-internal-inl.h in
    133 // his code.
    134 #define GTEST_IMPLEMENTATION_ 1
    135 #include "src/gtest-internal-inl.h"
    136 #undef GTEST_IMPLEMENTATION_
    137 
    138 #if GTEST_OS_WINDOWS
    139 # define vsnprintf _vsnprintf
    140 #endif  // GTEST_OS_WINDOWS
    141 
    142 namespace testing {
    143 
    144 using internal::CountIf;
    145 using internal::ForEach;
    146 using internal::GetElementOr;
    147 using internal::Shuffle;
    148 
    149 // Constants.
    150 
    151 // A test whose test case name or test name matches this filter is
    152 // disabled and not run.
    153 static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
    154 
    155 // A test case whose name matches this filter is considered a death
    156 // test case and will be run before test cases whose name doesn't
    157 // match this filter.
    158 static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*";
    159 
    160 // A test filter that matches everything.
    161 static const char kUniversalFilter[] = "*";
    162 
    163 // The default output file for XML output.
    164 static const char kDefaultOutputFile[] = "test_detail.xml";
    165 
    166 // The environment variable name for the test shard index.
    167 static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
    168 // The environment variable name for the total number of test shards.
    169 static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
    170 // The environment variable name for the test shard status file.
    171 static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
    172 
    173 namespace internal {
    174 
    175 // The text used in failure messages to indicate the start of the
    176 // stack trace.
    177 const char kStackTraceMarker[] = "\nStack trace:\n";
    178 
    179 // g_help_flag is true iff the --help flag or an equivalent form is
    180 // specified on the command line.
    181 bool g_help_flag = false;
    182 
    183 }  // namespace internal
    184 
    185 GTEST_DEFINE_bool_(
    186     also_run_disabled_tests,
    187     internal::BoolFromGTestEnv("also_run_disabled_tests", false),
    188     "Run disabled tests too, in addition to the tests normally being run.");
    189 
    190 GTEST_DEFINE_bool_(
    191     break_on_failure,
    192     internal::BoolFromGTestEnv("break_on_failure", false),
    193     "True iff a failed assertion should be a debugger break-point.");
    194 
    195 GTEST_DEFINE_bool_(
    196     catch_exceptions,
    197     internal::BoolFromGTestEnv("catch_exceptions", true),
    198     "True iff " GTEST_NAME_
    199     " should catch exceptions and treat them as test failures.");
    200 
    201 GTEST_DEFINE_string_(
    202     color,
    203     internal::StringFromGTestEnv("color", "auto"),
    204     "Whether to use colors in the output.  Valid values: yes, no, "
    205     "and auto.  'auto' means to use colors if the output is "
    206     "being sent to a terminal and the TERM environment variable "
    207     "is set to xterm, xterm-color, xterm-256color, linux or cygwin.");
    208 
    209 GTEST_DEFINE_string_(
    210     filter,
    211     internal::StringFromGTestEnv("filter", kUniversalFilter),
    212     "A colon-separated list of glob (not regex) patterns "
    213     "for filtering the tests to run, optionally followed by a "
    214     "'-' and a : separated list of negative patterns (tests to "
    215     "exclude).  A test is run if it matches one of the positive "
    216     "patterns and does not match any of the negative patterns.");
    217 
    218 GTEST_DEFINE_bool_(list_tests, false,
    219                    "List all tests without running them.");
    220 
    221 GTEST_DEFINE_string_(
    222     output,
    223     internal::StringFromGTestEnv("output", ""),
    224     "A format (currently must be \"xml\"), optionally followed "
    225     "by a colon and an output file name or directory. A directory "
    226     "is indicated by a trailing pathname separator. "
    227     "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
    228     "If a directory is specified, output files will be created "
    229     "within that directory, with file-names based on the test "
    230     "executable's name and, if necessary, made unique by adding "
    231     "digits.");
    232 
    233 GTEST_DEFINE_bool_(
    234     print_time,
    235     internal::BoolFromGTestEnv("print_time", true),
    236     "True iff " GTEST_NAME_
    237     " should display elapsed time in text output.");
    238 
    239 GTEST_DEFINE_int32_(
    240     random_seed,
    241     internal::Int32FromGTestEnv("random_seed", 0),
    242     "Random number seed to use when shuffling test orders.  Must be in range "
    243     "[1, 99999], or 0 to use a seed based on the current time.");
    244 
    245 GTEST_DEFINE_int32_(
    246     repeat,
    247     internal::Int32FromGTestEnv("repeat", 1),
    248     "How many times to repeat each test.  Specify a negative number "
    249     "for repeating forever.  Useful for shaking out flaky tests.");
    250 
    251 GTEST_DEFINE_bool_(
    252     show_internal_stack_frames, false,
    253     "True iff " GTEST_NAME_ " should include internal stack frames when "
    254     "printing test failure stack traces.");
    255 
    256 GTEST_DEFINE_bool_(
    257     shuffle,
    258     internal::BoolFromGTestEnv("shuffle", false),
    259     "True iff " GTEST_NAME_
    260     " should randomize tests' order on every run.");
    261 
    262 GTEST_DEFINE_int32_(
    263     stack_trace_depth,
    264     internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
    265     "The maximum number of stack frames to print when an "
    266     "assertion fails.  The valid range is 0 through 100, inclusive.");
    267 
    268 GTEST_DEFINE_string_(
    269     stream_result_to,
    270     internal::StringFromGTestEnv("stream_result_to", ""),
    271     "This flag specifies the host name and the port number on which to stream "
    272     "test results. Example: \"localhost:555\". The flag is effective only on "
    273     "Linux.");
    274 
    275 GTEST_DEFINE_bool_(
    276     throw_on_failure,
    277     internal::BoolFromGTestEnv("throw_on_failure", false),
    278     "When this flag is specified, a failed assertion will throw an exception "
    279     "if exceptions are enabled or exit the program with a non-zero code "
    280     "otherwise.");
    281 
    282 namespace internal {
    283 
    284 // Generates a random number from [0, range), using a Linear
    285 // Congruential Generator (LCG).  Crashes if 'range' is 0 or greater
    286 // than kMaxRange.
    287 UInt32 Random::Generate(UInt32 range) {
    288   // These constants are the same as are used in glibc's rand(3).
    289   state_ = (1103515245U*state_ + 12345U) % kMaxRange;
    290 
    291   GTEST_CHECK_(range > 0)
    292       << "Cannot generate a number in the range [0, 0).";
    293   GTEST_CHECK_(range <= kMaxRange)
    294       << "Generation of a number in [0, " << range << ") was requested, "
    295       << "but this can only generate numbers in [0, " << kMaxRange << ").";
    296 
    297   // Converting via modulus introduces a bit of downward bias, but
    298   // it's simple, and a linear congruential generator isn't too good
    299   // to begin with.
    300   return state_ % range;
    301 }
    302 
    303 // GTestIsInitialized() returns true iff the user has initialized
    304 // Google Test.  Useful for catching the user mistake of not initializing
    305 // Google Test before calling RUN_ALL_TESTS().
    306 //
    307 // A user must call testing::InitGoogleTest() to initialize Google
    308 // Test.  g_init_gtest_count is set to the number of times
    309 // InitGoogleTest() has been called.  We don't protect this variable
    310 // under a mutex as it is only accessed in the main thread.
    311 GTEST_API_ int g_init_gtest_count = 0;
    312 static bool GTestIsInitialized() { return g_init_gtest_count != 0; }
    313 
    314 // Iterates over a vector of TestCases, keeping a running sum of the
    315 // results of calling a given int-returning method on each.
    316 // Returns the sum.
    317 static int SumOverTestCaseList(const std::vector<TestCase*>& case_list,
    318                                int (TestCase::*method)() const) {
    319   int sum = 0;
    320   for (size_t i = 0; i < case_list.size(); i++) {
    321     sum += (case_list[i]->*method)();
    322   }
    323   return sum;
    324 }
    325 
    326 // Returns true iff the test case passed.
    327 static bool TestCasePassed(const TestCase* test_case) {
    328   return test_case->should_run() && test_case->Passed();
    329 }
    330 
    331 // Returns true iff the test case failed.
    332 static bool TestCaseFailed(const TestCase* test_case) {
    333   return test_case->should_run() && test_case->Failed();
    334 }
    335 
    336 // Returns true iff test_case contains at least one test that should
    337 // run.
    338 static bool ShouldRunTestCase(const TestCase* test_case) {
    339   return test_case->should_run();
    340 }
    341 
    342 // AssertHelper constructor.
    343 AssertHelper::AssertHelper(TestPartResult::Type type,
    344                            const char* file,
    345                            int line,
    346                            const char* message)
    347     : data_(new AssertHelperData(type, file, line, message)) {
    348 }
    349 
    350 AssertHelper::~AssertHelper() {
    351   delete data_;
    352 }
    353 
    354 // Message assignment, for assertion streaming support.
    355 void AssertHelper::operator=(const Message& message) const {
    356   UnitTest::GetInstance()->
    357     AddTestPartResult(data_->type, data_->file, data_->line,
    358                       AppendUserMessage(data_->message, message),
    359                       UnitTest::GetInstance()->impl()
    360                       ->CurrentOsStackTraceExceptTop(1)
    361                       // Skips the stack frame for this function itself.
    362                       );  // NOLINT
    363 }
    364 
    365 // Mutex for linked pointers.
    366 GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex);
    367 
    368 // Application pathname gotten in InitGoogleTest.
    369 std::string g_executable_path;
    370 
    371 // Returns the current application's name, removing directory path if that
    372 // is present.
    373 FilePath GetCurrentExecutableName() {
    374   FilePath result;
    375 
    376 #if GTEST_OS_WINDOWS
    377   result.Set(FilePath(g_executable_path).RemoveExtension("exe"));
    378 #else
    379   result.Set(FilePath(g_executable_path));
    380 #endif  // GTEST_OS_WINDOWS
    381 
    382   return result.RemoveDirectoryName();
    383 }
    384 
    385 // Functions for processing the gtest_output flag.
    386 
    387 // Returns the output format, or "" for normal printed output.
    388 std::string UnitTestOptions::GetOutputFormat() {
    389   const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
    390   if (gtest_output_flag == NULL) return std::string("");
    391 
    392   const char* const colon = strchr(gtest_output_flag, ':');
    393   return (colon == NULL) ?
    394       std::string(gtest_output_flag) :
    395       std::string(gtest_output_flag, colon - gtest_output_flag);
    396 }
    397 
    398 // Returns the name of the requested output file, or the default if none
    399 // was explicitly specified.
    400 std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
    401   const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
    402   if (gtest_output_flag == NULL)
    403     return "";
    404 
    405   const char* const colon = strchr(gtest_output_flag, ':');
    406   if (colon == NULL)
    407     return internal::FilePath::ConcatPaths(
    408         internal::FilePath(
    409             UnitTest::GetInstance()->original_working_dir()),
    410         internal::FilePath(kDefaultOutputFile)).string();
    411 
    412   internal::FilePath output_name(colon + 1);
    413   if (!output_name.IsAbsolutePath())
    414     // TODO(wan (at) google.com): on Windows \some\path is not an absolute
    415     // path (as its meaning depends on the current drive), yet the
    416     // following logic for turning it into an absolute path is wrong.
    417     // Fix it.
    418     output_name = internal::FilePath::ConcatPaths(
    419         internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
    420         internal::FilePath(colon + 1));
    421 
    422   if (!output_name.IsDirectory())
    423     return output_name.string();
    424 
    425   internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
    426       output_name, internal::GetCurrentExecutableName(),
    427       GetOutputFormat().c_str()));
    428   return result.string();
    429 }
    430 
    431 // Returns true iff the wildcard pattern matches the string.  The
    432 // first ':' or '\0' character in pattern marks the end of it.
    433 //
    434 // This recursive algorithm isn't very efficient, but is clear and
    435 // works well enough for matching test names, which are short.
    436 bool UnitTestOptions::PatternMatchesString(const char *pattern,
    437                                            const char *str) {
    438   switch (*pattern) {
    439     case '\0':
    440     case ':':  // Either ':' or '\0' marks the end of the pattern.
    441       return *str == '\0';
    442     case '?':  // Matches any single character.
    443       return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);
    444     case '*':  // Matches any string (possibly empty) of characters.
    445       return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||
    446           PatternMatchesString(pattern + 1, str);
    447     default:  // Non-special character.  Matches itself.
    448       return *pattern == *str &&
    449           PatternMatchesString(pattern + 1, str + 1);
    450   }
    451 }
    452 
    453 bool UnitTestOptions::MatchesFilter(
    454     const std::string& name, const char* filter) {
    455   const char *cur_pattern = filter;
    456   for (;;) {
    457     if (PatternMatchesString(cur_pattern, name.c_str())) {
    458       return true;
    459     }
    460 
    461     // Finds the next pattern in the filter.
    462     cur_pattern = strchr(cur_pattern, ':');
    463 
    464     // Returns if no more pattern can be found.
    465     if (cur_pattern == NULL) {
    466       return false;
    467     }
    468 
    469     // Skips the pattern separater (the ':' character).
    470     cur_pattern++;
    471   }
    472 }
    473 
    474 // Returns true iff the user-specified filter matches the test case
    475 // name and the test name.
    476 bool UnitTestOptions::FilterMatchesTest(const std::string &test_case_name,
    477                                         const std::string &test_name) {
    478   const std::string& full_name = test_case_name + "." + test_name.c_str();
    479 
    480   // Split --gtest_filter at '-', if there is one, to separate into
    481   // positive filter and negative filter portions
    482   const char* const p = GTEST_FLAG(filter).c_str();
    483   const char* const dash = strchr(p, '-');
    484   std::string positive;
    485   std::string negative;
    486   if (dash == NULL) {
    487     positive = GTEST_FLAG(filter).c_str();  // Whole string is a positive filter
    488     negative = "";
    489   } else {
    490     positive = std::string(p, dash);   // Everything up to the dash
    491     negative = std::string(dash + 1);  // Everything after the dash
    492     if (positive.empty()) {
    493       // Treat '-test1' as the same as '*-test1'
    494       positive = kUniversalFilter;
    495     }
    496   }
    497 
    498   // A filter is a colon-separated list of patterns.  It matches a
    499   // test if any pattern in it matches the test.
    500   return (MatchesFilter(full_name, positive.c_str()) &&
    501           !MatchesFilter(full_name, negative.c_str()));
    502 }
    503 
    504 #if GTEST_HAS_SEH
    505 // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
    506 // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
    507 // This function is useful as an __except condition.
    508 int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
    509   // Google Test should handle a SEH exception if:
    510   //   1. the user wants it to, AND
    511   //   2. this is not a breakpoint exception, AND
    512   //   3. this is not a C++ exception (VC++ implements them via SEH,
    513   //      apparently).
    514   //
    515   // SEH exception code for C++ exceptions.
    516   // (see http://support.microsoft.com/kb/185294 for more information).
    517   const DWORD kCxxExceptionCode = 0xe06d7363;
    518 
    519   bool should_handle = true;
    520 
    521   if (!GTEST_FLAG(catch_exceptions))
    522     should_handle = false;
    523   else if (exception_code == EXCEPTION_BREAKPOINT)
    524     should_handle = false;
    525   else if (exception_code == kCxxExceptionCode)
    526     should_handle = false;
    527 
    528   return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
    529 }
    530 #endif  // GTEST_HAS_SEH
    531 
    532 }  // namespace internal
    533 
    534 // The c'tor sets this object as the test part result reporter used by
    535 // Google Test.  The 'result' parameter specifies where to report the
    536 // results. Intercepts only failures from the current thread.
    537 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
    538     TestPartResultArray* result)
    539     : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
    540       result_(result) {
    541   Init();
    542 }
    543 
    544 // The c'tor sets this object as the test part result reporter used by
    545 // Google Test.  The 'result' parameter specifies where to report the
    546 // results.
    547 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
    548     InterceptMode intercept_mode, TestPartResultArray* result)
    549     : intercept_mode_(intercept_mode),
    550       result_(result) {
    551   Init();
    552 }
    553 
    554 void ScopedFakeTestPartResultReporter::Init() {
    555   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
    556   if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
    557     old_reporter_ = impl->GetGlobalTestPartResultReporter();
    558     impl->SetGlobalTestPartResultReporter(this);
    559   } else {
    560     old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
    561     impl->SetTestPartResultReporterForCurrentThread(this);
    562   }
    563 }
    564 
    565 // The d'tor restores the test part result reporter used by Google Test
    566 // before.
    567 ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
    568   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
    569   if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
    570     impl->SetGlobalTestPartResultReporter(old_reporter_);
    571   } else {
    572     impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
    573   }
    574 }
    575 
    576 // Increments the test part result count and remembers the result.
    577 // This method is from the TestPartResultReporterInterface interface.
    578 void ScopedFakeTestPartResultReporter::ReportTestPartResult(
    579     const TestPartResult& result) {
    580   result_->Append(result);
    581 }
    582 
    583 namespace internal {
    584 
    585 // Returns the type ID of ::testing::Test.  We should always call this
    586 // instead of GetTypeId< ::testing::Test>() to get the type ID of
    587 // testing::Test.  This is to work around a suspected linker bug when
    588 // using Google Test as a framework on Mac OS X.  The bug causes
    589 // GetTypeId< ::testing::Test>() to return different values depending
    590 // on whether the call is from the Google Test framework itself or
    591 // from user test code.  GetTestTypeId() is guaranteed to always
    592 // return the same value, as it always calls GetTypeId<>() from the
    593 // gtest.cc, which is within the Google Test framework.
    594 TypeId GetTestTypeId() {
    595   return GetTypeId<Test>();
    596 }
    597 
    598 // The value of GetTestTypeId() as seen from within the Google Test
    599 // library.  This is solely for testing GetTestTypeId().
    600 extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
    601 
    602 // This predicate-formatter checks that 'results' contains a test part
    603 // failure of the given type and that the failure message contains the
    604 // given substring.
    605 AssertionResult HasOneFailure(const char* /* results_expr */,
    606                               const char* /* type_expr */,
    607                               const char* /* substr_expr */,
    608                               const TestPartResultArray& results,
    609                               TestPartResult::Type type,
    610                               const string& substr) {
    611   const std::string expected(type == TestPartResult::kFatalFailure ?
    612                         "1 fatal failure" :
    613                         "1 non-fatal failure");
    614   Message msg;
    615   if (results.size() != 1) {
    616     msg << "Expected: " << expected << "\n"
    617         << "  Actual: " << results.size() << " failures";
    618     for (int i = 0; i < results.size(); i++) {
    619       msg << "\n" << results.GetTestPartResult(i);
    620     }
    621     return AssertionFailure() << msg;
    622   }
    623 
    624   const TestPartResult& r = results.GetTestPartResult(0);
    625   if (r.type() != type) {
    626     return AssertionFailure() << "Expected: " << expected << "\n"
    627                               << "  Actual:\n"
    628                               << r;
    629   }
    630 
    631   if (strstr(r.message(), substr.c_str()) == NULL) {
    632     return AssertionFailure() << "Expected: " << expected << " containing \""
    633                               << substr << "\"\n"
    634                               << "  Actual:\n"
    635                               << r;
    636   }
    637 
    638   return AssertionSuccess();
    639 }
    640 
    641 // The constructor of SingleFailureChecker remembers where to look up
    642 // test part results, what type of failure we expect, and what
    643 // substring the failure message should contain.
    644 SingleFailureChecker:: SingleFailureChecker(
    645     const TestPartResultArray* results,
    646     TestPartResult::Type type,
    647     const string& substr)
    648     : results_(results),
    649       type_(type),
    650       substr_(substr) {}
    651 
    652 // The destructor of SingleFailureChecker verifies that the given
    653 // TestPartResultArray contains exactly one failure that has the given
    654 // type and contains the given substring.  If that's not the case, a
    655 // non-fatal failure will be generated.
    656 SingleFailureChecker::~SingleFailureChecker() {
    657   EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_);
    658 }
    659 
    660 DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
    661     UnitTestImpl* unit_test) : unit_test_(unit_test) {}
    662 
    663 void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
    664     const TestPartResult& result) {
    665   unit_test_->current_test_result()->AddTestPartResult(result);
    666   unit_test_->listeners()->repeater()->OnTestPartResult(result);
    667 }
    668 
    669 DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
    670     UnitTestImpl* unit_test) : unit_test_(unit_test) {}
    671 
    672 void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
    673     const TestPartResult& result) {
    674   unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
    675 }
    676 
    677 // Returns the global test part result reporter.
    678 TestPartResultReporterInterface*
    679 UnitTestImpl::GetGlobalTestPartResultReporter() {
    680   internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
    681   return global_test_part_result_repoter_;
    682 }
    683 
    684 // Sets the global test part result reporter.
    685 void UnitTestImpl::SetGlobalTestPartResultReporter(
    686     TestPartResultReporterInterface* reporter) {
    687   internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
    688   global_test_part_result_repoter_ = reporter;
    689 }
    690 
    691 // Returns the test part result reporter for the current thread.
    692 TestPartResultReporterInterface*
    693 UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
    694   return per_thread_test_part_result_reporter_.get();
    695 }
    696 
    697 // Sets the test part result reporter for the current thread.
    698 void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
    699     TestPartResultReporterInterface* reporter) {
    700   per_thread_test_part_result_reporter_.set(reporter);
    701 }
    702 
    703 // Gets the number of successful test cases.
    704 int UnitTestImpl::successful_test_case_count() const {
    705   return CountIf(test_cases_, TestCasePassed);
    706 }
    707 
    708 // Gets the number of failed test cases.
    709 int UnitTestImpl::failed_test_case_count() const {
    710   return CountIf(test_cases_, TestCaseFailed);
    711 }
    712 
    713 // Gets the number of all test cases.
    714 int UnitTestImpl::total_test_case_count() const {
    715   return static_cast<int>(test_cases_.size());
    716 }
    717 
    718 // Gets the number of all test cases that contain at least one test
    719 // that should run.
    720 int UnitTestImpl::test_case_to_run_count() const {
    721   return CountIf(test_cases_, ShouldRunTestCase);
    722 }
    723 
    724 // Gets the number of successful tests.
    725 int UnitTestImpl::successful_test_count() const {
    726   return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count);
    727 }
    728 
    729 // Gets the number of failed tests.
    730 int UnitTestImpl::failed_test_count() const {
    731   return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count);
    732 }
    733 
    734 // Gets the number of disabled tests.
    735 int UnitTestImpl::disabled_test_count() const {
    736   return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count);
    737 }
    738 
    739 // Gets the number of all tests.
    740 int UnitTestImpl::total_test_count() const {
    741   return SumOverTestCaseList(test_cases_, &TestCase::total_test_count);
    742 }
    743 
    744 // Gets the number of tests that should run.
    745 int UnitTestImpl::test_to_run_count() const {
    746   return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count);
    747 }
    748 
    749 // Returns the current OS stack trace as an std::string.
    750 //
    751 // The maximum number of stack frames to be included is specified by
    752 // the gtest_stack_trace_depth flag.  The skip_count parameter
    753 // specifies the number of top frames to be skipped, which doesn't
    754 // count against the number of frames to be included.
    755 //
    756 // For example, if Foo() calls Bar(), which in turn calls
    757 // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
    758 // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
    759 std::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
    760   (void)skip_count;
    761   return "";
    762 }
    763 
    764 // Returns the current time in milliseconds.
    765 TimeInMillis GetTimeInMillis() {
    766 #if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__)
    767   // Difference between 1970-01-01 and 1601-01-01 in milliseconds.
    768   // http://analogous.blogspot.com/2005/04/epoch.html
    769   const TimeInMillis kJavaEpochToWinFileTimeDelta =
    770     static_cast<TimeInMillis>(116444736UL) * 100000UL;
    771   const DWORD kTenthMicrosInMilliSecond = 10000;
    772 
    773   SYSTEMTIME now_systime;
    774   FILETIME now_filetime;
    775   ULARGE_INTEGER now_int64;
    776   // TODO(kenton (at) google.com): Shouldn't this just use
    777   //   GetSystemTimeAsFileTime()?
    778   GetSystemTime(&now_systime);
    779   if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
    780     now_int64.LowPart = now_filetime.dwLowDateTime;
    781     now_int64.HighPart = now_filetime.dwHighDateTime;
    782     now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
    783       kJavaEpochToWinFileTimeDelta;
    784     return now_int64.QuadPart;
    785   }
    786   return 0;
    787 #elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_
    788   __timeb64 now;
    789 
    790 # ifdef _MSC_VER
    791 
    792   // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996
    793   // (deprecated function) there.
    794   // TODO(kenton (at) google.com): Use GetTickCount()?  Or use
    795   //   SystemTimeToFileTime()
    796 #  pragma warning(push)          // Saves the current warning state.
    797 #  pragma warning(disable:4996)  // Temporarily disables warning 4996.
    798   _ftime64(&now);
    799 #  pragma warning(pop)           // Restores the warning state.
    800 # else
    801 
    802   _ftime64(&now);
    803 
    804 # endif  // _MSC_VER
    805 
    806   return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
    807 #elif GTEST_HAS_GETTIMEOFDAY_
    808   struct timeval now;
    809   gettimeofday(&now, NULL);
    810   return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
    811 #else
    812 # error "Don't know how to get the current time on your system."
    813 #endif
    814 }
    815 
    816 // Utilities
    817 
    818 // class String.
    819 
    820 #if GTEST_OS_WINDOWS_MOBILE
    821 // Creates a UTF-16 wide string from the given ANSI string, allocating
    822 // memory using new. The caller is responsible for deleting the return
    823 // value using delete[]. Returns the wide string, or NULL if the
    824 // input is NULL.
    825 LPCWSTR String::AnsiToUtf16(const char* ansi) {
    826   if (!ansi) return NULL;
    827   const int length = strlen(ansi);
    828   const int unicode_length =
    829       MultiByteToWideChar(CP_ACP, 0, ansi, length,
    830                           NULL, 0);
    831   WCHAR* unicode = new WCHAR[unicode_length + 1];
    832   MultiByteToWideChar(CP_ACP, 0, ansi, length,
    833                       unicode, unicode_length);
    834   unicode[unicode_length] = 0;
    835   return unicode;
    836 }
    837 
    838 // Creates an ANSI string from the given wide string, allocating
    839 // memory using new. The caller is responsible for deleting the return
    840 // value using delete[]. Returns the ANSI string, or NULL if the
    841 // input is NULL.
    842 const char* String::Utf16ToAnsi(LPCWSTR utf16_str)  {
    843   if (!utf16_str) return NULL;
    844   const int ansi_length =
    845       WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
    846                           NULL, 0, NULL, NULL);
    847   char* ansi = new char[ansi_length + 1];
    848   WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
    849                       ansi, ansi_length, NULL, NULL);
    850   ansi[ansi_length] = 0;
    851   return ansi;
    852 }
    853 
    854 #endif  // GTEST_OS_WINDOWS_MOBILE
    855 
    856 // Compares two C strings.  Returns true iff they have the same content.
    857 //
    858 // Unlike strcmp(), this function can handle NULL argument(s).  A NULL
    859 // C string is considered different to any non-NULL C string,
    860 // including the empty string.
    861 bool String::CStringEquals(const char * lhs, const char * rhs) {
    862   if ( lhs == NULL ) return rhs == NULL;
    863 
    864   if ( rhs == NULL ) return false;
    865 
    866   return strcmp(lhs, rhs) == 0;
    867 }
    868 
    869 #if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
    870 
    871 // Converts an array of wide chars to a narrow string using the UTF-8
    872 // encoding, and streams the result to the given Message object.
    873 static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
    874                                      Message* msg) {
    875   for (size_t i = 0; i != length; ) {  // NOLINT
    876     if (wstr[i] != L'\0') {
    877       *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
    878       while (i != length && wstr[i] != L'\0')
    879         i++;
    880     } else {
    881       *msg << '\0';
    882       i++;
    883     }
    884   }
    885 }
    886 
    887 #endif  // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
    888 
    889 }  // namespace internal
    890 
    891 // Constructs an empty Message.
    892 // We allocate the stringstream separately because otherwise each use of
    893 // ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's
    894 // stack frame leading to huge stack frames in some cases; gcc does not reuse
    895 // the stack space.
    896 Message::Message() : ss_(new ::std::stringstream) {
    897   // By default, we want there to be enough precision when printing
    898   // a double to a Message.
    899   *ss_ << std::setprecision(std::numeric_limits<double>::digits10 + 2);
    900 }
    901 
    902 // These two overloads allow streaming a wide C string to a Message
    903 // using the UTF-8 encoding.
    904 Message& Message::operator <<(const wchar_t* wide_c_str) {
    905   return *this << internal::String::ShowWideCString(wide_c_str);
    906 }
    907 Message& Message::operator <<(wchar_t* wide_c_str) {
    908   return *this << internal::String::ShowWideCString(wide_c_str);
    909 }
    910 
    911 #if GTEST_HAS_STD_WSTRING
    912 // Converts the given wide string to a narrow string using the UTF-8
    913 // encoding, and streams the result to this Message object.
    914 Message& Message::operator <<(const ::std::wstring& wstr) {
    915   internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
    916   return *this;
    917 }
    918 #endif  // GTEST_HAS_STD_WSTRING
    919 
    920 #if GTEST_HAS_GLOBAL_WSTRING
    921 // Converts the given wide string to a narrow string using the UTF-8
    922 // encoding, and streams the result to this Message object.
    923 Message& Message::operator <<(const ::wstring& wstr) {
    924   internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
    925   return *this;
    926 }
    927 #endif  // GTEST_HAS_GLOBAL_WSTRING
    928 
    929 // Gets the text streamed to this object so far as an std::string.
    930 // Each '\0' character in the buffer is replaced with "\\0".
    931 std::string Message::GetString() const {
    932   return internal::StringStreamToString(ss_.get());
    933 }
    934 
    935 // AssertionResult constructors.
    936 // Used in EXPECT_TRUE/FALSE(assertion_result).
    937 AssertionResult::AssertionResult(const AssertionResult& other)
    938     : success_(other.success_),
    939       message_(other.message_.get() != NULL ?
    940                new ::std::string(*other.message_) :
    941                static_cast< ::std::string*>(NULL)) {
    942 }
    943 
    944 // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
    945 AssertionResult AssertionResult::operator!() const {
    946   AssertionResult negation(!success_);
    947   if (message_.get() != NULL)
    948     negation << *message_;
    949   return negation;
    950 }
    951 
    952 // Makes a successful assertion result.
    953 AssertionResult AssertionSuccess() {
    954   return AssertionResult(true);
    955 }
    956 
    957 // Makes a failed assertion result.
    958 AssertionResult AssertionFailure() {
    959   return AssertionResult(false);
    960 }
    961 
    962 // Makes a failed assertion result with the given failure message.
    963 // Deprecated; use AssertionFailure() << message.
    964 AssertionResult AssertionFailure(const Message& message) {
    965   return AssertionFailure() << message;
    966 }
    967 
    968 namespace internal {
    969 
    970 // Constructs and returns the message for an equality assertion
    971 // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
    972 //
    973 // The first four parameters are the expressions used in the assertion
    974 // and their values, as strings.  For example, for ASSERT_EQ(foo, bar)
    975 // where foo is 5 and bar is 6, we have:
    976 //
    977 //   expected_expression: "foo"
    978 //   actual_expression:   "bar"
    979 //   expected_value:      "5"
    980 //   actual_value:        "6"
    981 //
    982 // The ignoring_case parameter is true iff the assertion is a
    983 // *_STRCASEEQ*.  When it's true, the string " (ignoring case)" will
    984 // be inserted into the message.
    985 AssertionResult EqFailure(const char* expected_expression,
    986                           const char* actual_expression,
    987                           const std::string& expected_value,
    988                           const std::string& actual_value,
    989                           bool ignoring_case) {
    990   Message msg;
    991   msg << "Value of: " << actual_expression;
    992   if (actual_value != actual_expression) {
    993     msg << "\n  Actual: " << actual_value;
    994   }
    995 
    996   msg << "\nExpected: " << expected_expression;
    997   if (ignoring_case) {
    998     msg << " (ignoring case)";
    999   }
   1000   if (expected_value != expected_expression) {
   1001     msg << "\nWhich is: " << expected_value;
   1002   }
   1003 
   1004   return AssertionFailure() << msg;
   1005 }
   1006 
   1007 // Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
   1008 std::string GetBoolAssertionFailureMessage(
   1009     const AssertionResult& assertion_result,
   1010     const char* expression_text,
   1011     const char* actual_predicate_value,
   1012     const char* expected_predicate_value) {
   1013   const char* actual_message = assertion_result.message();
   1014   Message msg;
   1015   msg << "Value of: " << expression_text
   1016       << "\n  Actual: " << actual_predicate_value;
   1017   if (actual_message[0] != '\0')
   1018     msg << " (" << actual_message << ")";
   1019   msg << "\nExpected: " << expected_predicate_value;
   1020   return msg.GetString();
   1021 }
   1022 
   1023 // Helper function for implementing ASSERT_NEAR.
   1024 AssertionResult DoubleNearPredFormat(const char* expr1,
   1025                                      const char* expr2,
   1026                                      const char* abs_error_expr,
   1027                                      double val1,
   1028                                      double val2,
   1029                                      double abs_error) {
   1030   const double diff = fabs(val1 - val2);
   1031   if (diff <= abs_error) return AssertionSuccess();
   1032 
   1033   // TODO(wan): do not print the value of an expression if it's
   1034   // already a literal.
   1035   return AssertionFailure()
   1036       << "The difference between " << expr1 << " and " << expr2
   1037       << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"
   1038       << expr1 << " evaluates to " << val1 << ",\n"
   1039       << expr2 << " evaluates to " << val2 << ", and\n"
   1040       << abs_error_expr << " evaluates to " << abs_error << ".";
   1041 }
   1042 
   1043 
   1044 // Helper template for implementing FloatLE() and DoubleLE().
   1045 template <typename RawType>
   1046 AssertionResult FloatingPointLE(const char* expr1,
   1047                                 const char* expr2,
   1048                                 RawType val1,
   1049                                 RawType val2) {
   1050   // Returns success if val1 is less than val2,
   1051   if (val1 < val2) {
   1052     return AssertionSuccess();
   1053   }
   1054 
   1055   // or if val1 is almost equal to val2.
   1056   const FloatingPoint<RawType> lhs(val1), rhs(val2);
   1057   if (lhs.AlmostEquals(rhs)) {
   1058     return AssertionSuccess();
   1059   }
   1060 
   1061   // Note that the above two checks will both fail if either val1 or
   1062   // val2 is NaN, as the IEEE floating-point standard requires that
   1063   // any predicate involving a NaN must return false.
   1064 
   1065   ::std::stringstream val1_ss;
   1066   val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
   1067           << val1;
   1068 
   1069   ::std::stringstream val2_ss;
   1070   val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
   1071           << val2;
   1072 
   1073   return AssertionFailure()
   1074       << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
   1075       << "  Actual: " << StringStreamToString(&val1_ss) << " vs "
   1076       << StringStreamToString(&val2_ss);
   1077 }
   1078 
   1079 }  // namespace internal
   1080 
   1081 // Asserts that val1 is less than, or almost equal to, val2.  Fails
   1082 // otherwise.  In particular, it fails if either val1 or val2 is NaN.
   1083 AssertionResult FloatLE(const char* expr1, const char* expr2,
   1084                         float val1, float val2) {
   1085   return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
   1086 }
   1087 
   1088 // Asserts that val1 is less than, or almost equal to, val2.  Fails
   1089 // otherwise.  In particular, it fails if either val1 or val2 is NaN.
   1090 AssertionResult DoubleLE(const char* expr1, const char* expr2,
   1091                          double val1, double val2) {
   1092   return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
   1093 }
   1094 
   1095 namespace internal {
   1096 
   1097 // The helper function for {ASSERT|EXPECT}_EQ with int or enum
   1098 // arguments.
   1099 AssertionResult CmpHelperEQ(const char* expected_expression,
   1100                             const char* actual_expression,
   1101                             BiggestInt expected,
   1102                             BiggestInt actual) {
   1103   if (expected == actual) {
   1104     return AssertionSuccess();
   1105   }
   1106 
   1107   return EqFailure(expected_expression,
   1108                    actual_expression,
   1109                    FormatForComparisonFailureMessage(expected, actual),
   1110                    FormatForComparisonFailureMessage(actual, expected),
   1111                    false);
   1112 }
   1113 
   1114 // A macro for implementing the helper functions needed to implement
   1115 // ASSERT_?? and EXPECT_?? with integer or enum arguments.  It is here
   1116 // just to avoid copy-and-paste of similar code.
   1117 #define GTEST_IMPL_CMP_HELPER_(op_name, op)\
   1118 AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
   1119                                    BiggestInt val1, BiggestInt val2) {\
   1120   if (val1 op val2) {\
   1121     return AssertionSuccess();\
   1122   } else {\
   1123     return AssertionFailure() \
   1124         << "Expected: (" << expr1 << ") " #op " (" << expr2\
   1125         << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
   1126         << " vs " << FormatForComparisonFailureMessage(val2, val1);\
   1127   }\
   1128 }
   1129 
   1130 // Implements the helper function for {ASSERT|EXPECT}_NE with int or
   1131 // enum arguments.
   1132 GTEST_IMPL_CMP_HELPER_(NE, !=)
   1133 // Implements the helper function for {ASSERT|EXPECT}_LE with int or
   1134 // enum arguments.
   1135 GTEST_IMPL_CMP_HELPER_(LE, <=)
   1136 // Implements the helper function for {ASSERT|EXPECT}_LT with int or
   1137 // enum arguments.
   1138 GTEST_IMPL_CMP_HELPER_(LT, < )
   1139 // Implements the helper function for {ASSERT|EXPECT}_GE with int or
   1140 // enum arguments.
   1141 GTEST_IMPL_CMP_HELPER_(GE, >=)
   1142 // Implements the helper function for {ASSERT|EXPECT}_GT with int or
   1143 // enum arguments.
   1144 GTEST_IMPL_CMP_HELPER_(GT, > )
   1145 
   1146 #undef GTEST_IMPL_CMP_HELPER_
   1147 
   1148 // The helper function for {ASSERT|EXPECT}_STREQ.
   1149 AssertionResult CmpHelperSTREQ(const char* expected_expression,
   1150                                const char* actual_expression,
   1151                                const char* expected,
   1152                                const char* actual) {
   1153   if (String::CStringEquals(expected, actual)) {
   1154     return AssertionSuccess();
   1155   }
   1156 
   1157   return EqFailure(expected_expression,
   1158                    actual_expression,
   1159                    PrintToString(expected),
   1160                    PrintToString(actual),
   1161                    false);
   1162 }
   1163 
   1164 // The helper function for {ASSERT|EXPECT}_STRCASEEQ.
   1165 AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression,
   1166                                    const char* actual_expression,
   1167                                    const char* expected,
   1168                                    const char* actual) {
   1169   if (String::CaseInsensitiveCStringEquals(expected, actual)) {
   1170     return AssertionSuccess();
   1171   }
   1172 
   1173   return EqFailure(expected_expression,
   1174                    actual_expression,
   1175                    PrintToString(expected),
   1176                    PrintToString(actual),
   1177                    true);
   1178 }
   1179 
   1180 // The helper function for {ASSERT|EXPECT}_STRNE.
   1181 AssertionResult CmpHelperSTRNE(const char* s1_expression,
   1182                                const char* s2_expression,
   1183                                const char* s1,
   1184                                const char* s2) {
   1185   if (!String::CStringEquals(s1, s2)) {
   1186     return AssertionSuccess();
   1187   } else {
   1188     return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
   1189                               << s2_expression << "), actual: \""
   1190                               << s1 << "\" vs \"" << s2 << "\"";
   1191   }
   1192 }
   1193 
   1194 // The helper function for {ASSERT|EXPECT}_STRCASENE.
   1195 AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
   1196                                    const char* s2_expression,
   1197                                    const char* s1,
   1198                                    const char* s2) {
   1199   if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
   1200     return AssertionSuccess();
   1201   } else {
   1202     return AssertionFailure()
   1203         << "Expected: (" << s1_expression << ") != ("
   1204         << s2_expression << ") (ignoring case), actual: \""
   1205         << s1 << "\" vs \"" << s2 << "\"";
   1206   }
   1207 }
   1208 
   1209 }  // namespace internal
   1210 
   1211 namespace {
   1212 
   1213 // Helper functions for implementing IsSubString() and IsNotSubstring().
   1214 
   1215 // This group of overloaded functions return true iff needle is a
   1216 // substring of haystack.  NULL is considered a substring of itself
   1217 // only.
   1218 
   1219 bool IsSubstringPred(const char* needle, const char* haystack) {
   1220   if (needle == NULL || haystack == NULL)
   1221     return needle == haystack;
   1222 
   1223   return strstr(haystack, needle) != NULL;
   1224 }
   1225 
   1226 bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
   1227   if (needle == NULL || haystack == NULL)
   1228     return needle == haystack;
   1229 
   1230   return wcsstr(haystack, needle) != NULL;
   1231 }
   1232 
   1233 // StringType here can be either ::std::string or ::std::wstring.
   1234 template <typename StringType>
   1235 bool IsSubstringPred(const StringType& needle,
   1236                      const StringType& haystack) {
   1237   return haystack.find(needle) != StringType::npos;
   1238 }
   1239 
   1240 // This function implements either IsSubstring() or IsNotSubstring(),
   1241 // depending on the value of the expected_to_be_substring parameter.
   1242 // StringType here can be const char*, const wchar_t*, ::std::string,
   1243 // or ::std::wstring.
   1244 template <typename StringType>
   1245 AssertionResult IsSubstringImpl(
   1246     bool expected_to_be_substring,
   1247     const char* needle_expr, const char* haystack_expr,
   1248     const StringType& needle, const StringType& haystack) {
   1249   if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
   1250     return AssertionSuccess();
   1251 
   1252   const bool is_wide_string = sizeof(needle[0]) > 1;
   1253   const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
   1254   return AssertionFailure()
   1255       << "Value of: " << needle_expr << "\n"
   1256       << "  Actual: " << begin_string_quote << needle << "\"\n"
   1257       << "Expected: " << (expected_to_be_substring ? "" : "not ")
   1258       << "a substring of " << haystack_expr << "\n"
   1259       << "Which is: " << begin_string_quote << haystack << "\"";
   1260 }
   1261 
   1262 }  // namespace
   1263 
   1264 // IsSubstring() and IsNotSubstring() check whether needle is a
   1265 // substring of haystack (NULL is considered a substring of itself
   1266 // only), and return an appropriate error message when they fail.
   1267 
   1268 AssertionResult IsSubstring(
   1269     const char* needle_expr, const char* haystack_expr,
   1270     const char* needle, const char* haystack) {
   1271   return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
   1272 }
   1273 
   1274 AssertionResult IsSubstring(
   1275     const char* needle_expr, const char* haystack_expr,
   1276     const wchar_t* needle, const wchar_t* haystack) {
   1277   return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
   1278 }
   1279 
   1280 AssertionResult IsNotSubstring(
   1281     const char* needle_expr, const char* haystack_expr,
   1282     const char* needle, const char* haystack) {
   1283   return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
   1284 }
   1285 
   1286 AssertionResult IsNotSubstring(
   1287     const char* needle_expr, const char* haystack_expr,
   1288     const wchar_t* needle, const wchar_t* haystack) {
   1289   return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
   1290 }
   1291 
   1292 AssertionResult IsSubstring(
   1293     const char* needle_expr, const char* haystack_expr,
   1294     const ::std::string& needle, const ::std::string& haystack) {
   1295   return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
   1296 }
   1297 
   1298 AssertionResult IsNotSubstring(
   1299     const char* needle_expr, const char* haystack_expr,
   1300     const ::std::string& needle, const ::std::string& haystack) {
   1301   return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
   1302 }
   1303 
   1304 #if GTEST_HAS_STD_WSTRING
   1305 AssertionResult IsSubstring(
   1306     const char* needle_expr, const char* haystack_expr,
   1307     const ::std::wstring& needle, const ::std::wstring& haystack) {
   1308   return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
   1309 }
   1310 
   1311 AssertionResult IsNotSubstring(
   1312     const char* needle_expr, const char* haystack_expr,
   1313     const ::std::wstring& needle, const ::std::wstring& haystack) {
   1314   return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
   1315 }
   1316 #endif  // GTEST_HAS_STD_WSTRING
   1317 
   1318 namespace internal {
   1319 
   1320 #if GTEST_OS_WINDOWS
   1321 
   1322 namespace {
   1323 
   1324 // Helper function for IsHRESULT{SuccessFailure} predicates
   1325 AssertionResult HRESULTFailureHelper(const char* expr,
   1326                                      const char* expected,
   1327                                      long hr) {  // NOLINT
   1328 # if GTEST_OS_WINDOWS_MOBILE
   1329 
   1330   // Windows CE doesn't support FormatMessage.
   1331   const char error_text[] = "";
   1332 
   1333 # else
   1334 
   1335   // Looks up the human-readable system message for the HRESULT code
   1336   // and since we're not passing any params to FormatMessage, we don't
   1337   // want inserts expanded.
   1338   const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
   1339                        FORMAT_MESSAGE_IGNORE_INSERTS;
   1340   const DWORD kBufSize = 4096;
   1341   // Gets the system's human readable message string for this HRESULT.
   1342   char error_text[kBufSize] = { '\0' };
   1343   DWORD message_length = ::FormatMessageA(kFlags,
   1344                                           0,  // no source, we're asking system
   1345                                           hr,  // the error
   1346                                           0,  // no line width restrictions
   1347                                           error_text,  // output buffer
   1348                                           kBufSize,  // buf size
   1349                                           NULL);  // no arguments for inserts
   1350   // Trims tailing white space (FormatMessage leaves a trailing CR-LF)
   1351   for (; message_length && IsSpace(error_text[message_length - 1]);
   1352           --message_length) {
   1353     error_text[message_length - 1] = '\0';
   1354   }
   1355 
   1356 # endif  // GTEST_OS_WINDOWS_MOBILE
   1357 
   1358   const std::string error_hex("0x" + String::FormatHexInt(hr));
   1359   return ::testing::AssertionFailure()
   1360       << "Expected: " << expr << " " << expected << ".\n"
   1361       << "  Actual: " << error_hex << " " << error_text << "\n";
   1362 }
   1363 
   1364 }  // namespace
   1365 
   1366 AssertionResult IsHRESULTSuccess(const char* expr, long hr) {  // NOLINT
   1367   if (SUCCEEDED(hr)) {
   1368     return AssertionSuccess();
   1369   }
   1370   return HRESULTFailureHelper(expr, "succeeds", hr);
   1371 }
   1372 
   1373 AssertionResult IsHRESULTFailure(const char* expr, long hr) {  // NOLINT
   1374   if (FAILED(hr)) {
   1375     return AssertionSuccess();
   1376   }
   1377   return HRESULTFailureHelper(expr, "fails", hr);
   1378 }
   1379 
   1380 #endif  // GTEST_OS_WINDOWS
   1381 
   1382 // Utility functions for encoding Unicode text (wide strings) in
   1383 // UTF-8.
   1384 
   1385 // A Unicode code-point can have upto 21 bits, and is encoded in UTF-8
   1386 // like this:
   1387 //
   1388 // Code-point length   Encoding
   1389 //   0 -  7 bits       0xxxxxxx
   1390 //   8 - 11 bits       110xxxxx 10xxxxxx
   1391 //  12 - 16 bits       1110xxxx 10xxxxxx 10xxxxxx
   1392 //  17 - 21 bits       11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
   1393 
   1394 // The maximum code-point a one-byte UTF-8 sequence can represent.
   1395 const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) <<  7) - 1;
   1396 
   1397 // The maximum code-point a two-byte UTF-8 sequence can represent.
   1398 const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1;
   1399 
   1400 // The maximum code-point a three-byte UTF-8 sequence can represent.
   1401 const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2*6)) - 1;
   1402 
   1403 // The maximum code-point a four-byte UTF-8 sequence can represent.
   1404 const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3*6)) - 1;
   1405 
   1406 // Chops off the n lowest bits from a bit pattern.  Returns the n
   1407 // lowest bits.  As a side effect, the original bit pattern will be
   1408 // shifted to the right by n bits.
   1409 inline UInt32 ChopLowBits(UInt32* bits, int n) {
   1410   const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1);
   1411   *bits >>= n;
   1412   return low_bits;
   1413 }
   1414 
   1415 // Converts a Unicode code point to a narrow string in UTF-8 encoding.
   1416 // code_point parameter is of type UInt32 because wchar_t may not be
   1417 // wide enough to contain a code point.
   1418 // If the code_point is not a valid Unicode code point
   1419 // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
   1420 // to "(Invalid Unicode 0xXXXXXXXX)".
   1421 std::string CodePointToUtf8(UInt32 code_point) {
   1422   if (code_point > kMaxCodePoint4) {
   1423     return "(Invalid Unicode 0x" + String::FormatHexInt(code_point) + ")";
   1424   }
   1425 
   1426   char str[5];  // Big enough for the largest valid code point.
   1427   if (code_point <= kMaxCodePoint1) {
   1428     str[1] = '\0';
   1429     str[0] = static_cast<char>(code_point);                          // 0xxxxxxx
   1430   } else if (code_point <= kMaxCodePoint2) {
   1431     str[2] = '\0';
   1432     str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
   1433     str[0] = static_cast<char>(0xC0 | code_point);                   // 110xxxxx
   1434   } else if (code_point <= kMaxCodePoint3) {
   1435     str[3] = '\0';
   1436     str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
   1437     str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
   1438     str[0] = static_cast<char>(0xE0 | code_point);                   // 1110xxxx
   1439   } else {  // code_point <= kMaxCodePoint4
   1440     str[4] = '\0';
   1441     str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
   1442     str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
   1443     str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
   1444     str[0] = static_cast<char>(0xF0 | code_point);                   // 11110xxx
   1445   }
   1446   return str;
   1447 }
   1448 
   1449 // The following two functions only make sense if the the system
   1450 // uses UTF-16 for wide string encoding. All supported systems
   1451 // with 16 bit wchar_t (Windows, Cygwin, Symbian OS) do use UTF-16.
   1452 
   1453 // Determines if the arguments constitute UTF-16 surrogate pair
   1454 // and thus should be combined into a single Unicode code point
   1455 // using CreateCodePointFromUtf16SurrogatePair.
   1456 inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
   1457   return sizeof(wchar_t) == 2 &&
   1458       (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;
   1459 }
   1460 
   1461 // Creates a Unicode code point from UTF16 surrogate pair.
   1462 inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first,
   1463                                                     wchar_t second) {
   1464   const UInt32 mask = (1 << 10) - 1;
   1465   return (sizeof(wchar_t) == 2) ?
   1466       (((first & mask) << 10) | (second & mask)) + 0x10000 :
   1467       // This function should not be called when the condition is
   1468       // false, but we provide a sensible default in case it is.
   1469       static_cast<UInt32>(first);
   1470 }
   1471 
   1472 // Converts a wide string to a narrow string in UTF-8 encoding.
   1473 // The wide string is assumed to have the following encoding:
   1474 //   UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
   1475 //   UTF-32 if sizeof(wchar_t) == 4 (on Linux)
   1476 // Parameter str points to a null-terminated wide string.
   1477 // Parameter num_chars may additionally limit the number
   1478 // of wchar_t characters processed. -1 is used when the entire string
   1479 // should be processed.
   1480 // If the string contains code points that are not valid Unicode code points
   1481 // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
   1482 // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
   1483 // and contains invalid UTF-16 surrogate pairs, values in those pairs
   1484 // will be encoded as individual Unicode characters from Basic Normal Plane.
   1485 std::string WideStringToUtf8(const wchar_t* str, int num_chars) {
   1486   if (num_chars == -1)
   1487     num_chars = static_cast<int>(wcslen(str));
   1488 
   1489   ::std::stringstream stream;
   1490   for (int i = 0; i < num_chars; ++i) {
   1491     UInt32 unicode_code_point;
   1492 
   1493     if (str[i] == L'\0') {
   1494       break;
   1495     } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
   1496       unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i],
   1497                                                                  str[i + 1]);
   1498       i++;
   1499     } else {
   1500       unicode_code_point = static_cast<UInt32>(str[i]);
   1501     }
   1502 
   1503     stream << CodePointToUtf8(unicode_code_point);
   1504   }
   1505   return StringStreamToString(&stream);
   1506 }
   1507 
   1508 // Converts a wide C string to an std::string using the UTF-8 encoding.
   1509 // NULL will be converted to "(null)".
   1510 std::string String::ShowWideCString(const wchar_t * wide_c_str) {
   1511   if (wide_c_str == NULL)  return "(null)";
   1512 
   1513   return internal::WideStringToUtf8(wide_c_str, -1);
   1514 }
   1515 
   1516 // Compares two wide C strings.  Returns true iff they have the same
   1517 // content.
   1518 //
   1519 // Unlike wcscmp(), this function can handle NULL argument(s).  A NULL
   1520 // C string is considered different to any non-NULL C string,
   1521 // including the empty string.
   1522 bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {
   1523   if (lhs == NULL) return rhs == NULL;
   1524 
   1525   if (rhs == NULL) return false;
   1526 
   1527   return wcscmp(lhs, rhs) == 0;
   1528 }
   1529 
   1530 // Helper function for *_STREQ on wide strings.
   1531 AssertionResult CmpHelperSTREQ(const char* expected_expression,
   1532                                const char* actual_expression,
   1533                                const wchar_t* expected,
   1534                                const wchar_t* actual) {
   1535   if (String::WideCStringEquals(expected, actual)) {
   1536     return AssertionSuccess();
   1537   }
   1538 
   1539   return EqFailure(expected_expression,
   1540                    actual_expression,
   1541                    PrintToString(expected),
   1542                    PrintToString(actual),
   1543                    false);
   1544 }
   1545 
   1546 // Helper function for *_STRNE on wide strings.
   1547 AssertionResult CmpHelperSTRNE(const char* s1_expression,
   1548                                const char* s2_expression,
   1549                                const wchar_t* s1,
   1550                                const wchar_t* s2) {
   1551   if (!String::WideCStringEquals(s1, s2)) {
   1552     return AssertionSuccess();
   1553   }
   1554 
   1555   return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
   1556                             << s2_expression << "), actual: "
   1557                             << PrintToString(s1)
   1558                             << " vs " << PrintToString(s2);
   1559 }
   1560 
   1561 // Compares two C strings, ignoring case.  Returns true iff they have
   1562 // the same content.
   1563 //
   1564 // Unlike strcasecmp(), this function can handle NULL argument(s).  A
   1565 // NULL C string is considered different to any non-NULL C string,
   1566 // including the empty string.
   1567 bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) {
   1568   if (lhs == NULL)
   1569     return rhs == NULL;
   1570   if (rhs == NULL)
   1571     return false;
   1572   return posix::StrCaseCmp(lhs, rhs) == 0;
   1573 }
   1574 
   1575   // Compares two wide C strings, ignoring case.  Returns true iff they
   1576   // have the same content.
   1577   //
   1578   // Unlike wcscasecmp(), this function can handle NULL argument(s).
   1579   // A NULL C string is considered different to any non-NULL wide C string,
   1580   // including the empty string.
   1581   // NB: The implementations on different platforms slightly differ.
   1582   // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
   1583   // environment variable. On GNU platform this method uses wcscasecmp
   1584   // which compares according to LC_CTYPE category of the current locale.
   1585   // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
   1586   // current locale.
   1587 bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
   1588                                               const wchar_t* rhs) {
   1589   if (lhs == NULL) return rhs == NULL;
   1590 
   1591   if (rhs == NULL) return false;
   1592 
   1593 #if GTEST_OS_WINDOWS
   1594   return _wcsicmp(lhs, rhs) == 0;
   1595 #elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID
   1596   return wcscasecmp(lhs, rhs) == 0;
   1597 #else
   1598   // Android, Mac OS X and Cygwin don't define wcscasecmp.
   1599   // Other unknown OSes may not define it either.
   1600   wint_t left, right;
   1601   do {
   1602     left = towlower(*lhs++);
   1603     right = towlower(*rhs++);
   1604   } while (left && left == right);
   1605   return left == right;
   1606 #endif  // OS selector
   1607 }
   1608 
   1609 // Returns true iff str ends with the given suffix, ignoring case.
   1610 // Any string is considered to end with an empty suffix.
   1611 bool String::EndsWithCaseInsensitive(
   1612     const std::string& str, const std::string& suffix) {
   1613   const size_t str_len = str.length();
   1614   const size_t suffix_len = suffix.length();
   1615   return (str_len >= suffix_len) &&
   1616          CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len,
   1617                                       suffix.c_str());
   1618 }
   1619 
   1620 // Formats an int value as "%02d".
   1621 std::string String::FormatIntWidth2(int value) {
   1622   std::stringstream ss;
   1623   ss << std::setfill('0') << std::setw(2) << value;
   1624   return ss.str();
   1625 }
   1626 
   1627 // Formats an int value as "%X".
   1628 std::string String::FormatHexInt(int value) {
   1629   std::stringstream ss;
   1630   ss << std::hex << std::uppercase << value;
   1631   return ss.str();
   1632 }
   1633 
   1634 // Formats a byte as "%02X".
   1635 std::string String::FormatByte(unsigned char value) {
   1636   std::stringstream ss;
   1637   ss << std::setfill('0') << std::setw(2) << std::hex << std::uppercase
   1638      << static_cast<unsigned int>(value);
   1639   return ss.str();
   1640 }
   1641 
   1642 // Converts the buffer in a stringstream to an std::string, converting NUL
   1643 // bytes to "\\0" along the way.
   1644 std::string StringStreamToString(::std::stringstream* ss) {
   1645   const ::std::string& str = ss->str();
   1646   const char* const start = str.c_str();
   1647   const char* const end = start + str.length();
   1648 
   1649   std::string result;
   1650   result.reserve(2 * (end - start));
   1651   for (const char* ch = start; ch != end; ++ch) {
   1652     if (*ch == '\0') {
   1653       result += "\\0";  // Replaces NUL with "\\0";
   1654     } else {
   1655       result += *ch;
   1656     }
   1657   }
   1658 
   1659   return result;
   1660 }
   1661 
   1662 // Appends the user-supplied message to the Google-Test-generated message.
   1663 std::string AppendUserMessage(const std::string& gtest_msg,
   1664                               const Message& user_msg) {
   1665   // Appends the user message if it's non-empty.
   1666   const std::string user_msg_string = user_msg.GetString();
   1667   if (user_msg_string.empty()) {
   1668     return gtest_msg;
   1669   }
   1670 
   1671   return gtest_msg + "\n" + user_msg_string;
   1672 }
   1673 
   1674 }  // namespace internal
   1675 
   1676 // class TestResult
   1677 
   1678 // Creates an empty TestResult.
   1679 TestResult::TestResult()
   1680     : death_test_count_(0),
   1681       elapsed_time_(0) {
   1682 }
   1683 
   1684 // D'tor.
   1685 TestResult::~TestResult() {
   1686 }
   1687 
   1688 // Returns the i-th test part result among all the results. i can
   1689 // range from 0 to total_part_count() - 1. If i is not in that range,
   1690 // aborts the program.
   1691 const TestPartResult& TestResult::GetTestPartResult(int i) const {
   1692   if (i < 0 || i >= total_part_count())
   1693     internal::posix::Abort();
   1694   return test_part_results_.at(i);
   1695 }
   1696 
   1697 // Returns the i-th test property. i can range from 0 to
   1698 // test_property_count() - 1. If i is not in that range, aborts the
   1699 // program.
   1700 const TestProperty& TestResult::GetTestProperty(int i) const {
   1701   if (i < 0 || i >= test_property_count())
   1702     internal::posix::Abort();
   1703   return test_properties_.at(i);
   1704 }
   1705 
   1706 // Clears the test part results.
   1707 void TestResult::ClearTestPartResults() {
   1708   test_part_results_.clear();
   1709 }
   1710 
   1711 // Adds a test part result to the list.
   1712 void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
   1713   test_part_results_.push_back(test_part_result);
   1714 }
   1715 
   1716 // Adds a test property to the list. If a property with the same key as the
   1717 // supplied property is already represented, the value of this test_property
   1718 // replaces the old value for that key.
   1719 void TestResult::RecordProperty(const TestProperty& test_property) {
   1720   if (!ValidateTestProperty(test_property)) {
   1721     return;
   1722   }
   1723   internal::MutexLock lock(&test_properites_mutex_);
   1724   const std::vector<TestProperty>::iterator property_with_matching_key =
   1725       std::find_if(test_properties_.begin(), test_properties_.end(),
   1726                    internal::TestPropertyKeyIs(test_property.key()));
   1727   if (property_with_matching_key == test_properties_.end()) {
   1728     test_properties_.push_back(test_property);
   1729     return;
   1730   }
   1731   property_with_matching_key->SetValue(test_property.value());
   1732 }
   1733 
   1734 // Adds a failure if the key is a reserved attribute of Google Test
   1735 // testcase tags.  Returns true if the property is valid.
   1736 bool TestResult::ValidateTestProperty(const TestProperty& test_property) {
   1737   const std::string& key = test_property.key();
   1738   if (key == "name" || key == "status" || key == "time" || key == "classname") {
   1739     ADD_FAILURE()
   1740         << "Reserved key used in RecordProperty(): "
   1741         << key
   1742         << " ('name', 'status', 'time', and 'classname' are reserved by "
   1743         << GTEST_NAME_ << ")";
   1744     return false;
   1745   }
   1746   return true;
   1747 }
   1748 
   1749 // Clears the object.
   1750 void TestResult::Clear() {
   1751   test_part_results_.clear();
   1752   test_properties_.clear();
   1753   death_test_count_ = 0;
   1754   elapsed_time_ = 0;
   1755 }
   1756 
   1757 // Returns true iff the test failed.
   1758 bool TestResult::Failed() const {
   1759   for (int i = 0; i < total_part_count(); ++i) {
   1760     if (GetTestPartResult(i).failed())
   1761       return true;
   1762   }
   1763   return false;
   1764 }
   1765 
   1766 // Returns true iff the test part fatally failed.
   1767 static bool TestPartFatallyFailed(const TestPartResult& result) {
   1768   return result.fatally_failed();
   1769 }
   1770 
   1771 // Returns true iff the test fatally failed.
   1772 bool TestResult::HasFatalFailure() const {
   1773   return CountIf(test_part_results_, TestPartFatallyFailed) > 0;
   1774 }
   1775 
   1776 // Returns true iff the test part non-fatally failed.
   1777 static bool TestPartNonfatallyFailed(const TestPartResult& result) {
   1778   return result.nonfatally_failed();
   1779 }
   1780 
   1781 // Returns true iff the test has a non-fatal failure.
   1782 bool TestResult::HasNonfatalFailure() const {
   1783   return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0;
   1784 }
   1785 
   1786 // Gets the number of all test parts.  This is the sum of the number
   1787 // of successful test parts and the number of failed test parts.
   1788 int TestResult::total_part_count() const {
   1789   return static_cast<int>(test_part_results_.size());
   1790 }
   1791 
   1792 // Returns the number of the test properties.
   1793 int TestResult::test_property_count() const {
   1794   return static_cast<int>(test_properties_.size());
   1795 }
   1796 
   1797 // class Test
   1798 
   1799 // Creates a Test object.
   1800 
   1801 // The c'tor saves the values of all Google Test flags.
   1802 Test::Test()
   1803     : gtest_flag_saver_(new internal::GTestFlagSaver) {
   1804 }
   1805 
   1806 // The d'tor restores the values of all Google Test flags.
   1807 Test::~Test() {
   1808   delete gtest_flag_saver_;
   1809 }
   1810 
   1811 // Sets up the test fixture.
   1812 //
   1813 // A sub-class may override this.
   1814 void Test::SetUp() {
   1815 }
   1816 
   1817 // Tears down the test fixture.
   1818 //
   1819 // A sub-class may override this.
   1820 void Test::TearDown() {
   1821 }
   1822 
   1823 // Allows user supplied key value pairs to be recorded for later output.
   1824 void Test::RecordProperty(const char* key, const char* value) {
   1825   UnitTest::GetInstance()->RecordPropertyForCurrentTest(key, value);
   1826 }
   1827 
   1828 // Allows user supplied key value pairs to be recorded for later output.
   1829 void Test::RecordProperty(const char* key, int value) {
   1830   Message value_message;
   1831   value_message << value;
   1832   RecordProperty(key, value_message.GetString().c_str());
   1833 }
   1834 
   1835 namespace internal {
   1836 
   1837 void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
   1838                                     const std::string& message) {
   1839   // This function is a friend of UnitTest and as such has access to
   1840   // AddTestPartResult.
   1841   UnitTest::GetInstance()->AddTestPartResult(
   1842       result_type,
   1843       NULL,  // No info about the source file where the exception occurred.
   1844       -1,    // We have no info on which line caused the exception.
   1845       message,
   1846       "");   // No stack trace, either.
   1847 }
   1848 
   1849 }  // namespace internal
   1850 
   1851 // Google Test requires all tests in the same test case to use the same test
   1852 // fixture class.  This function checks if the current test has the
   1853 // same fixture class as the first test in the current test case.  If
   1854 // yes, it returns true; otherwise it generates a Google Test failure and
   1855 // returns false.
   1856 bool Test::HasSameFixtureClass() {
   1857   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
   1858   const TestCase* const test_case = impl->current_test_case();
   1859 
   1860   // Info about the first test in the current test case.
   1861   const TestInfo* const first_test_info = test_case->test_info_list()[0];
   1862   const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_;
   1863   const char* const first_test_name = first_test_info->name();
   1864 
   1865   // Info about the current test.
   1866   const TestInfo* const this_test_info = impl->current_test_info();
   1867   const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_;
   1868   const char* const this_test_name = this_test_info->name();
   1869 
   1870   if (this_fixture_id != first_fixture_id) {
   1871     // Is the first test defined using TEST?
   1872     const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();
   1873     // Is this test defined using TEST?
   1874     const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();
   1875 
   1876     if (first_is_TEST || this_is_TEST) {
   1877       // The user mixed TEST and TEST_F in this test case - we'll tell
   1878       // him/her how to fix it.
   1879 
   1880       // Gets the name of the TEST and the name of the TEST_F.  Note
   1881       // that first_is_TEST and this_is_TEST cannot both be true, as
   1882       // the fixture IDs are different for the two tests.
   1883       const char* const TEST_name =
   1884           first_is_TEST ? first_test_name : this_test_name;
   1885       const char* const TEST_F_name =
   1886           first_is_TEST ? this_test_name : first_test_name;
   1887 
   1888       ADD_FAILURE()
   1889           << "All tests in the same test case must use the same test fixture\n"
   1890           << "class, so mixing TEST_F and TEST in the same test case is\n"
   1891           << "illegal.  In test case " << this_test_info->test_case_name()
   1892           << ",\n"
   1893           << "test " << TEST_F_name << " is defined using TEST_F but\n"
   1894           << "test " << TEST_name << " is defined using TEST.  You probably\n"
   1895           << "want to change the TEST to TEST_F or move it to another test\n"
   1896           << "case.";
   1897     } else {
   1898       // The user defined two fixture classes with the same name in
   1899       // two namespaces - we'll tell him/her how to fix it.
   1900       ADD_FAILURE()
   1901           << "All tests in the same test case must use the same test fixture\n"
   1902           << "class.  However, in test case "
   1903           << this_test_info->test_case_name() << ",\n"
   1904           << "you defined test " << first_test_name
   1905           << " and test " << this_test_name << "\n"
   1906           << "using two different test fixture classes.  This can happen if\n"
   1907           << "the two classes are from different namespaces or translation\n"
   1908           << "units and have the same name.  You should probably rename one\n"
   1909           << "of the classes to put the tests into different test cases.";
   1910     }
   1911     return false;
   1912   }
   1913 
   1914   return true;
   1915 }
   1916 
   1917 #if GTEST_HAS_SEH
   1918 
   1919 // Adds an "exception thrown" fatal failure to the current test.  This
   1920 // function returns its result via an output parameter pointer because VC++
   1921 // prohibits creation of objects with destructors on stack in functions
   1922 // using __try (see error C2712).
   1923 static std::string* FormatSehExceptionMessage(DWORD exception_code,
   1924                                               const char* location) {
   1925   Message message;
   1926   message << "SEH exception with code 0x" << std::setbase(16) <<
   1927     exception_code << std::setbase(10) << " thrown in " << location << ".";
   1928 
   1929   return new std::string(message.GetString());
   1930 }
   1931 
   1932 #endif  // GTEST_HAS_SEH
   1933 
   1934 namespace internal {
   1935 
   1936 #if GTEST_HAS_EXCEPTIONS
   1937 
   1938 // Adds an "exception thrown" fatal failure to the current test.
   1939 static std::string FormatCxxExceptionMessage(const char* description,
   1940                                              const char* location) {
   1941   Message message;
   1942   if (description != NULL) {
   1943     message << "C++ exception with description \"" << description << "\"";
   1944   } else {
   1945     message << "Unknown C++ exception";
   1946   }
   1947   message << " thrown in " << location << ".";
   1948 
   1949   return message.GetString();
   1950 }
   1951 
   1952 static std::string PrintTestPartResultToString(
   1953     const TestPartResult& test_part_result);
   1954 
   1955 GoogleTestFailureException::GoogleTestFailureException(
   1956     const TestPartResult& failure)
   1957     : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
   1958 
   1959 #endif  // GTEST_HAS_EXCEPTIONS
   1960 
   1961 // We put these helper functions in the internal namespace as IBM's xlC
   1962 // compiler rejects the code if they were declared static.
   1963 
   1964 // Runs the given method and handles SEH exceptions it throws, when
   1965 // SEH is supported; returns the 0-value for type Result in case of an
   1966 // SEH exception.  (Microsoft compilers cannot handle SEH and C++
   1967 // exceptions in the same function.  Therefore, we provide a separate
   1968 // wrapper function for handling SEH exceptions.)
   1969 template <class T, typename Result>
   1970 Result HandleSehExceptionsInMethodIfSupported(
   1971     T* object, Result (T::*method)(), const char* location) {
   1972 #if GTEST_HAS_SEH
   1973   __try {
   1974     return (object->*method)();
   1975   } __except (internal::UnitTestOptions::GTestShouldProcessSEH(  // NOLINT
   1976       GetExceptionCode())) {
   1977     // We create the exception message on the heap because VC++ prohibits
   1978     // creation of objects with destructors on stack in functions using __try
   1979     // (see error C2712).
   1980     std::string* exception_message = FormatSehExceptionMessage(
   1981         GetExceptionCode(), location);
   1982     internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
   1983                                              *exception_message);
   1984     delete exception_message;
   1985     return static_cast<Result>(0);
   1986   }
   1987 #else
   1988   (void)location;
   1989   return (object->*method)();
   1990 #endif  // GTEST_HAS_SEH
   1991 }
   1992 
   1993 // Runs the given method and catches and reports C++ and/or SEH-style
   1994 // exceptions, if they are supported; returns the 0-value for type
   1995 // Result in case of an SEH exception.
   1996 template <class T, typename Result>
   1997 Result HandleExceptionsInMethodIfSupported(
   1998     T* object, Result (T::*method)(), const char* location) {
   1999   // NOTE: The user code can affect the way in which Google Test handles
   2000   // exceptions by setting GTEST_FLAG(catch_exceptions), but only before
   2001   // RUN_ALL_TESTS() starts. It is technically possible to check the flag
   2002   // after the exception is caught and either report or re-throw the
   2003   // exception based on the flag's value:
   2004   //
   2005   // try {
   2006   //   // Perform the test method.
   2007   // } catch (...) {
   2008   //   if (GTEST_FLAG(catch_exceptions))
   2009   //     // Report the exception as failure.
   2010   //   else
   2011   //     throw;  // Re-throws the original exception.
   2012   // }
   2013   //
   2014   // However, the purpose of this flag is to allow the program to drop into
   2015   // the debugger when the exception is thrown. On most platforms, once the
   2016   // control enters the catch block, the exception origin information is
   2017   // lost and the debugger will stop the program at the point of the
   2018   // re-throw in this function -- instead of at the point of the original
   2019   // throw statement in the code under test.  For this reason, we perform
   2020   // the check early, sacrificing the ability to affect Google Test's
   2021   // exception handling in the method where the exception is thrown.
   2022   if (internal::GetUnitTestImpl()->catch_exceptions()) {
   2023 #if GTEST_HAS_EXCEPTIONS
   2024     try {
   2025       return HandleSehExceptionsInMethodIfSupported(object, method, location);
   2026     } catch (const internal::GoogleTestFailureException&) {  // NOLINT
   2027       // This exception type can only be thrown by a failed Google
   2028       // Test assertion with the intention of letting another testing
   2029       // framework catch it.  Therefore we just re-throw it.
   2030       throw;
   2031     } catch (const std::exception& e) {  // NOLINT
   2032       internal::ReportFailureInUnknownLocation(
   2033           TestPartResult::kFatalFailure,
   2034           FormatCxxExceptionMessage(e.what(), location));
   2035     } catch (...) {  // NOLINT
   2036       internal::ReportFailureInUnknownLocation(
   2037           TestPartResult::kFatalFailure,
   2038           FormatCxxExceptionMessage(NULL, location));
   2039     }
   2040     return static_cast<Result>(0);
   2041 #else
   2042     return HandleSehExceptionsInMethodIfSupported(object, method, location);
   2043 #endif  // GTEST_HAS_EXCEPTIONS
   2044   } else {
   2045     return (object->*method)();
   2046   }
   2047 }
   2048 
   2049 }  // namespace internal
   2050 
   2051 // Runs the test and updates the test result.
   2052 void Test::Run() {
   2053   if (!HasSameFixtureClass()) return;
   2054 
   2055   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
   2056   impl->os_stack_trace_getter()->UponLeavingGTest();
   2057   internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()");
   2058   // We will run the test only if SetUp() was successful.
   2059   if (!HasFatalFailure()) {
   2060     impl->os_stack_trace_getter()->UponLeavingGTest();
   2061     internal::HandleExceptionsInMethodIfSupported(
   2062         this, &Test::TestBody, "the test body");
   2063   }
   2064 
   2065   // However, we want to clean up as much as possible.  Hence we will
   2066   // always call TearDown(), even if SetUp() or the test body has
   2067   // failed.
   2068   impl->os_stack_trace_getter()->UponLeavingGTest();
   2069   internal::HandleExceptionsInMethodIfSupported(
   2070       this, &Test::TearDown, "TearDown()");
   2071 }
   2072 
   2073 // Returns true iff the current test has a fatal failure.
   2074 bool Test::HasFatalFailure() {
   2075   return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
   2076 }
   2077 
   2078 // Returns true iff the current test has a non-fatal failure.
   2079 bool Test::HasNonfatalFailure() {
   2080   return internal::GetUnitTestImpl()->current_test_result()->
   2081       HasNonfatalFailure();
   2082 }
   2083 
   2084 // class TestInfo
   2085 
   2086 // Constructs a TestInfo object. It assumes ownership of the test factory
   2087 // object.
   2088 TestInfo::TestInfo(const std::string& a_test_case_name,
   2089                    const std::string& a_name,
   2090                    const char* a_type_param,
   2091                    const char* a_value_param,
   2092                    internal::TypeId fixture_class_id,
   2093                    internal::TestFactoryBase* factory)
   2094     : test_case_name_(a_test_case_name),
   2095       name_(a_name),
   2096       type_param_(a_type_param ? new std::string(a_type_param) : NULL),
   2097       value_param_(a_value_param ? new std::string(a_value_param) : NULL),
   2098       fixture_class_id_(fixture_class_id),
   2099       should_run_(false),
   2100       is_disabled_(false),
   2101       matches_filter_(false),
   2102       factory_(factory),
   2103       result_() {}
   2104 
   2105 // Destructs a TestInfo object.
   2106 TestInfo::~TestInfo() { delete factory_; }
   2107 
   2108 namespace internal {
   2109 
   2110 // Creates a new TestInfo object and registers it with Google Test;
   2111 // returns the created object.
   2112 //
   2113 // Arguments:
   2114 //
   2115 //   test_case_name:   name of the test case
   2116 //   name:             name of the test
   2117 //   type_param:       the name of the test's type parameter, or NULL if
   2118 //                     this is not a typed or a type-parameterized test.
   2119 //   value_param:      text representation of the test's value parameter,
   2120 //                     or NULL if this is not a value-parameterized test.
   2121 //   fixture_class_id: ID of the test fixture class
   2122 //   set_up_tc:        pointer to the function that sets up the test case
   2123 //   tear_down_tc:     pointer to the function that tears down the test case
   2124 //   factory:          pointer to the factory that creates a test object.
   2125 //                     The newly created TestInfo instance will assume
   2126 //                     ownership of the factory object.
   2127 TestInfo* MakeAndRegisterTestInfo(
   2128     const char* test_case_name,
   2129     const char* name,
   2130     const char* type_param,
   2131     const char* value_param,
   2132     TypeId fixture_class_id,
   2133     SetUpTestCaseFunc set_up_tc,
   2134     TearDownTestCaseFunc tear_down_tc,
   2135     TestFactoryBase* factory) {
   2136   TestInfo* const test_info =
   2137       new TestInfo(test_case_name, name, type_param, value_param,
   2138                    fixture_class_id, factory);
   2139   GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
   2140   return test_info;
   2141 }
   2142 
   2143 #if GTEST_HAS_PARAM_TEST
   2144 void ReportInvalidTestCaseType(const char* test_case_name,
   2145                                const char* file, int line) {
   2146   Message errors;
   2147   errors
   2148       << "Attempted redefinition of test case " << test_case_name << ".\n"
   2149       << "All tests in the same test case must use the same test fixture\n"
   2150       << "class.  However, in test case " << test_case_name << ", you tried\n"
   2151       << "to define a test using a fixture class different from the one\n"
   2152       << "used earlier. This can happen if the two fixture classes are\n"
   2153       << "from different namespaces and have the same name. You should\n"
   2154       << "probably rename one of the classes to put the tests into different\n"
   2155       << "test cases.";
   2156 
   2157   fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
   2158           errors.GetString().c_str());
   2159 }
   2160 #endif  // GTEST_HAS_PARAM_TEST
   2161 
   2162 }  // namespace internal
   2163 
   2164 namespace {
   2165 
   2166 // A predicate that checks the test name of a TestInfo against a known
   2167 // value.
   2168 //
   2169 // This is used for implementation of the TestCase class only.  We put
   2170 // it in the anonymous namespace to prevent polluting the outer
   2171 // namespace.
   2172 //
   2173 // TestNameIs is copyable.
   2174 class TestNameIs {
   2175  public:
   2176   // Constructor.
   2177   //
   2178   // TestNameIs has NO default constructor.
   2179   explicit TestNameIs(const char* name)
   2180       : name_(name) {}
   2181 
   2182   // Returns true iff the test name of test_info matches name_.
   2183   bool operator()(const TestInfo * test_info) const {
   2184     return test_info && test_info->name() == name_;
   2185   }
   2186 
   2187  private:
   2188   std::string name_;
   2189 };
   2190 
   2191 }  // namespace
   2192 
   2193 namespace internal {
   2194 
   2195 // This method expands all parameterized tests registered with macros TEST_P
   2196 // and INSTANTIATE_TEST_CASE_P into regular tests and registers those.
   2197 // This will be done just once during the program runtime.
   2198 void UnitTestImpl::RegisterParameterizedTests() {
   2199 #if GTEST_HAS_PARAM_TEST
   2200   if (!parameterized_tests_registered_) {
   2201     parameterized_test_registry_.RegisterTests();
   2202     parameterized_tests_registered_ = true;
   2203   }
   2204 #endif
   2205 }
   2206 
   2207 }  // namespace internal
   2208 
   2209 // Creates the test object, runs it, records its result, and then
   2210 // deletes it.
   2211 void TestInfo::Run() {
   2212   if (!should_run_) return;
   2213 
   2214   // Tells UnitTest where to store test result.
   2215   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
   2216   impl->set_current_test_info(this);
   2217 
   2218   TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
   2219 
   2220   // Notifies the unit test event listeners that a test is about to start.
   2221   repeater->OnTestStart(*this);
   2222 
   2223   const TimeInMillis start = internal::GetTimeInMillis();
   2224 
   2225   impl->os_stack_trace_getter()->UponLeavingGTest();
   2226 
   2227   // Creates the test object.
   2228   Test* const test = internal::HandleExceptionsInMethodIfSupported(
   2229       factory_, &internal::TestFactoryBase::CreateTest,
   2230       "the test fixture's constructor");
   2231 
   2232   // Runs the test only if the test object was created and its
   2233   // constructor didn't generate a fatal failure.
   2234   if ((test != NULL) && !Test::HasFatalFailure()) {
   2235     // This doesn't throw as all user code that can throw are wrapped into
   2236     // exception handling code.
   2237     test->Run();
   2238   }
   2239 
   2240   // Deletes the test object.
   2241   impl->os_stack_trace_getter()->UponLeavingGTest();
   2242   internal::HandleExceptionsInMethodIfSupported(
   2243       test, &Test::DeleteSelf_, "the test fixture's destructor");
   2244 
   2245   result_.set_elapsed_time(internal::GetTimeInMillis() - start);
   2246 
   2247   // Notifies the unit test event listener that a test has just finished.
   2248   repeater->OnTestEnd(*this);
   2249 
   2250   // Tells UnitTest to stop associating assertion results to this
   2251   // test.
   2252   impl->set_current_test_info(NULL);
   2253 }
   2254 
   2255 // class TestCase
   2256 
   2257 // Gets the number of successful tests in this test case.
   2258 int TestCase::successful_test_count() const {
   2259   return CountIf(test_info_list_, TestPassed);
   2260 }
   2261 
   2262 // Gets the number of failed tests in this test case.
   2263 int TestCase::failed_test_count() const {
   2264   return CountIf(test_info_list_, TestFailed);
   2265 }
   2266 
   2267 int TestCase::disabled_test_count() const {
   2268   return CountIf(test_info_list_, TestDisabled);
   2269 }
   2270 
   2271 // Get the number of tests in this test case that should run.
   2272 int TestCase::test_to_run_count() const {
   2273   return CountIf(test_info_list_, ShouldRunTest);
   2274 }
   2275 
   2276 // Gets the number of all tests.
   2277 int TestCase::total_test_count() const {
   2278   return static_cast<int>(test_info_list_.size());
   2279 }
   2280 
   2281 // Creates a TestCase with the given name.
   2282 //
   2283 // Arguments:
   2284 //
   2285 //   name:         name of the test case
   2286 //   a_type_param: the name of the test case's type parameter, or NULL if
   2287 //                 this is not a typed or a type-parameterized test case.
   2288 //   set_up_tc:    pointer to the function that sets up the test case
   2289 //   tear_down_tc: pointer to the function that tears down the test case
   2290 TestCase::TestCase(const char* a_name, const char* a_type_param,
   2291                    Test::SetUpTestCaseFunc set_up_tc,
   2292                    Test::TearDownTestCaseFunc tear_down_tc)
   2293     : name_(a_name),
   2294       type_param_(a_type_param ? new std::string(a_type_param) : NULL),
   2295       set_up_tc_(set_up_tc),
   2296       tear_down_tc_(tear_down_tc),
   2297       should_run_(false),
   2298       elapsed_time_(0) {
   2299 }
   2300 
   2301 // Destructor of TestCase.
   2302 TestCase::~TestCase() {
   2303   // Deletes every Test in the collection.
   2304   ForEach(test_info_list_, internal::Delete<TestInfo>);
   2305 }
   2306 
   2307 // Returns the i-th test among all the tests. i can range from 0 to
   2308 // total_test_count() - 1. If i is not in that range, returns NULL.
   2309 const TestInfo* TestCase::GetTestInfo(int i) const {
   2310   const int index = GetElementOr(test_indices_, i, -1);
   2311   return index < 0 ? NULL : test_info_list_[index];
   2312 }
   2313 
   2314 // Returns the i-th test among all the tests. i can range from 0 to
   2315 // total_test_count() - 1. If i is not in that range, returns NULL.
   2316 TestInfo* TestCase::GetMutableTestInfo(int i) {
   2317   const int index = GetElementOr(test_indices_, i, -1);
   2318   return index < 0 ? NULL : test_info_list_[index];
   2319 }
   2320 
   2321 // Adds a test to this test case.  Will delete the test upon
   2322 // destruction of the TestCase object.
   2323 void TestCase::AddTestInfo(TestInfo * test_info) {
   2324   test_info_list_.push_back(test_info);
   2325   test_indices_.push_back(static_cast<int>(test_indices_.size()));
   2326 }
   2327 
   2328 // Runs every test in this TestCase.
   2329 void TestCase::Run() {
   2330   if (!should_run_) return;
   2331 
   2332   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
   2333   impl->set_current_test_case(this);
   2334 
   2335   TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
   2336 
   2337   repeater->OnTestCaseStart(*this);
   2338   impl->os_stack_trace_getter()->UponLeavingGTest();
   2339   internal::HandleExceptionsInMethodIfSupported(
   2340       this, &TestCase::RunSetUpTestCase, "SetUpTestCase()");
   2341 
   2342   const internal::TimeInMillis start = internal::GetTimeInMillis();
   2343   for (int i = 0; i < total_test_count(); i++) {
   2344     GetMutableTestInfo(i)->Run();
   2345   }
   2346   elapsed_time_ = internal::GetTimeInMillis() - start;
   2347 
   2348   impl->os_stack_trace_getter()->UponLeavingGTest();
   2349   internal::HandleExceptionsInMethodIfSupported(
   2350       this, &TestCase::RunTearDownTestCase, "TearDownTestCase()");
   2351 
   2352   repeater->OnTestCaseEnd(*this);
   2353   impl->set_current_test_case(NULL);
   2354 }
   2355 
   2356 // Clears the results of all tests in this test case.
   2357 void TestCase::ClearResult() {
   2358   ForEach(test_info_list_, TestInfo::ClearTestResult);
   2359 }
   2360 
   2361 // Shuffles the tests in this test case.
   2362 void TestCase::ShuffleTests(internal::Random* random) {
   2363   Shuffle(random, &test_indices_);
   2364 }
   2365 
   2366 // Restores the test order to before the first shuffle.
   2367 void TestCase::UnshuffleTests() {
   2368   for (size_t i = 0; i < test_indices_.size(); i++) {
   2369     test_indices_[i] = static_cast<int>(i);
   2370   }
   2371 }
   2372 
   2373 // Formats a countable noun.  Depending on its quantity, either the
   2374 // singular form or the plural form is used. e.g.
   2375 //
   2376 // FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
   2377 // FormatCountableNoun(5, "book", "books") returns "5 books".
   2378 static std::string FormatCountableNoun(int count,
   2379                                        const char * singular_form,
   2380                                        const char * plural_form) {
   2381   return internal::StreamableToString(count) + " " +
   2382       (count == 1 ? singular_form : plural_form);
   2383 }
   2384 
   2385 // Formats the count of tests.
   2386 static std::string FormatTestCount(int test_count) {
   2387   return FormatCountableNoun(test_count, "test", "tests");
   2388 }
   2389 
   2390 // Formats the count of test cases.
   2391 static std::string FormatTestCaseCount(int test_case_count) {
   2392   return FormatCountableNoun(test_case_count, "test case", "test cases");
   2393 }
   2394 
   2395 // Converts a TestPartResult::Type enum to human-friendly string
   2396 // representation.  Both kNonFatalFailure and kFatalFailure are translated
   2397 // to "Failure", as the user usually doesn't care about the difference
   2398 // between the two when viewing the test result.
   2399 static const char * TestPartResultTypeToString(TestPartResult::Type type) {
   2400   switch (type) {
   2401     case TestPartResult::kSuccess:
   2402       return "Success";
   2403 
   2404     case TestPartResult::kNonFatalFailure:
   2405     case TestPartResult::kFatalFailure:
   2406 #ifdef _MSC_VER
   2407       return "error: ";
   2408 #else
   2409       return "Failure\n";
   2410 #endif
   2411     default:
   2412       return "Unknown result type";
   2413   }
   2414 }
   2415 
   2416 namespace internal {
   2417 
   2418 // Prints a TestPartResult to an std::string.
   2419 static std::string PrintTestPartResultToString(
   2420     const TestPartResult& test_part_result) {
   2421   return (Message()
   2422           << internal::FormatFileLocation(test_part_result.file_name(),
   2423                                           test_part_result.line_number())
   2424           << " " << TestPartResultTypeToString(test_part_result.type())
   2425           << test_part_result.message()).GetString();
   2426 }
   2427 
   2428 // Prints a TestPartResult.
   2429 static void PrintTestPartResult(const TestPartResult& test_part_result) {
   2430   const std::string& result =
   2431       PrintTestPartResultToString(test_part_result);
   2432   printf("%s\n", result.c_str());
   2433   fflush(stdout);
   2434   // If the test program runs in Visual Studio or a debugger, the
   2435   // following statements add the test part result message to the Output
   2436   // window such that the user can double-click on it to jump to the
   2437   // corresponding source code location; otherwise they do nothing.
   2438 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
   2439   // We don't call OutputDebugString*() on Windows Mobile, as printing
   2440   // to stdout is done by OutputDebugString() there already - we don't
   2441   // want the same message printed twice.
   2442   ::OutputDebugStringA(result.c_str());
   2443   ::OutputDebugStringA("\n");
   2444 #endif
   2445 }
   2446 
   2447 // class PrettyUnitTestResultPrinter
   2448 
   2449 enum GTestColor {
   2450   COLOR_DEFAULT,
   2451   COLOR_RED,
   2452   COLOR_GREEN,
   2453   COLOR_YELLOW
   2454 };
   2455 
   2456 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
   2457 
   2458 // Returns the character attribute for the given color.
   2459 WORD GetColorAttribute(GTestColor color) {
   2460   switch (color) {
   2461     case COLOR_RED:    return FOREGROUND_RED;
   2462     case COLOR_GREEN:  return FOREGROUND_GREEN;
   2463     case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
   2464     default:           return 0;
   2465   }
   2466 }
   2467 
   2468 #else
   2469 
   2470 // Returns the ANSI color code for the given color.  COLOR_DEFAULT is
   2471 // an invalid input.
   2472 const char* GetAnsiColorCode(GTestColor color) {
   2473   switch (color) {
   2474     case COLOR_RED:     return "1";
   2475     case COLOR_GREEN:   return "2";
   2476     case COLOR_YELLOW:  return "3";
   2477     default:            return NULL;
   2478   };
   2479 }
   2480 
   2481 #endif  // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
   2482 
   2483 // Returns true iff Google Test should use colors in the output.
   2484 bool ShouldUseColor(bool stdout_is_tty) {
   2485   const char* const gtest_color = GTEST_FLAG(color).c_str();
   2486 
   2487   if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
   2488 #if GTEST_OS_WINDOWS
   2489     // On Windows the TERM variable is usually not set, but the
   2490     // console there does support colors.
   2491     return stdout_is_tty;
   2492 #else
   2493     // On non-Windows platforms, we rely on the TERM variable.
   2494     const char* const term = posix::GetEnv("TERM");
   2495     const bool term_supports_color =
   2496         String::CStringEquals(term, "xterm") ||
   2497         String::CStringEquals(term, "xterm-color") ||
   2498         String::CStringEquals(term, "xterm-256color") ||
   2499         String::CStringEquals(term, "screen") ||
   2500         String::CStringEquals(term, "linux") ||
   2501         String::CStringEquals(term, "cygwin");
   2502     return stdout_is_tty && term_supports_color;
   2503 #endif  // GTEST_OS_WINDOWS
   2504   }
   2505 
   2506   return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
   2507       String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
   2508       String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
   2509       String::CStringEquals(gtest_color, "1");
   2510   // We take "yes", "true", "t", and "1" as meaning "yes".  If the
   2511   // value is neither one of these nor "auto", we treat it as "no" to
   2512   // be conservative.
   2513 }
   2514 
   2515 // Helpers for printing colored strings to stdout. Note that on Windows, we
   2516 // cannot simply emit special characters and have the terminal change colors.
   2517 // This routine must actually emit the characters rather than return a string
   2518 // that would be colored when printed, as can be done on Linux.
   2519 void ColoredPrintf(GTestColor color, const char* fmt, ...) {
   2520   va_list args;
   2521   va_start(args, fmt);
   2522 
   2523 #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS || GTEST_OS_IOS
   2524   const bool use_color = false;
   2525 #else
   2526   static const bool in_color_mode =
   2527       ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
   2528   const bool use_color = in_color_mode && (color != COLOR_DEFAULT);
   2529 #endif  // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
   2530   // The '!= 0' comparison is necessary to satisfy MSVC 7.1.
   2531 
   2532   if (!use_color) {
   2533     vprintf(fmt, args);
   2534     va_end(args);
   2535     return;
   2536   }
   2537 
   2538 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
   2539   const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
   2540 
   2541   // Gets the current text color.
   2542   CONSOLE_SCREEN_BUFFER_INFO buffer_info;
   2543   GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
   2544   const WORD old_color_attrs = buffer_info.wAttributes;
   2545 
   2546   // We need to flush the stream buffers into the console before each
   2547   // SetConsoleTextAttribute call lest it affect the text that is already
   2548   // printed but has not yet reached the console.
   2549   fflush(stdout);
   2550   SetConsoleTextAttribute(stdout_handle,
   2551                           GetColorAttribute(color) | FOREGROUND_INTENSITY);
   2552   vprintf(fmt, args);
   2553 
   2554   fflush(stdout);
   2555   // Restores the text color.
   2556   SetConsoleTextAttribute(stdout_handle, old_color_attrs);
   2557 #else
   2558   printf("\033[0;3%sm", GetAnsiColorCode(color));
   2559   vprintf(fmt, args);
   2560   printf("\033[m");  // Resets the terminal to default.
   2561 #endif  // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
   2562   va_end(args);
   2563 }
   2564 
   2565 void PrintFullTestCommentIfPresent(const TestInfo& test_info) {
   2566   const char* const type_param = test_info.type_param();
   2567   const char* const value_param = test_info.value_param();
   2568 
   2569   if (type_param != NULL || value_param != NULL) {
   2570     printf(", where ");
   2571     if (type_param != NULL) {
   2572       printf("TypeParam = %s", type_param);
   2573       if (value_param != NULL)
   2574         printf(" and ");
   2575     }
   2576     if (value_param != NULL) {
   2577       printf("GetParam() = %s", value_param);
   2578     }
   2579   }
   2580 }
   2581 
   2582 // This class implements the TestEventListener interface.
   2583 //
   2584 // Class PrettyUnitTestResultPrinter is copyable.
   2585 class PrettyUnitTestResultPrinter : public TestEventListener {
   2586  public:
   2587   PrettyUnitTestResultPrinter() {}
   2588   static void PrintTestName(const char * test_case, const char * test) {
   2589     printf("%s.%s", test_case, test);
   2590   }
   2591 
   2592   // The following methods override what's in the TestEventListener class.
   2593   virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {}
   2594   virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
   2595   virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
   2596   virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {}
   2597   virtual void OnTestCaseStart(const TestCase& test_case);
   2598   virtual void OnTestStart(const TestInfo& test_info);
   2599   virtual void OnTestPartResult(const TestPartResult& result);
   2600   virtual void OnTestEnd(const TestInfo& test_info);
   2601   virtual void OnTestCaseEnd(const TestCase& test_case);
   2602   virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
   2603   virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {}
   2604   virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
   2605   virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {}
   2606 
   2607  private:
   2608   static void PrintFailedTests(const UnitTest& unit_test);
   2609 };
   2610 
   2611   // Fired before each iteration of tests starts.
   2612 void PrettyUnitTestResultPrinter::OnTestIterationStart(
   2613     const UnitTest& unit_test, int iteration) {
   2614   if (GTEST_FLAG(repeat) != 1)
   2615     printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
   2616 
   2617   const char* const filter = GTEST_FLAG(filter).c_str();
   2618 
   2619   // Prints the filter if it's not *.  This reminds the user that some
   2620   // tests may be skipped.
   2621   if (!String::CStringEquals(filter, kUniversalFilter)) {
   2622     ColoredPrintf(COLOR_YELLOW,
   2623                   "Note: %s filter = %s\n", GTEST_NAME_, filter);
   2624   }
   2625 
   2626   if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
   2627     const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
   2628     ColoredPrintf(COLOR_YELLOW,
   2629                   "Note: This is test shard %d of %s.\n",
   2630                   static_cast<int>(shard_index) + 1,
   2631                   internal::posix::GetEnv(kTestTotalShards));
   2632   }
   2633 
   2634   if (GTEST_FLAG(shuffle)) {
   2635     ColoredPrintf(COLOR_YELLOW,
   2636                   "Note: Randomizing tests' orders with a seed of %d .\n",
   2637                   unit_test.random_seed());
   2638   }
   2639 
   2640   ColoredPrintf(COLOR_GREEN,  "[==========] ");
   2641   printf("Running %s from %s.\n",
   2642          FormatTestCount(unit_test.test_to_run_count()).c_str(),
   2643          FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
   2644   fflush(stdout);
   2645 }
   2646 
   2647 void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
   2648     const UnitTest& /*unit_test*/) {
   2649   ColoredPrintf(COLOR_GREEN,  "[----------] ");
   2650   printf("Global test environment set-up.\n");
   2651   fflush(stdout);
   2652 }
   2653 
   2654 void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {
   2655   const std::string counts =
   2656       FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
   2657   ColoredPrintf(COLOR_GREEN, "[----------] ");
   2658   printf("%s from %s", counts.c_str(), test_case.name());
   2659   if (test_case.type_param() == NULL) {
   2660     printf("\n");
   2661   } else {
   2662     printf(", where TypeParam = %s\n", test_case.type_param());
   2663   }
   2664   fflush(stdout);
   2665 }
   2666 
   2667 void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
   2668   ColoredPrintf(COLOR_GREEN,  "[ RUN      ] ");
   2669   PrintTestName(test_info.test_case_name(), test_info.name());
   2670   printf("\n");
   2671   fflush(stdout);
   2672 }
   2673 
   2674 // Called after an assertion failure.
   2675 void PrettyUnitTestResultPrinter::OnTestPartResult(
   2676     const TestPartResult& result) {
   2677   // If the test part succeeded, we don't need to do anything.
   2678   if (result.type() == TestPartResult::kSuccess)
   2679     return;
   2680 
   2681   // Print failure message from the assertion (e.g. expected this and got that).
   2682   PrintTestPartResult(result);
   2683   fflush(stdout);
   2684 }
   2685 
   2686 void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
   2687   if (test_info.result()->Passed()) {
   2688     ColoredPrintf(COLOR_GREEN, "[       OK ] ");
   2689   } else {
   2690     ColoredPrintf(COLOR_RED, "[  FAILED  ] ");
   2691   }
   2692   PrintTestName(test_info.test_case_name(), test_info.name());
   2693   if (test_info.result()->Failed())
   2694     PrintFullTestCommentIfPresent(test_info);
   2695 
   2696   if (GTEST_FLAG(print_time)) {
   2697     printf(" (%s ms)\n", internal::StreamableToString(
   2698            test_info.result()->elapsed_time()).c_str());
   2699   } else {
   2700     printf("\n");
   2701   }
   2702   fflush(stdout);
   2703 }
   2704 
   2705 void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {
   2706   if (!GTEST_FLAG(print_time)) return;
   2707 
   2708   const std::string counts =
   2709       FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
   2710   ColoredPrintf(COLOR_GREEN, "[----------] ");
   2711   printf("%s from %s (%s ms total)\n\n",
   2712          counts.c_str(), test_case.name(),
   2713          internal::StreamableToString(test_case.elapsed_time()).c_str());
   2714   fflush(stdout);
   2715 }
   2716 
   2717 void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
   2718     const UnitTest& /*unit_test*/) {
   2719   ColoredPrintf(COLOR_GREEN,  "[----------] ");
   2720   printf("Global test environment tear-down\n");
   2721   fflush(stdout);
   2722 }
   2723 
   2724 // Internal helper for printing the list of failed tests.
   2725 void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
   2726   const int failed_test_count = unit_test.failed_test_count();
   2727   if (failed_test_count == 0) {
   2728     return;
   2729   }
   2730 
   2731   for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
   2732     const TestCase& test_case = *unit_test.GetTestCase(i);
   2733     if (!test_case.should_run() || (test_case.failed_test_count() == 0)) {
   2734       continue;
   2735     }
   2736     for (int j = 0; j < test_case.total_test_count(); ++j) {
   2737       const TestInfo& test_info = *test_case.GetTestInfo(j);
   2738       if (!test_info.should_run() || test_info.result()->Passed()) {
   2739         continue;
   2740       }
   2741       ColoredPrintf(COLOR_RED, "[  FAILED  ] ");
   2742       printf("%s.%s", test_case.name(), test_info.name());
   2743       PrintFullTestCommentIfPresent(test_info);
   2744       printf("\n");
   2745     }
   2746   }
   2747 }
   2748 
   2749 void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
   2750                                                      int /*iteration*/) {
   2751   ColoredPrintf(COLOR_GREEN,  "[==========] ");
   2752   printf("%s from %s ran.",
   2753          FormatTestCount(unit_test.test_to_run_count()).c_str(),
   2754          FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
   2755   if (GTEST_FLAG(print_time)) {
   2756     printf(" (%s ms total)",
   2757            internal::StreamableToString(unit_test.elapsed_time()).c_str());
   2758   }
   2759   printf("\n");
   2760   ColoredPrintf(COLOR_GREEN,  "[  PASSED  ] ");
   2761   printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
   2762 
   2763   int num_failures = unit_test.failed_test_count();
   2764   if (!unit_test.Passed()) {
   2765     const int failed_test_count = unit_test.failed_test_count();
   2766     ColoredPrintf(COLOR_RED,  "[  FAILED  ] ");
   2767     printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
   2768     PrintFailedTests(unit_test);
   2769     printf("\n%2d FAILED %s\n", num_failures,
   2770                         num_failures == 1 ? "TEST" : "TESTS");
   2771   }
   2772 
   2773   int num_disabled = unit_test.disabled_test_count();
   2774   if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
   2775     if (!num_failures) {
   2776       printf("\n");  // Add a spacer if no FAILURE banner is displayed.
   2777     }
   2778     ColoredPrintf(COLOR_YELLOW,
   2779                   "  YOU HAVE %d DISABLED %s\n\n",
   2780                   num_disabled,
   2781                   num_disabled == 1 ? "TEST" : "TESTS");
   2782   }
   2783   // Ensure that Google Test output is printed before, e.g., heapchecker output.
   2784   fflush(stdout);
   2785 }
   2786 
   2787 // End PrettyUnitTestResultPrinter
   2788 
   2789 // class TestEventRepeater
   2790 //
   2791 // This class forwards events to other event listeners.
   2792 class TestEventRepeater : public TestEventListener {
   2793  public:
   2794   TestEventRepeater() : forwarding_enabled_(true) {}
   2795   virtual ~TestEventRepeater();
   2796   void Append(TestEventListener *listener);
   2797   TestEventListener* Release(TestEventListener* listener);
   2798 
   2799   // Controls whether events will be forwarded to listeners_. Set to false
   2800   // in death test child processes.
   2801   bool forwarding_enabled() const { return forwarding_enabled_; }
   2802   void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }
   2803 
   2804   virtual void OnTestProgramStart(const UnitTest& unit_test);
   2805   virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
   2806   virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
   2807   virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test);
   2808   virtual void OnTestCaseStart(const TestCase& test_case);
   2809   virtual void OnTestStart(const TestInfo& test_info);
   2810   virtual void OnTestPartResult(const TestPartResult& result);
   2811   virtual void OnTestEnd(const TestInfo& test_info);
   2812   virtual void OnTestCaseEnd(const TestCase& test_case);
   2813   virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
   2814   virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test);
   2815   virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
   2816   virtual void OnTestProgramEnd(const UnitTest& unit_test);
   2817 
   2818  private:
   2819   // Controls whether events will be forwarded to listeners_. Set to false
   2820   // in death test child processes.
   2821   bool forwarding_enabled_;
   2822   // The list of listeners that receive events.
   2823   std::vector<TestEventListener*> listeners_;
   2824 
   2825   GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater);
   2826 };
   2827 
   2828 TestEventRepeater::~TestEventRepeater() {
   2829   ForEach(listeners_, Delete<TestEventListener>);
   2830 }
   2831 
   2832 void TestEventRepeater::Append(TestEventListener *listener) {
   2833   listeners_.push_back(listener);
   2834 }
   2835 
   2836 // TODO(vladl (at) google.com): Factor the search functionality into Vector::Find.
   2837 TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {
   2838   for (size_t i = 0; i < listeners_.size(); ++i) {
   2839     if (listeners_[i] == listener) {
   2840       listeners_.erase(listeners_.begin() + i);
   2841       return listener;
   2842     }
   2843   }
   2844 
   2845   return NULL;
   2846 }
   2847 
   2848 // Since most methods are very similar, use macros to reduce boilerplate.
   2849 // This defines a member that forwards the call to all listeners.
   2850 #define GTEST_REPEATER_METHOD_(Name, Type) \
   2851 void TestEventRepeater::Name(const Type& parameter) { \
   2852   if (forwarding_enabled_) { \
   2853     for (size_t i = 0; i < listeners_.size(); i++) { \
   2854       listeners_[i]->Name(parameter); \
   2855     } \
   2856   } \
   2857 }
   2858 // This defines a member that forwards the call to all listeners in reverse
   2859 // order.
   2860 #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
   2861 void TestEventRepeater::Name(const Type& parameter) { \
   2862   if (forwarding_enabled_) { \
   2863     for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \
   2864       listeners_[i]->Name(parameter); \
   2865     } \
   2866   } \
   2867 }
   2868 
   2869 GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)
   2870 GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)
   2871 GTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase)
   2872 GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
   2873 GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)
   2874 GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)
   2875 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)
   2876 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)
   2877 GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)
   2878 GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestCase)
   2879 GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)
   2880 
   2881 #undef GTEST_REPEATER_METHOD_
   2882 #undef GTEST_REVERSE_REPEATER_METHOD_
   2883 
   2884 void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,
   2885                                              int iteration) {
   2886   if (forwarding_enabled_) {
   2887     for (size_t i = 0; i < listeners_.size(); i++) {
   2888       listeners_[i]->OnTestIterationStart(unit_test, iteration);
   2889     }
   2890   }
   2891 }
   2892 
   2893 void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,
   2894                                            int iteration) {
   2895   if (forwarding_enabled_) {
   2896     for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) {
   2897       listeners_[i]->OnTestIterationEnd(unit_test, iteration);
   2898     }
   2899   }
   2900 }
   2901 
   2902 // End TestEventRepeater
   2903 
   2904 // This class generates an XML output file.
   2905 class XmlUnitTestResultPrinter : public EmptyTestEventListener {
   2906  public:
   2907   explicit XmlUnitTestResultPrinter(const char* output_file);
   2908 
   2909   virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
   2910 
   2911  private:
   2912   // Is c a whitespace character that is normalized to a space character
   2913   // when it appears in an XML attribute value?
   2914   static bool IsNormalizableWhitespace(char c) {
   2915     return c == 0x9 || c == 0xA || c == 0xD;
   2916   }
   2917 
   2918   // May c appear in a well-formed XML document?
   2919   static bool IsValidXmlCharacter(char c) {
   2920     return IsNormalizableWhitespace(c) || c >= 0x20;
   2921   }
   2922 
   2923   // Returns an XML-escaped copy of the input string str.  If
   2924   // is_attribute is true, the text is meant to appear as an attribute
   2925   // value, and normalizable whitespace is preserved by replacing it
   2926   // with character references.
   2927   static std::string EscapeXml(const char* str, bool is_attribute);
   2928 
   2929   // Returns the given string with all characters invalid in XML removed.
   2930   static string RemoveInvalidXmlCharacters(const string& str);
   2931 
   2932   // Convenience wrapper around EscapeXml when str is an attribute value.
   2933   static std::string EscapeXmlAttribute(const char* str) {
   2934     return EscapeXml(str, true);
   2935   }
   2936 
   2937   // Convenience wrapper around EscapeXml when str is not an attribute value.
   2938   static std::string EscapeXmlText(const char* str) {
   2939     return EscapeXml(str, false);
   2940   }
   2941 
   2942   // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
   2943   static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
   2944 
   2945   // Streams an XML representation of a TestInfo object.
   2946   static void OutputXmlTestInfo(::std::ostream* stream,
   2947                                 const char* test_case_name,
   2948                                 const TestInfo& test_info);
   2949 
   2950   // Prints an XML representation of a TestCase object
   2951   static void PrintXmlTestCase(FILE* out, const TestCase& test_case);
   2952 
   2953   // Prints an XML summary of unit_test to output stream out.
   2954   static void PrintXmlUnitTest(FILE* out, const UnitTest& unit_test);
   2955 
   2956   // Produces a string representing the test properties in a result as space
   2957   // delimited XML attributes based on the property key="value" pairs.
   2958   // When the std::string is not empty, it includes a space at the beginning,
   2959   // to delimit this attribute from prior attributes.
   2960   static std::string TestPropertiesAsXmlAttributes(const TestResult& result);
   2961 
   2962   // The output file.
   2963   const std::string output_file_;
   2964 
   2965   GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);
   2966 };
   2967 
   2968 // Creates a new XmlUnitTestResultPrinter.
   2969 XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
   2970     : output_file_(output_file) {
   2971   if (output_file_.c_str() == NULL || output_file_.empty()) {
   2972     fprintf(stderr, "XML output file may not be null\n");
   2973     fflush(stderr);
   2974     exit(EXIT_FAILURE);
   2975   }
   2976 }
   2977 
   2978 // Called after the unit test ends.
   2979 void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
   2980                                                   int /*iteration*/) {
   2981   FILE* xmlout = NULL;
   2982   FilePath output_file(output_file_);
   2983   FilePath output_dir(output_file.RemoveFileName());
   2984 
   2985   if (output_dir.CreateDirectoriesRecursively()) {
   2986     xmlout = posix::FOpen(output_file_.c_str(), "w");
   2987   }
   2988   if (xmlout == NULL) {
   2989     // TODO(wan): report the reason of the failure.
   2990     //
   2991     // We don't do it for now as:
   2992     //
   2993     //   1. There is no urgent need for it.
   2994     //   2. It's a bit involved to make the errno variable thread-safe on
   2995     //      all three operating systems (Linux, Windows, and Mac OS).
   2996     //   3. To interpret the meaning of errno in a thread-safe way,
   2997     //      we need the strerror_r() function, which is not available on
   2998     //      Windows.
   2999     fprintf(stderr,
   3000             "Unable to open file \"%s\"\n",
   3001             output_file_.c_str());
   3002     fflush(stderr);
   3003     exit(EXIT_FAILURE);
   3004   }
   3005   PrintXmlUnitTest(xmlout, unit_test);
   3006   fclose(xmlout);
   3007 }
   3008 
   3009 // Returns an XML-escaped copy of the input string str.  If is_attribute
   3010 // is true, the text is meant to appear as an attribute value, and
   3011 // normalizable whitespace is preserved by replacing it with character
   3012 // references.
   3013 //
   3014 // Invalid XML characters in str, if any, are stripped from the output.
   3015 // It is expected that most, if not all, of the text processed by this
   3016 // module will consist of ordinary English text.
   3017 // If this module is ever modified to produce version 1.1 XML output,
   3018 // most invalid characters can be retained using character references.
   3019 // TODO(wan): It might be nice to have a minimally invasive, human-readable
   3020 // escaping scheme for invalid characters, rather than dropping them.
   3021 std::string XmlUnitTestResultPrinter::EscapeXml(
   3022     const char* str, bool is_attribute) {
   3023   Message m;
   3024 
   3025   if (str != NULL) {
   3026     for (const char* src = str; *src; ++src) {
   3027       switch (*src) {
   3028         case '<':
   3029           m << "&lt;";
   3030           break;
   3031         case '>':
   3032           m << "&gt;";
   3033           break;
   3034         case '&':
   3035           m << "&amp;";
   3036           break;
   3037         case '\'':
   3038           if (is_attribute)
   3039             m << "&apos;";
   3040           else
   3041             m << '\'';
   3042           break;
   3043         case '"':
   3044           if (is_attribute)
   3045             m << "&quot;";
   3046           else
   3047             m << '"';
   3048           break;
   3049         default:
   3050           if (IsValidXmlCharacter(*src)) {
   3051             if (is_attribute && IsNormalizableWhitespace(*src))
   3052               m << "&#x" << String::FormatByte(static_cast<unsigned char>(*src))
   3053                 << ";";
   3054             else
   3055               m << *src;
   3056           }
   3057           break;
   3058       }
   3059     }
   3060   }
   3061 
   3062   return m.GetString();
   3063 }
   3064 
   3065 // Returns the given string with all characters invalid in XML removed.
   3066 // Currently invalid characters are dropped from the string. An
   3067 // alternative is to replace them with certain characters such as . or ?.
   3068 string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(const string& str) {
   3069   string output;
   3070   output.reserve(str.size());
   3071   for (string::const_iterator it = str.begin(); it != str.end(); ++it)
   3072     if (IsValidXmlCharacter(*it))
   3073       output.push_back(*it);
   3074 
   3075   return output;
   3076 }
   3077 
   3078 // The following routines generate an XML representation of a UnitTest
   3079 // object.
   3080 //
   3081 // This is how Google Test concepts map to the DTD:
   3082 //
   3083 // <testsuites name="AllTests">        <-- corresponds to a UnitTest object
   3084 //   <testsuite name="testcase-name">  <-- corresponds to a TestCase object
   3085 //     <testcase name="test-name">     <-- corresponds to a TestInfo object
   3086 //       <failure message="...">...</failure>
   3087 //       <failure message="...">...</failure>
   3088 //       <failure message="...">...</failure>
   3089 //                                     <-- individual assertion failures
   3090 //     </testcase>
   3091 //   </testsuite>
   3092 // </testsuites>
   3093 
   3094 // Formats the given time in milliseconds as seconds.
   3095 std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {
   3096   ::std::stringstream ss;
   3097   ss << ms/1000.0;
   3098   return ss.str();
   3099 }
   3100 
   3101 // Converts the given epoch time in milliseconds to a date string in the ISO
   3102 // 8601 format, without the timezone information.
   3103 std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) {
   3104   // Using non-reentrant version as localtime_r is not portable.
   3105   time_t seconds = static_cast<time_t>(ms / 1000);
   3106 #ifdef _MSC_VER
   3107 # pragma warning(push)          // Saves the current warning state.
   3108 # pragma warning(disable:4996)  // Temporarily disables warning 4996
   3109                                 // (function or variable may be unsafe).
   3110   const struct tm* const time_struct = localtime(&seconds);  // NOLINT
   3111 # pragma warning(pop)           // Restores the warning state again.
   3112 #else
   3113   const struct tm* const time_struct = localtime(&seconds);  // NOLINT
   3114 #endif
   3115   if (time_struct == NULL)
   3116     return "";  // Invalid ms value
   3117 
   3118   // YYYY-MM-DDThh:mm:ss
   3119   return StreamableToString(time_struct->tm_year + 1900) + "-" +
   3120       String::FormatIntWidth2(time_struct->tm_mon + 1) + "-" +
   3121       String::FormatIntWidth2(time_struct->tm_mday) + "T" +
   3122       String::FormatIntWidth2(time_struct->tm_hour) + ":" +
   3123       String::FormatIntWidth2(time_struct->tm_min) + ":" +
   3124       String::FormatIntWidth2(time_struct->tm_sec);
   3125 }
   3126 
   3127 // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
   3128 void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
   3129                                                      const char* data) {
   3130   const char* segment = data;
   3131   *stream << "<![CDATA[";
   3132   for (;;) {
   3133     const char* const next_segment = strstr(segment, "]]>");
   3134     if (next_segment != NULL) {
   3135       stream->write(
   3136           segment, static_cast<std::streamsize>(next_segment - segment));
   3137       *stream << "]]>]]&gt;<![CDATA[";
   3138       segment = next_segment + strlen("]]>");
   3139     } else {
   3140       *stream << segment;
   3141       break;
   3142     }
   3143   }
   3144   *stream << "]]>";
   3145 }
   3146 
   3147 // Prints an XML representation of a TestInfo object.
   3148 // TODO(wan): There is also value in printing properties with the plain printer.
   3149 void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
   3150                                                  const char* test_case_name,
   3151                                                  const TestInfo& test_info) {
   3152   const TestResult& result = *test_info.result();
   3153   *stream << "    <testcase name=\""
   3154           << EscapeXmlAttribute(test_info.name()).c_str() << "\"";
   3155 
   3156   if (test_info.value_param() != NULL) {
   3157     *stream << " value_param=\"" << EscapeXmlAttribute(test_info.value_param())
   3158             << "\"";
   3159   }
   3160   if (test_info.type_param() != NULL) {
   3161     *stream << " type_param=\"" << EscapeXmlAttribute(test_info.type_param())
   3162             << "\"";
   3163   }
   3164 
   3165   *stream << " status=\""
   3166           << (test_info.should_run() ? "run" : "notrun")
   3167           << "\" time=\""
   3168           << FormatTimeInMillisAsSeconds(result.elapsed_time())
   3169           << "\" classname=\"" << EscapeXmlAttribute(test_case_name).c_str()
   3170           << "\"" << TestPropertiesAsXmlAttributes(result).c_str();
   3171 
   3172   int failures = 0;
   3173   for (int i = 0; i < result.total_part_count(); ++i) {
   3174     const TestPartResult& part = result.GetTestPartResult(i);
   3175     if (part.failed()) {
   3176       if (++failures == 1) {
   3177         *stream << ">\n";
   3178       }
   3179       const string location = internal::FormatCompilerIndependentFileLocation(
   3180           part.file_name(), part.line_number());
   3181       const string summary = location + "\n" + part.summary();
   3182       *stream << "      <failure message=\""
   3183               << EscapeXmlAttribute(summary.c_str())
   3184               << "\" type=\"\">";
   3185       const string detail = location + "\n" + part.message();
   3186       OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
   3187       *stream << "</failure>\n";
   3188     }
   3189   }
   3190 
   3191   if (failures == 0)
   3192     *stream << " />\n";
   3193   else
   3194     *stream << "    </testcase>\n";
   3195 }
   3196 
   3197 // Prints an XML representation of a TestCase object
   3198 void XmlUnitTestResultPrinter::PrintXmlTestCase(FILE* out,
   3199                                                 const TestCase& test_case) {
   3200   fprintf(out,
   3201           "  <testsuite name=\"%s\" tests=\"%d\" failures=\"%d\" "
   3202           "disabled=\"%d\" ",
   3203           EscapeXmlAttribute(test_case.name()).c_str(),
   3204           test_case.total_test_count(),
   3205           test_case.failed_test_count(),
   3206           test_case.disabled_test_count());
   3207   fprintf(out,
   3208           "errors=\"0\" time=\"%s\">\n",
   3209           FormatTimeInMillisAsSeconds(test_case.elapsed_time()).c_str());
   3210   for (int i = 0; i < test_case.total_test_count(); ++i) {
   3211     ::std::stringstream stream;
   3212     OutputXmlTestInfo(&stream, test_case.name(), *test_case.GetTestInfo(i));
   3213     fprintf(out, "%s", StringStreamToString(&stream).c_str());
   3214   }
   3215   fprintf(out, "  </testsuite>\n");
   3216 }
   3217 
   3218 // Prints an XML summary of unit_test to output stream out.
   3219 void XmlUnitTestResultPrinter::PrintXmlUnitTest(FILE* out,
   3220                                                 const UnitTest& unit_test) {
   3221   fprintf(out, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
   3222   fprintf(out,
   3223           "<testsuites tests=\"%d\" failures=\"%d\" disabled=\"%d\" "
   3224           "errors=\"0\" timestamp=\"%s\" time=\"%s\" ",
   3225           unit_test.total_test_count(),
   3226           unit_test.failed_test_count(),
   3227           unit_test.disabled_test_count(),
   3228           FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp()).c_str(),
   3229           FormatTimeInMillisAsSeconds(unit_test.elapsed_time()).c_str());
   3230   if (GTEST_FLAG(shuffle)) {
   3231     fprintf(out, "random_seed=\"%d\" ", unit_test.random_seed());
   3232   }
   3233   fprintf(out, "name=\"AllTests\">\n");
   3234   for (int i = 0; i < unit_test.total_test_case_count(); ++i)
   3235     PrintXmlTestCase(out, *unit_test.GetTestCase(i));
   3236   fprintf(out, "</testsuites>\n");
   3237 }
   3238 
   3239 // Produces a string representing the test properties in a result as space
   3240 // delimited XML attributes based on the property key="value" pairs.
   3241 std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
   3242     const TestResult& result) {
   3243   Message attributes;
   3244   for (int i = 0; i < result.test_property_count(); ++i) {
   3245     const TestProperty& property = result.GetTestProperty(i);
   3246     attributes << " " << property.key() << "="
   3247         << "\"" << EscapeXmlAttribute(property.value()) << "\"";
   3248   }
   3249   return attributes.GetString();
   3250 }
   3251 
   3252 // End XmlUnitTestResultPrinter
   3253 
   3254 #if GTEST_CAN_STREAM_RESULTS_
   3255 
   3256 // Checks if str contains '=', '&', '%' or '\n' characters. If yes,
   3257 // replaces them by "%xx" where xx is their hexadecimal value. For
   3258 // example, replaces "=" with "%3D".  This algorithm is O(strlen(str))
   3259 // in both time and space -- important as the input str may contain an
   3260 // arbitrarily long test failure message and stack trace.
   3261 string StreamingListener::UrlEncode(const char* str) {
   3262   string result;
   3263   result.reserve(strlen(str) + 1);
   3264   for (char ch = *str; ch != '\0'; ch = *++str) {
   3265     switch (ch) {
   3266       case '%':
   3267       case '=':
   3268       case '&':
   3269       case '\n':
   3270         result.append("%" + String::FormatByte(static_cast<unsigned char>(ch)));
   3271         break;
   3272       default:
   3273         result.push_back(ch);
   3274         break;
   3275     }
   3276   }
   3277   return result;
   3278 }
   3279 
   3280 void StreamingListener::SocketWriter::MakeConnection() {
   3281   GTEST_CHECK_(sockfd_ == -1)
   3282       << "MakeConnection() can't be called when there is already a connection.";
   3283 
   3284   addrinfo hints;
   3285   memset(&hints, 0, sizeof(hints));
   3286   hints.ai_family = AF_UNSPEC;    // To allow both IPv4 and IPv6 addresses.
   3287   hints.ai_socktype = SOCK_STREAM;
   3288   addrinfo* servinfo = NULL;
   3289 
   3290   // Use the getaddrinfo() to get a linked list of IP addresses for
   3291   // the given host name.
   3292   const int error_num = getaddrinfo(
   3293       host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
   3294   if (error_num != 0) {
   3295     GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: "
   3296                         << gai_strerror(error_num);
   3297   }
   3298 
   3299   // Loop through all the results and connect to the first we can.
   3300   for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != NULL;
   3301        cur_addr = cur_addr->ai_next) {
   3302     sockfd_ = socket(
   3303         cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol);
   3304     if (sockfd_ != -1) {
   3305       // Connect the client socket to the server socket.
   3306       if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
   3307         close(sockfd_);
   3308         sockfd_ = -1;
   3309       }
   3310     }
   3311   }
   3312 
   3313   freeaddrinfo(servinfo);  // all done with this structure
   3314 
   3315   if (sockfd_ == -1) {
   3316     GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to "
   3317                         << host_name_ << ":" << port_num_;
   3318   }
   3319 }
   3320 
   3321 // End of class Streaming Listener
   3322 #endif  // GTEST_CAN_STREAM_RESULTS__
   3323 
   3324 // Class ScopedTrace
   3325 
   3326 // Pushes the given source file location and message onto a per-thread
   3327 // trace stack maintained by Google Test.
   3328 ScopedTrace::ScopedTrace(const char* file, int line, const Message& message)
   3329     GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
   3330   TraceInfo trace;
   3331   trace.file = file;
   3332   trace.line = line;
   3333   trace.message = message.GetString();
   3334 
   3335   UnitTest::GetInstance()->PushGTestTrace(trace);
   3336 }
   3337 
   3338 // Pops the info pushed by the c'tor.
   3339 ScopedTrace::~ScopedTrace()
   3340     GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
   3341   UnitTest::GetInstance()->PopGTestTrace();
   3342 }
   3343 
   3344 
   3345 // class OsStackTraceGetter
   3346 
   3347 // Returns the current OS stack trace as an std::string.  Parameters:
   3348 //
   3349 //   max_depth  - the maximum number of stack frames to be included
   3350 //                in the trace.
   3351 //   skip_count - the number of top frames to be skipped; doesn't count
   3352 //                against max_depth.
   3353 //
   3354 string OsStackTraceGetter::CurrentStackTrace(int /* max_depth */,
   3355                                              int /* skip_count */)
   3356     GTEST_LOCK_EXCLUDED_(mutex_) {
   3357   return "";
   3358 }
   3359 
   3360 void OsStackTraceGetter::UponLeavingGTest()
   3361     GTEST_LOCK_EXCLUDED_(mutex_) {
   3362 }
   3363 
   3364 const char* const
   3365 OsStackTraceGetter::kElidedFramesMarker =
   3366     "... " GTEST_NAME_ " internal frames ...";
   3367 
   3368 }  // namespace internal
   3369 
   3370 // class TestEventListeners
   3371 
   3372 TestEventListeners::TestEventListeners()
   3373     : repeater_(new internal::TestEventRepeater()),
   3374       default_result_printer_(NULL),
   3375       default_xml_generator_(NULL) {
   3376 }
   3377 
   3378 TestEventListeners::~TestEventListeners() { delete repeater_; }
   3379 
   3380 // Returns the standard listener responsible for the default console
   3381 // output.  Can be removed from the listeners list to shut down default
   3382 // console output.  Note that removing this object from the listener list
   3383 // with Release transfers its ownership to the user.
   3384 void TestEventListeners::Append(TestEventListener* listener) {
   3385   repeater_->Append(listener);
   3386 }
   3387 
   3388 // Removes the given event listener from the list and returns it.  It then
   3389 // becomes the caller's responsibility to delete the listener. Returns
   3390 // NULL if the listener is not found in the list.
   3391 TestEventListener* TestEventListeners::Release(TestEventListener* listener) {
   3392   if (listener == default_result_printer_)
   3393     default_result_printer_ = NULL;
   3394   else if (listener == default_xml_generator_)
   3395     default_xml_generator_ = NULL;
   3396   return repeater_->Release(listener);
   3397 }
   3398 
   3399 // Returns repeater that broadcasts the TestEventListener events to all
   3400 // subscribers.
   3401 TestEventListener* TestEventListeners::repeater() { return repeater_; }
   3402 
   3403 // Sets the default_result_printer attribute to the provided listener.
   3404 // The listener is also added to the listener list and previous
   3405 // default_result_printer is removed from it and deleted. The listener can
   3406 // also be NULL in which case it will not be added to the list. Does
   3407 // nothing if the previous and the current listener objects are the same.
   3408 void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
   3409   if (default_result_printer_ != listener) {
   3410     // It is an error to pass this method a listener that is already in the
   3411     // list.
   3412     delete Release(default_result_printer_);
   3413     default_result_printer_ = listener;
   3414     if (listener != NULL)
   3415       Append(listener);
   3416   }
   3417 }
   3418 
   3419 // Sets the default_xml_generator attribute to the provided listener.  The
   3420 // listener is also added to the listener list and previous
   3421 // default_xml_generator is removed from it and deleted. The listener can
   3422 // also be NULL in which case it will not be added to the list. Does
   3423 // nothing if the previous and the current listener objects are the same.
   3424 void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
   3425   if (default_xml_generator_ != listener) {
   3426     // It is an error to pass this method a listener that is already in the
   3427     // list.
   3428     delete Release(default_xml_generator_);
   3429     default_xml_generator_ = listener;
   3430     if (listener != NULL)
   3431       Append(listener);
   3432   }
   3433 }
   3434 
   3435 // Controls whether events will be forwarded by the repeater to the
   3436 // listeners in the list.
   3437 bool TestEventListeners::EventForwardingEnabled() const {
   3438   return repeater_->forwarding_enabled();
   3439 }
   3440 
   3441 void TestEventListeners::SuppressEventForwarding() {
   3442   repeater_->set_forwarding_enabled(false);
   3443 }
   3444 
   3445 // class UnitTest
   3446 
   3447 // Gets the singleton UnitTest object.  The first time this method is
   3448 // called, a UnitTest object is constructed and returned.  Consecutive
   3449 // calls will return the same object.
   3450 //
   3451 // We don't protect this under mutex_ as a user is not supposed to
   3452 // call this before main() starts, from which point on the return
   3453 // value will never change.
   3454 UnitTest * UnitTest::GetInstance() {
   3455   // When compiled with MSVC 7.1 in optimized mode, destroying the
   3456   // UnitTest object upon exiting the program messes up the exit code,
   3457   // causing successful tests to appear failed.  We have to use a
   3458   // different implementation in this case to bypass the compiler bug.
   3459   // This implementation makes the compiler happy, at the cost of
   3460   // leaking the UnitTest object.
   3461 
   3462   // CodeGear C++Builder insists on a public destructor for the
   3463   // default implementation.  Use this implementation to keep good OO
   3464   // design with private destructor.
   3465 
   3466 #if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
   3467   static UnitTest* const instance = new UnitTest;
   3468   return instance;
   3469 #else
   3470   static UnitTest instance;
   3471   return &instance;
   3472 #endif  // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
   3473 }
   3474 
   3475 // Gets the number of successful test cases.
   3476 int UnitTest::successful_test_case_count() const {
   3477   return impl()->successful_test_case_count();
   3478 }
   3479 
   3480 // Gets the number of failed test cases.
   3481 int UnitTest::failed_test_case_count() const {
   3482   return impl()->failed_test_case_count();
   3483 }
   3484 
   3485 // Gets the number of all test cases.
   3486 int UnitTest::total_test_case_count() const {
   3487   return impl()->total_test_case_count();
   3488 }
   3489 
   3490 // Gets the number of all test cases that contain at least one test
   3491 // that should run.
   3492 int UnitTest::test_case_to_run_count() const {
   3493   return impl()->test_case_to_run_count();
   3494 }
   3495 
   3496 // Gets the number of successful tests.
   3497 int UnitTest::successful_test_count() const {
   3498   return impl()->successful_test_count();
   3499 }
   3500 
   3501 // Gets the number of failed tests.
   3502 int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
   3503 
   3504 // Gets the number of disabled tests.
   3505 int UnitTest::disabled_test_count() const {
   3506   return impl()->disabled_test_count();
   3507 }
   3508 
   3509 // Gets the number of all tests.
   3510 int UnitTest::total_test_count() const { return impl()->total_test_count(); }
   3511 
   3512 // Gets the number of tests that should run.
   3513 int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
   3514 
   3515 // Gets the time of the test program start, in ms from the start of the
   3516 // UNIX epoch.
   3517 internal::TimeInMillis UnitTest::start_timestamp() const {
   3518     return impl()->start_timestamp();
   3519 }
   3520 
   3521 // Gets the elapsed time, in milliseconds.
   3522 internal::TimeInMillis UnitTest::elapsed_time() const {
   3523   return impl()->elapsed_time();
   3524 }
   3525 
   3526 // Returns true iff the unit test passed (i.e. all test cases passed).
   3527 bool UnitTest::Passed() const { return impl()->Passed(); }
   3528 
   3529 // Returns true iff the unit test failed (i.e. some test case failed
   3530 // or something outside of all tests failed).
   3531 bool UnitTest::Failed() const { return impl()->Failed(); }
   3532 
   3533 // Gets the i-th test case among all the test cases. i can range from 0 to
   3534 // total_test_case_count() - 1. If i is not in that range, returns NULL.
   3535 const TestCase* UnitTest::GetTestCase(int i) const {
   3536   return impl()->GetTestCase(i);
   3537 }
   3538 
   3539 // Gets the i-th test case among all the test cases. i can range from 0 to
   3540 // total_test_case_count() - 1. If i is not in that range, returns NULL.
   3541 TestCase* UnitTest::GetMutableTestCase(int i) {
   3542   return impl()->GetMutableTestCase(i);
   3543 }
   3544 
   3545 // Returns the list of event listeners that can be used to track events
   3546 // inside Google Test.
   3547 TestEventListeners& UnitTest::listeners() {
   3548   return *impl()->listeners();
   3549 }
   3550 
   3551 // Registers and returns a global test environment.  When a test
   3552 // program is run, all global test environments will be set-up in the
   3553 // order they were registered.  After all tests in the program have
   3554 // finished, all global test environments will be torn-down in the
   3555 // *reverse* order they were registered.
   3556 //
   3557 // The UnitTest object takes ownership of the given environment.
   3558 //
   3559 // We don't protect this under mutex_, as we only support calling it
   3560 // from the main thread.
   3561 Environment* UnitTest::AddEnvironment(Environment* env) {
   3562   if (env == NULL) {
   3563     return NULL;
   3564   }
   3565 
   3566   impl_->environments().push_back(env);
   3567   return env;
   3568 }
   3569 
   3570 // Adds a TestPartResult to the current TestResult object.  All Google Test
   3571 // assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
   3572 // this to report their results.  The user code should use the
   3573 // assertion macros instead of calling this directly.
   3574 GTEST_LOCK_EXCLUDED_(mutex_)
   3575 void UnitTest::AddTestPartResult(
   3576     TestPartResult::Type result_type,
   3577     const char* file_name,
   3578     int line_number,
   3579     const std::string& message,
   3580     const std::string& os_stack_trace) {
   3581   Message msg;
   3582   msg << message;
   3583 
   3584   internal::MutexLock lock(&mutex_);
   3585   if (impl_->gtest_trace_stack().size() > 0) {
   3586     msg << "\n" << GTEST_NAME_ << " trace:";
   3587 
   3588     for (int i = static_cast<int>(impl_->gtest_trace_stack().size());
   3589          i > 0; --i) {
   3590       const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
   3591       msg << "\n" << internal::FormatFileLocation(trace.file, trace.line)
   3592           << " " << trace.message;
   3593     }
   3594   }
   3595 
   3596   if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) {
   3597     msg << internal::kStackTraceMarker << os_stack_trace;
   3598   }
   3599 
   3600   const TestPartResult result =
   3601     TestPartResult(result_type, file_name, line_number,
   3602                    msg.GetString().c_str());
   3603   impl_->GetTestPartResultReporterForCurrentThread()->
   3604       ReportTestPartResult(result);
   3605 
   3606   if (result_type != TestPartResult::kSuccess) {
   3607     // gtest_break_on_failure takes precedence over
   3608     // gtest_throw_on_failure.  This allows a user to set the latter
   3609     // in the code (perhaps in order to use Google Test assertions
   3610     // with another testing framework) and specify the former on the
   3611     // command line for debugging.
   3612     if (GTEST_FLAG(break_on_failure)) {
   3613 #if GTEST_OS_WINDOWS
   3614       // Using DebugBreak on Windows allows gtest to still break into a debugger
   3615       // when a failure happens and both the --gtest_break_on_failure and
   3616       // the --gtest_catch_exceptions flags are specified.
   3617       DebugBreak();
   3618 #else
   3619       // Dereference NULL through a volatile pointer to prevent the compiler
   3620       // from removing. We use this rather than abort() or __builtin_trap() for
   3621       // portability: Symbian doesn't implement abort() well, and some debuggers
   3622       // don't correctly trap abort().
   3623       *static_cast<volatile int*>(NULL) = 1;
   3624 #endif  // GTEST_OS_WINDOWS
   3625     } else if (GTEST_FLAG(throw_on_failure)) {
   3626 #if GTEST_HAS_EXCEPTIONS
   3627       throw internal::GoogleTestFailureException(result);
   3628 #else
   3629       // We cannot call abort() as it generates a pop-up in debug mode
   3630       // that cannot be suppressed in VC 7.1 or below.
   3631       exit(1);
   3632 #endif
   3633     }
   3634   }
   3635 }
   3636 
   3637 // Creates and adds a property to the current TestResult. If a property matching
   3638 // the supplied value already exists, updates its value instead.
   3639 void UnitTest::RecordPropertyForCurrentTest(const char* key,
   3640                                             const char* value) {
   3641   const TestProperty test_property(key, value);
   3642   impl_->current_test_result()->RecordProperty(test_property);
   3643 }
   3644 
   3645 // Runs all tests in this UnitTest object and prints the result.
   3646 // Returns 0 if successful, or 1 otherwise.
   3647 //
   3648 // We don't protect this under mutex_, as we only support calling it
   3649 // from the main thread.
   3650 int UnitTest::Run() {
   3651   // Captures the value of GTEST_FLAG(catch_exceptions).  This value will be
   3652   // used for the duration of the program.
   3653   impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions));
   3654 
   3655 #if GTEST_HAS_SEH
   3656   const bool in_death_test_child_process =
   3657       internal::GTEST_FLAG(internal_run_death_test).length() > 0;
   3658 
   3659   // Either the user wants Google Test to catch exceptions thrown by the
   3660   // tests or this is executing in the context of death test child
   3661   // process. In either case the user does not want to see pop-up dialogs
   3662   // about crashes - they are expected.
   3663   if (impl()->catch_exceptions() || in_death_test_child_process) {
   3664 # if !GTEST_OS_WINDOWS_MOBILE
   3665     // SetErrorMode doesn't exist on CE.
   3666     SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
   3667                  SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
   3668 # endif  // !GTEST_OS_WINDOWS_MOBILE
   3669 
   3670 # if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
   3671     // Death test children can be terminated with _abort().  On Windows,
   3672     // _abort() can show a dialog with a warning message.  This forces the
   3673     // abort message to go to stderr instead.
   3674     _set_error_mode(_OUT_TO_STDERR);
   3675 # endif
   3676 
   3677 # if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
   3678     // In the debug version, Visual Studio pops up a separate dialog
   3679     // offering a choice to debug the aborted program. We need to suppress
   3680     // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
   3681     // executed. Google Test will notify the user of any unexpected
   3682     // failure via stderr.
   3683     //
   3684     // VC++ doesn't define _set_abort_behavior() prior to the version 8.0.
   3685     // Users of prior VC versions shall suffer the agony and pain of
   3686     // clicking through the countless debug dialogs.
   3687     // TODO(vladl (at) google.com): find a way to suppress the abort dialog() in the
   3688     // debug mode when compiled with VC 7.1 or lower.
   3689     if (!GTEST_FLAG(break_on_failure))
   3690       _set_abort_behavior(
   3691           0x0,                                    // Clear the following flags:
   3692           _WRITE_ABORT_MSG | _CALL_REPORTFAULT);  // pop-up window, core dump.
   3693 # endif
   3694   }
   3695 #endif  // GTEST_HAS_SEH
   3696 
   3697   return internal::HandleExceptionsInMethodIfSupported(
   3698       impl(),
   3699       &internal::UnitTestImpl::RunAllTests,
   3700       "auxiliary test code (environments or event listeners)") ? 0 : 1;
   3701 }
   3702 
   3703 // Returns the working directory when the first TEST() or TEST_F() was
   3704 // executed.
   3705 const char* UnitTest::original_working_dir() const {
   3706   return impl_->original_working_dir_.c_str();
   3707 }
   3708 
   3709 // Returns the TestCase object for the test that's currently running,
   3710 // or NULL if no test is running.
   3711 const TestCase* UnitTest::current_test_case() const
   3712     GTEST_LOCK_EXCLUDED_(mutex_) {
   3713   internal::MutexLock lock(&mutex_);
   3714   return impl_->current_test_case();
   3715 }
   3716 
   3717 // Returns the TestInfo object for the test that's currently running,
   3718 // or NULL if no test is running.
   3719 const TestInfo* UnitTest::current_test_info() const
   3720     GTEST_LOCK_EXCLUDED_(mutex_) {
   3721   internal::MutexLock lock(&mutex_);
   3722   return impl_->current_test_info();
   3723 }
   3724 
   3725 // Returns the random seed used at the start of the current test run.
   3726 int UnitTest::random_seed() const { return impl_->random_seed(); }
   3727 
   3728 #if GTEST_HAS_PARAM_TEST
   3729 // Returns ParameterizedTestCaseRegistry object used to keep track of
   3730 // value-parameterized tests and instantiate and register them.
   3731 internal::ParameterizedTestCaseRegistry&
   3732     UnitTest::parameterized_test_registry()
   3733         GTEST_LOCK_EXCLUDED_(mutex_) {
   3734   return impl_->parameterized_test_registry();
   3735 }
   3736 #endif  // GTEST_HAS_PARAM_TEST
   3737 
   3738 // Creates an empty UnitTest.
   3739 UnitTest::UnitTest() {
   3740   impl_ = new internal::UnitTestImpl(this);
   3741 }
   3742 
   3743 // Destructor of UnitTest.
   3744 UnitTest::~UnitTest() {
   3745   delete impl_;
   3746 }
   3747 
   3748 // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
   3749 // Google Test trace stack.
   3750 void UnitTest::PushGTestTrace(const internal::TraceInfo& trace)
   3751     GTEST_LOCK_EXCLUDED_(mutex_) {
   3752   internal::MutexLock lock(&mutex_);
   3753   impl_->gtest_trace_stack().push_back(trace);
   3754 }
   3755 
   3756 // Pops a trace from the per-thread Google Test trace stack.
   3757 void UnitTest::PopGTestTrace()
   3758     GTEST_LOCK_EXCLUDED_(mutex_) {
   3759   internal::MutexLock lock(&mutex_);
   3760   impl_->gtest_trace_stack().pop_back();
   3761 }
   3762 
   3763 namespace internal {
   3764 
   3765 UnitTestImpl::UnitTestImpl(UnitTest* parent)
   3766     : parent_(parent),
   3767 #ifdef _MSC_VER
   3768 # pragma warning(push)                    // Saves the current warning state.
   3769 # pragma warning(disable:4355)            // Temporarily disables warning 4355
   3770                                          // (using this in initializer).
   3771       default_global_test_part_result_reporter_(this),
   3772       default_per_thread_test_part_result_reporter_(this),
   3773 # pragma warning(pop)                     // Restores the warning state again.
   3774 #else
   3775       default_global_test_part_result_reporter_(this),
   3776       default_per_thread_test_part_result_reporter_(this),
   3777 #endif  // _MSC_VER
   3778       global_test_part_result_repoter_(
   3779           &default_global_test_part_result_reporter_),
   3780       per_thread_test_part_result_reporter_(
   3781           &default_per_thread_test_part_result_reporter_),
   3782 #if GTEST_HAS_PARAM_TEST
   3783       parameterized_test_registry_(),
   3784       parameterized_tests_registered_(false),
   3785 #endif  // GTEST_HAS_PARAM_TEST
   3786       last_death_test_case_(-1),
   3787       current_test_case_(NULL),
   3788       current_test_info_(NULL),
   3789       ad_hoc_test_result_(),
   3790       os_stack_trace_getter_(NULL),
   3791       post_flag_parse_init_performed_(false),
   3792       random_seed_(0),  // Will be overridden by the flag before first use.
   3793       random_(0),  // Will be reseeded before first use.
   3794       start_timestamp_(0),
   3795       elapsed_time_(0),
   3796 #if GTEST_HAS_DEATH_TEST
   3797       internal_run_death_test_flag_(NULL),
   3798       death_test_factory_(new DefaultDeathTestFactory),
   3799 #endif
   3800       // Will be overridden by the flag before first use.
   3801       catch_exceptions_(false) {
   3802   listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);
   3803 }
   3804 
   3805 UnitTestImpl::~UnitTestImpl() {
   3806   // Deletes every TestCase.
   3807   ForEach(test_cases_, internal::Delete<TestCase>);
   3808 
   3809   // Deletes every Environment.
   3810   ForEach(environments_, internal::Delete<Environment>);
   3811 
   3812   delete os_stack_trace_getter_;
   3813 }
   3814 
   3815 #if GTEST_HAS_DEATH_TEST
   3816 // Disables event forwarding if the control is currently in a death test
   3817 // subprocess. Must not be called before InitGoogleTest.
   3818 void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
   3819   if (internal_run_death_test_flag_.get() != NULL)
   3820     listeners()->SuppressEventForwarding();
   3821 }
   3822 #endif  // GTEST_HAS_DEATH_TEST
   3823 
   3824 // Initializes event listeners performing XML output as specified by
   3825 // UnitTestOptions. Must not be called before InitGoogleTest.
   3826 void UnitTestImpl::ConfigureXmlOutput() {
   3827   const std::string& output_format = UnitTestOptions::GetOutputFormat();
   3828   if (output_format == "xml") {
   3829     listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
   3830         UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
   3831   } else if (output_format != "") {
   3832     printf("WARNING: unrecognized output format \"%s\" ignored.\n",
   3833            output_format.c_str());
   3834     fflush(stdout);
   3835   }
   3836 }
   3837 
   3838 #if GTEST_CAN_STREAM_RESULTS_
   3839 // Initializes event listeners for streaming test results in string form.
   3840 // Must not be called before InitGoogleTest.
   3841 void UnitTestImpl::ConfigureStreamingOutput() {
   3842   const std::string& target = GTEST_FLAG(stream_result_to);
   3843   if (!target.empty()) {
   3844     const size_t pos = target.find(':');
   3845     if (pos != std::string::npos) {
   3846       listeners()->Append(new StreamingListener(target.substr(0, pos),
   3847                                                 target.substr(pos+1)));
   3848     } else {
   3849       printf("WARNING: unrecognized streaming target \"%s\" ignored.\n",
   3850              target.c_str());
   3851       fflush(stdout);
   3852     }
   3853   }
   3854 }
   3855 #endif  // GTEST_CAN_STREAM_RESULTS_
   3856 
   3857 // Performs initialization dependent upon flag values obtained in
   3858 // ParseGoogleTestFlagsOnly.  Is called from InitGoogleTest after the call to
   3859 // ParseGoogleTestFlagsOnly.  In case a user neglects to call InitGoogleTest
   3860 // this function is also called from RunAllTests.  Since this function can be
   3861 // called more than once, it has to be idempotent.
   3862 void UnitTestImpl::PostFlagParsingInit() {
   3863   // Ensures that this function does not execute more than once.
   3864   if (!post_flag_parse_init_performed_) {
   3865     post_flag_parse_init_performed_ = true;
   3866 
   3867 #if GTEST_HAS_DEATH_TEST
   3868     InitDeathTestSubprocessControlInfo();
   3869     SuppressTestEventsIfInSubprocess();
   3870 #endif  // GTEST_HAS_DEATH_TEST
   3871 
   3872     // Registers parameterized tests. This makes parameterized tests
   3873     // available to the UnitTest reflection API without running
   3874     // RUN_ALL_TESTS.
   3875     RegisterParameterizedTests();
   3876 
   3877     // Configures listeners for XML output. This makes it possible for users
   3878     // to shut down the default XML output before invoking RUN_ALL_TESTS.
   3879     ConfigureXmlOutput();
   3880 
   3881 #if GTEST_CAN_STREAM_RESULTS_
   3882     // Configures listeners for streaming test results to the specified server.
   3883     ConfigureStreamingOutput();
   3884 #endif  // GTEST_CAN_STREAM_RESULTS_
   3885   }
   3886 }
   3887 
   3888 // A predicate that checks the name of a TestCase against a known
   3889 // value.
   3890 //
   3891 // This is used for implementation of the UnitTest class only.  We put
   3892 // it in the anonymous namespace to prevent polluting the outer
   3893 // namespace.
   3894 //
   3895 // TestCaseNameIs is copyable.
   3896 class TestCaseNameIs {
   3897  public:
   3898   // Constructor.
   3899   explicit TestCaseNameIs(const std::string& name)
   3900       : name_(name) {}
   3901 
   3902   // Returns true iff the name of test_case matches name_.
   3903   bool operator()(const TestCase* test_case) const {
   3904     return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0;
   3905   }
   3906 
   3907  private:
   3908   std::string name_;
   3909 };
   3910 
   3911 // Finds and returns a TestCase with the given name.  If one doesn't
   3912 // exist, creates one and returns it.  It's the CALLER'S
   3913 // RESPONSIBILITY to ensure that this function is only called WHEN THE
   3914 // TESTS ARE NOT SHUFFLED.
   3915 //
   3916 // Arguments:
   3917 //
   3918 //   test_case_name: name of the test case
   3919 //   type_param:     the name of the test case's type parameter, or NULL if
   3920 //                   this is not a typed or a type-parameterized test case.
   3921 //   set_up_tc:      pointer to the function that sets up the test case
   3922 //   tear_down_tc:   pointer to the function that tears down the test case
   3923 TestCase* UnitTestImpl::GetTestCase(const char* test_case_name,
   3924                                     const char* type_param,
   3925                                     Test::SetUpTestCaseFunc set_up_tc,
   3926                                     Test::TearDownTestCaseFunc tear_down_tc) {
   3927   // Can we find a TestCase with the given name?
   3928   const std::vector<TestCase*>::const_iterator test_case =
   3929       std::find_if(test_cases_.begin(), test_cases_.end(),
   3930                    TestCaseNameIs(test_case_name));
   3931 
   3932   if (test_case != test_cases_.end())
   3933     return *test_case;
   3934 
   3935   // No.  Let's create one.
   3936   TestCase* const new_test_case =
   3937       new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc);
   3938 
   3939   // Is this a death test case?
   3940   if (internal::UnitTestOptions::MatchesFilter(test_case_name,
   3941                                                kDeathTestCaseFilter)) {
   3942     // Yes.  Inserts the test case after the last death test case
   3943     // defined so far.  This only works when the test cases haven't
   3944     // been shuffled.  Otherwise we may end up running a death test
   3945     // after a non-death test.
   3946     ++last_death_test_case_;
   3947     test_cases_.insert(test_cases_.begin() + last_death_test_case_,
   3948                        new_test_case);
   3949   } else {
   3950     // No.  Appends to the end of the list.
   3951     test_cases_.push_back(new_test_case);
   3952   }
   3953 
   3954   test_case_indices_.push_back(static_cast<int>(test_case_indices_.size()));
   3955   return new_test_case;
   3956 }
   3957 
   3958 // Helpers for setting up / tearing down the given environment.  They
   3959 // are for use in the ForEach() function.
   3960 static void SetUpEnvironment(Environment* env) { env->SetUp(); }
   3961 static void TearDownEnvironment(Environment* env) { env->TearDown(); }
   3962 
   3963 // Runs all tests in this UnitTest object, prints the result, and
   3964 // returns true if all tests are successful.  If any exception is
   3965 // thrown during a test, the test is considered to be failed, but the
   3966 // rest of the tests will still be run.
   3967 //
   3968 // When parameterized tests are enabled, it expands and registers
   3969 // parameterized tests first in RegisterParameterizedTests().
   3970 // All other functions called from RunAllTests() may safely assume that
   3971 // parameterized tests are ready to be counted and run.
   3972 bool UnitTestImpl::RunAllTests() {
   3973   // Makes sure InitGoogleTest() was called.
   3974   if (!GTestIsInitialized()) {
   3975     printf("%s",
   3976            "\nThis test program did NOT call ::testing::InitGoogleTest "
   3977            "before calling RUN_ALL_TESTS().  Please fix it.\n");
   3978     return false;
   3979   }
   3980 
   3981   // Do not run any test if the --help flag was specified.
   3982   if (g_help_flag)
   3983     return true;
   3984 
   3985   // Repeats the call to the post-flag parsing initialization in case the
   3986   // user didn't call InitGoogleTest.
   3987   PostFlagParsingInit();
   3988 
   3989   // Even if sharding is not on, test runners may want to use the
   3990   // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
   3991   // protocol.
   3992   internal::WriteToShardStatusFileIfNeeded();
   3993 
   3994   // True iff we are in a subprocess for running a thread-safe-style
   3995   // death test.
   3996   bool in_subprocess_for_death_test = false;
   3997 
   3998 #if GTEST_HAS_DEATH_TEST
   3999   in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL);
   4000 #endif  // GTEST_HAS_DEATH_TEST
   4001 
   4002   const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
   4003                                         in_subprocess_for_death_test);
   4004 
   4005   // Compares the full test names with the filter to decide which
   4006   // tests to run.
   4007   const bool has_tests_to_run = FilterTests(should_shard
   4008                                               ? HONOR_SHARDING_PROTOCOL
   4009                                               : IGNORE_SHARDING_PROTOCOL) > 0;
   4010 
   4011   // Lists the tests and exits if the --gtest_list_tests flag was specified.
   4012   if (GTEST_FLAG(list_tests)) {
   4013     // This must be called *after* FilterTests() has been called.
   4014     ListTestsMatchingFilter();
   4015     return true;
   4016   }
   4017 
   4018   random_seed_ = GTEST_FLAG(shuffle) ?
   4019       GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;
   4020 
   4021   // True iff at least one test has failed.
   4022   bool failed = false;
   4023 
   4024   TestEventListener* repeater = listeners()->repeater();
   4025 
   4026   start_timestamp_ = GetTimeInMillis();
   4027   repeater->OnTestProgramStart(*parent_);
   4028 
   4029   // How many times to repeat the tests?  We don't want to repeat them
   4030   // when we are inside the subprocess of a death test.
   4031   const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);
   4032   // Repeats forever if the repeat count is negative.
   4033   const bool forever = repeat < 0;
   4034   for (int i = 0; forever || i != repeat; i++) {
   4035     // We want to preserve failures generated by ad-hoc test
   4036     // assertions executed before RUN_ALL_TESTS().
   4037     ClearNonAdHocTestResult();
   4038 
   4039     const TimeInMillis start = GetTimeInMillis();
   4040 
   4041     // Shuffles test cases and tests if requested.
   4042     if (has_tests_to_run && GTEST_FLAG(shuffle)) {
   4043       random()->Reseed(random_seed_);
   4044       // This should be done before calling OnTestIterationStart(),
   4045       // such that a test event listener can see the actual test order
   4046       // in the event.
   4047       ShuffleTests();
   4048     }
   4049 
   4050     // Tells the unit test event listeners that the tests are about to start.
   4051     repeater->OnTestIterationStart(*parent_, i);
   4052 
   4053     // Runs each test case if there is at least one test to run.
   4054     if (has_tests_to_run) {
   4055       // Sets up all environments beforehand.
   4056       repeater->OnEnvironmentsSetUpStart(*parent_);
   4057       ForEach(environments_, SetUpEnvironment);
   4058       repeater->OnEnvironmentsSetUpEnd(*parent_);
   4059 
   4060       // Runs the tests only if there was no fatal failure during global
   4061       // set-up.
   4062       if (!Test::HasFatalFailure()) {
   4063         for (int test_index = 0; test_index < total_test_case_count();
   4064              test_index++) {
   4065           GetMutableTestCase(test_index)->Run();
   4066         }
   4067       }
   4068 
   4069       // Tears down all environments in reverse order afterwards.
   4070       repeater->OnEnvironmentsTearDownStart(*parent_);
   4071       std::for_each(environments_.rbegin(), environments_.rend(),
   4072                     TearDownEnvironment);
   4073       repeater->OnEnvironmentsTearDownEnd(*parent_);
   4074     }
   4075 
   4076     elapsed_time_ = GetTimeInMillis() - start;
   4077 
   4078     // Tells the unit test event listener that the tests have just finished.
   4079     repeater->OnTestIterationEnd(*parent_, i);
   4080 
   4081     // Gets the result and clears it.
   4082     if (!Passed()) {
   4083       failed = true;
   4084     }
   4085 
   4086     // Restores the original test order after the iteration.  This
   4087     // allows the user to quickly repro a failure that happens in the
   4088     // N-th iteration without repeating the first (N - 1) iterations.
   4089     // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in
   4090     // case the user somehow changes the value of the flag somewhere
   4091     // (it's always safe to unshuffle the tests).
   4092     UnshuffleTests();
   4093 
   4094     if (GTEST_FLAG(shuffle)) {
   4095       // Picks a new random seed for each iteration.
   4096       random_seed_ = GetNextRandomSeed(random_seed_);
   4097     }
   4098   }
   4099 
   4100   repeater->OnTestProgramEnd(*parent_);
   4101 
   4102   return !failed;
   4103 }
   4104 
   4105 // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
   4106 // if the variable is present. If a file already exists at this location, this
   4107 // function will write over it. If the variable is present, but the file cannot
   4108 // be created, prints an error and exits.
   4109 void WriteToShardStatusFileIfNeeded() {
   4110   const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);
   4111   if (test_shard_file != NULL) {
   4112     FILE* const file = posix::FOpen(test_shard_file, "w");
   4113     if (file == NULL) {
   4114       ColoredPrintf(COLOR_RED,
   4115                     "Could not write to the test shard status file \"%s\" "
   4116                     "specified by the %s environment variable.\n",
   4117                     test_shard_file, kTestShardStatusFile);
   4118       fflush(stdout);
   4119       exit(EXIT_FAILURE);
   4120     }
   4121     fclose(file);
   4122   }
   4123 }
   4124 
   4125 // Checks whether sharding is enabled by examining the relevant
   4126 // environment variable values. If the variables are present,
   4127 // but inconsistent (i.e., shard_index >= total_shards), prints
   4128 // an error and exits. If in_subprocess_for_death_test, sharding is
   4129 // disabled because it must only be applied to the original test
   4130 // process. Otherwise, we could filter out death tests we intended to execute.
   4131 bool ShouldShard(const char* total_shards_env,
   4132                  const char* shard_index_env,
   4133                  bool in_subprocess_for_death_test) {
   4134   if (in_subprocess_for_death_test) {
   4135     return false;
   4136   }
   4137 
   4138   const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1);
   4139   const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1);
   4140 
   4141   if (total_shards == -1 && shard_index == -1) {
   4142     return false;
   4143   } else if (total_shards == -1 && shard_index != -1) {
   4144     const Message msg = Message()
   4145       << "Invalid environment variables: you have "
   4146       << kTestShardIndex << " = " << shard_index
   4147       << ", but have left " << kTestTotalShards << " unset.\n";
   4148     ColoredPrintf(COLOR_RED, msg.GetString().c_str());
   4149     fflush(stdout);
   4150     exit(EXIT_FAILURE);
   4151   } else if (total_shards != -1 && shard_index == -1) {
   4152     const Message msg = Message()
   4153       << "Invalid environment variables: you have "
   4154       << kTestTotalShards << " = " << total_shards
   4155       << ", but have left " << kTestShardIndex << " unset.\n";
   4156     ColoredPrintf(COLOR_RED, msg.GetString().c_str());
   4157     fflush(stdout);
   4158     exit(EXIT_FAILURE);
   4159   } else if (shard_index < 0 || shard_index >= total_shards) {
   4160     const Message msg = Message()
   4161       << "Invalid environment variables: we require 0 <= "
   4162       << kTestShardIndex << " < " << kTestTotalShards
   4163       << ", but you have " << kTestShardIndex << "=" << shard_index
   4164       << ", " << kTestTotalShards << "=" << total_shards << ".\n";
   4165     ColoredPrintf(COLOR_RED, msg.GetString().c_str());
   4166     fflush(stdout);
   4167     exit(EXIT_FAILURE);
   4168   }
   4169 
   4170   return total_shards > 1;
   4171 }
   4172 
   4173 // Parses the environment variable var as an Int32. If it is unset,
   4174 // returns default_val. If it is not an Int32, prints an error
   4175 // and aborts.
   4176 Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) {
   4177   const char* str_val = posix::GetEnv(var);
   4178   if (str_val == NULL) {
   4179     return default_val;
   4180   }
   4181 
   4182   Int32 result;
   4183   if (!ParseInt32(Message() << "The value of environment variable " << var,
   4184                   str_val, &result)) {
   4185     exit(EXIT_FAILURE);
   4186   }
   4187   return result;
   4188 }
   4189 
   4190 // Given the total number of shards, the shard index, and the test id,
   4191 // returns true iff the test should be run on this shard. The test id is
   4192 // some arbitrary but unique non-negative integer assigned to each test
   4193 // method. Assumes that 0 <= shard_index < total_shards.
   4194 bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
   4195   return (test_id % total_shards) == shard_index;
   4196 }
   4197 
   4198 // Compares the name of each test with the user-specified filter to
   4199 // decide whether the test should be run, then records the result in
   4200 // each TestCase and TestInfo object.
   4201 // If shard_tests == true, further filters tests based on sharding
   4202 // variables in the environment - see
   4203 // http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide.
   4204 // Returns the number of tests that should run.
   4205 int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
   4206   const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?
   4207       Int32FromEnvOrDie(kTestTotalShards, -1) : -1;
   4208   const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?
   4209       Int32FromEnvOrDie(kTestShardIndex, -1) : -1;
   4210 
   4211   // num_runnable_tests are the number of tests that will
   4212   // run across all shards (i.e., match filter and are not disabled).
   4213   // num_selected_tests are the number of tests to be run on
   4214   // this shard.
   4215   int num_runnable_tests = 0;
   4216   int num_selected_tests = 0;
   4217   for (size_t i = 0; i < test_cases_.size(); i++) {
   4218     TestCase* const test_case = test_cases_[i];
   4219     const std::string &test_case_name = test_case->name();
   4220     test_case->set_should_run(false);
   4221 
   4222     for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
   4223       TestInfo* const test_info = test_case->test_info_list()[j];
   4224       const std::string test_name(test_info->name());
   4225       // A test is disabled if test case name or test name matches
   4226       // kDisableTestFilter.
   4227       const bool is_disabled =
   4228           internal::UnitTestOptions::MatchesFilter(test_case_name,
   4229                                                    kDisableTestFilter) ||
   4230           internal::UnitTestOptions::MatchesFilter(test_name,
   4231                                                    kDisableTestFilter);
   4232       test_info->is_disabled_ = is_disabled;
   4233 
   4234       const bool matches_filter =
   4235           internal::UnitTestOptions::FilterMatchesTest(test_case_name,
   4236                                                        test_name);
   4237       test_info->matches_filter_ = matches_filter;
   4238 
   4239       const bool is_runnable =
   4240           (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
   4241           matches_filter;
   4242 
   4243       const bool is_selected = is_runnable &&
   4244           (shard_tests == IGNORE_SHARDING_PROTOCOL ||
   4245            ShouldRunTestOnShard(total_shards, shard_index,
   4246                                 num_runnable_tests));
   4247 
   4248       num_runnable_tests += is_runnable;
   4249       num_selected_tests += is_selected;
   4250 
   4251       test_info->should_run_ = is_selected;
   4252       test_case->set_should_run(test_case->should_run() || is_selected);
   4253     }
   4254   }
   4255   return num_selected_tests;
   4256 }
   4257 
   4258 // Prints the names of the tests matching the user-specified filter flag.
   4259 void UnitTestImpl::ListTestsMatchingFilter() {
   4260   for (size_t i = 0; i < test_cases_.size(); i++) {
   4261     const TestCase* const test_case = test_cases_[i];
   4262     bool printed_test_case_name = false;
   4263 
   4264     for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
   4265       const TestInfo* const test_info =
   4266           test_case->test_info_list()[j];
   4267       if (test_info->matches_filter_) {
   4268         if (!printed_test_case_name) {
   4269           printed_test_case_name = true;
   4270           printf("%s.\n", test_case->name());
   4271         }
   4272         printf("  %s\n", test_info->name());
   4273       }
   4274     }
   4275   }
   4276   fflush(stdout);
   4277 }
   4278 
   4279 // Sets the OS stack trace getter.
   4280 //
   4281 // Does nothing if the input and the current OS stack trace getter are
   4282 // the same; otherwise, deletes the old getter and makes the input the
   4283 // current getter.
   4284 void UnitTestImpl::set_os_stack_trace_getter(
   4285     OsStackTraceGetterInterface* getter) {
   4286   if (os_stack_trace_getter_ != getter) {
   4287     delete os_stack_trace_getter_;
   4288     os_stack_trace_getter_ = getter;
   4289   }
   4290 }
   4291 
   4292 // Returns the current OS stack trace getter if it is not NULL;
   4293 // otherwise, creates an OsStackTraceGetter, makes it the current
   4294 // getter, and returns it.
   4295 OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
   4296   if (os_stack_trace_getter_ == NULL) {
   4297     os_stack_trace_getter_ = new OsStackTraceGetter;
   4298   }
   4299 
   4300   return os_stack_trace_getter_;
   4301 }
   4302 
   4303 // Returns the TestResult for the test that's currently running, or
   4304 // the TestResult for the ad hoc test if no test is running.
   4305 TestResult* UnitTestImpl::current_test_result() {
   4306   return current_test_info_ ?
   4307       &(current_test_info_->result_) : &ad_hoc_test_result_;
   4308 }
   4309 
   4310 // Shuffles all test cases, and the tests within each test case,
   4311 // making sure that death tests are still run first.
   4312 void UnitTestImpl::ShuffleTests() {
   4313   // Shuffles the death test cases.
   4314   ShuffleRange(random(), 0, last_death_test_case_ + 1, &test_case_indices_);
   4315 
   4316   // Shuffles the non-death test cases.
   4317   ShuffleRange(random(), last_death_test_case_ + 1,
   4318                static_cast<int>(test_cases_.size()), &test_case_indices_);
   4319 
   4320   // Shuffles the tests inside each test case.
   4321   for (size_t i = 0; i < test_cases_.size(); i++) {
   4322     test_cases_[i]->ShuffleTests(random());
   4323   }
   4324 }
   4325 
   4326 // Restores the test cases and tests to their order before the first shuffle.
   4327 void UnitTestImpl::UnshuffleTests() {
   4328   for (size_t i = 0; i < test_cases_.size(); i++) {
   4329     // Unshuffles the tests in each test case.
   4330     test_cases_[i]->UnshuffleTests();
   4331     // Resets the index of each test case.
   4332     test_case_indices_[i] = static_cast<int>(i);
   4333   }
   4334 }
   4335 
   4336 // Returns the current OS stack trace as an std::string.
   4337 //
   4338 // The maximum number of stack frames to be included is specified by
   4339 // the gtest_stack_trace_depth flag.  The skip_count parameter
   4340 // specifies the number of top frames to be skipped, which doesn't
   4341 // count against the number of frames to be included.
   4342 //
   4343 // For example, if Foo() calls Bar(), which in turn calls
   4344 // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
   4345 // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
   4346 std::string GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/,
   4347                                             int skip_count) {
   4348   // We pass skip_count + 1 to skip this wrapper function in addition
   4349   // to what the user really wants to skip.
   4350   return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
   4351 }
   4352 
   4353 // Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to
   4354 // suppress unreachable code warnings.
   4355 namespace {
   4356 class ClassUniqueToAlwaysTrue {};
   4357 }
   4358 
   4359 bool IsTrue(bool condition) { return condition; }
   4360 
   4361 bool AlwaysTrue() {
   4362 #if GTEST_HAS_EXCEPTIONS
   4363   // This condition is always false so AlwaysTrue() never actually throws,
   4364   // but it makes the compiler think that it may throw.
   4365   if (IsTrue(false))
   4366     throw ClassUniqueToAlwaysTrue();
   4367 #endif  // GTEST_HAS_EXCEPTIONS
   4368   return true;
   4369 }
   4370 
   4371 // If *pstr starts with the given prefix, modifies *pstr to be right
   4372 // past the prefix and returns true; otherwise leaves *pstr unchanged
   4373 // and returns false.  None of pstr, *pstr, and prefix can be NULL.
   4374 bool SkipPrefix(const char* prefix, const char** pstr) {
   4375   const size_t prefix_len = strlen(prefix);
   4376   if (strncmp(*pstr, prefix, prefix_len) == 0) {
   4377     *pstr += prefix_len;
   4378     return true;
   4379   }
   4380   return false;
   4381 }
   4382 
   4383 // Parses a string as a command line flag.  The string should have
   4384 // the format "--flag=value".  When def_optional is true, the "=value"
   4385 // part can be omitted.
   4386 //
   4387 // Returns the value of the flag, or NULL if the parsing failed.
   4388 const char* ParseFlagValue(const char* str,
   4389                            const char* flag,
   4390                            bool def_optional) {
   4391   // str and flag must not be NULL.
   4392   if (str == NULL || flag == NULL) return NULL;
   4393 
   4394   // The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
   4395   const std::string flag_str = std::string("--") + GTEST_FLAG_PREFIX_ + flag;
   4396   const size_t flag_len = flag_str.length();
   4397   if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;
   4398 
   4399   // Skips the flag name.
   4400   const char* flag_end = str + flag_len;
   4401 
   4402   // When def_optional is true, it's OK to not have a "=value" part.
   4403   if (def_optional && (flag_end[0] == '\0')) {
   4404     return flag_end;
   4405   }
   4406 
   4407   // If def_optional is true and there are more characters after the
   4408   // flag name, or if def_optional is false, there must be a '=' after
   4409   // the flag name.
   4410   if (flag_end[0] != '=') return NULL;
   4411 
   4412   // Returns the string after "=".
   4413   return flag_end + 1;
   4414 }
   4415 
   4416 // Parses a string for a bool flag, in the form of either
   4417 // "--flag=value" or "--flag".
   4418 //
   4419 // In the former case, the value is taken as true as long as it does
   4420 // not start with '0', 'f', or 'F'.
   4421 //
   4422 // In the latter case, the value is taken as true.
   4423 //
   4424 // On success, stores the value of the flag in *value, and returns
   4425 // true.  On failure, returns false without changing *value.
   4426 bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
   4427   // Gets the value of the flag as a string.
   4428   const char* const value_str = ParseFlagValue(str, flag, true);
   4429 
   4430   // Aborts if the parsing failed.
   4431   if (value_str == NULL) return false;
   4432 
   4433   // Converts the string value to a bool.
   4434   *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
   4435   return true;
   4436 }
   4437 
   4438 // Parses a string for an Int32 flag, in the form of
   4439 // "--flag=value".
   4440 //
   4441 // On success, stores the value of the flag in *value, and returns
   4442 // true.  On failure, returns false without changing *value.
   4443 bool ParseInt32Flag(const char* str, const char* flag, Int32* value) {
   4444   // Gets the value of the flag as a string.
   4445   const char* const value_str = ParseFlagValue(str, flag, false);
   4446 
   4447   // Aborts if the parsing failed.
   4448   if (value_str == NULL) return false;
   4449 
   4450   // Sets *value to the value of the flag.
   4451   return ParseInt32(Message() << "The value of flag --" << flag,
   4452                     value_str, value);
   4453 }
   4454 
   4455 // Parses a string for a string flag, in the form of
   4456 // "--flag=value".
   4457 //
   4458 // On success, stores the value of the flag in *value, and returns
   4459 // true.  On failure, returns false without changing *value.
   4460 bool ParseStringFlag(const char* str, const char* flag, std::string* value) {
   4461   // Gets the value of the flag as a string.
   4462   const char* const value_str = ParseFlagValue(str, flag, false);
   4463 
   4464   // Aborts if the parsing failed.
   4465   if (value_str == NULL) return false;
   4466 
   4467   // Sets *value to the value of the flag.
   4468   *value = value_str;
   4469   return true;
   4470 }
   4471 
   4472 // Determines whether a string has a prefix that Google Test uses for its
   4473 // flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.
   4474 // If Google Test detects that a command line flag has its prefix but is not
   4475 // recognized, it will print its help message. Flags starting with
   4476 // GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
   4477 // internal flags and do not trigger the help message.
   4478 static bool HasGoogleTestFlagPrefix(const char* str) {
   4479   return (SkipPrefix("--", &str) ||
   4480           SkipPrefix("-", &str) ||
   4481           SkipPrefix("/", &str)) &&
   4482          !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
   4483          (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
   4484           SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str));
   4485 }
   4486 
   4487 // Prints a string containing code-encoded text.  The following escape
   4488 // sequences can be used in the string to control the text color:
   4489 //
   4490 //   @@    prints a single '@' character.
   4491 //   @R    changes the color to red.
   4492 //   @G    changes the color to green.
   4493 //   @Y    changes the color to yellow.
   4494 //   @D    changes to the default terminal text color.
   4495 //
   4496 // TODO(wan (at) google.com): Write tests for this once we add stdout
   4497 // capturing to Google Test.
   4498 static void PrintColorEncoded(const char* str) {
   4499   GTestColor color = COLOR_DEFAULT;  // The current color.
   4500 
   4501   // Conceptually, we split the string into segments divided by escape
   4502   // sequences.  Then we print one segment at a time.  At the end of
   4503   // each iteration, the str pointer advances to the beginning of the
   4504   // next segment.
   4505   for (;;) {
   4506     const char* p = strchr(str, '@');
   4507     if (p == NULL) {
   4508       ColoredPrintf(color, "%s", str);
   4509       return;
   4510     }
   4511 
   4512     ColoredPrintf(color, "%s", std::string(str, p).c_str());
   4513 
   4514     const char ch = p[1];
   4515     str = p + 2;
   4516     if (ch == '@') {
   4517       ColoredPrintf(color, "@");
   4518     } else if (ch == 'D') {
   4519       color = COLOR_DEFAULT;
   4520     } else if (ch == 'R') {
   4521       color = COLOR_RED;
   4522     } else if (ch == 'G') {
   4523       color = COLOR_GREEN;
   4524     } else if (ch == 'Y') {
   4525       color = COLOR_YELLOW;
   4526     } else {
   4527       --str;
   4528     }
   4529   }
   4530 }
   4531 
   4532 static const char kColorEncodedHelpMessage[] =
   4533 "This program contains tests written using " GTEST_NAME_ ". You can use the\n"
   4534 "following command line flags to control its behavior:\n"
   4535 "\n"
   4536 "Test Selection:\n"
   4537 "  @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n"
   4538 "      List the names of all tests instead of running them. The name of\n"
   4539 "      TEST(Foo, Bar) is \"Foo.Bar\".\n"
   4540 "  @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS"
   4541     "[@G-@YNEGATIVE_PATTERNS]@D\n"
   4542 "      Run only the tests whose name matches one of the positive patterns but\n"
   4543 "      none of the negative patterns. '?' matches any single character; '*'\n"
   4544 "      matches any substring; ':' separates two patterns.\n"
   4545 "  @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n"
   4546 "      Run all disabled tests too.\n"
   4547 "\n"
   4548 "Test Execution:\n"
   4549 "  @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n"
   4550 "      Run the tests repeatedly; use a negative count to repeat forever.\n"
   4551 "  @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n"
   4552 "      Randomize tests' orders on every iteration.\n"
   4553 "  @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n"
   4554 "      Random number seed to use for shuffling test orders (between 1 and\n"
   4555 "      99999, or 0 to use a seed based on the current time).\n"
   4556 "\n"
   4557 "Test Output:\n"
   4558 "  @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
   4559 "      Enable/disable colored output. The default is @Gauto@D.\n"
   4560 "  -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n"
   4561 "      Don't print the elapsed time of each test.\n"
   4562 "  @G--" GTEST_FLAG_PREFIX_ "output=xml@Y[@G:@YDIRECTORY_PATH@G"
   4563     GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n"
   4564 "      Generate an XML report in the given directory or with the given file\n"
   4565 "      name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n"
   4566 #if GTEST_CAN_STREAM_RESULTS_
   4567 "  @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n"
   4568 "      Stream test results to the given server.\n"
   4569 #endif  // GTEST_CAN_STREAM_RESULTS_
   4570 "\n"
   4571 "Assertion Behavior:\n"
   4572 #if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
   4573 "  @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
   4574 "      Set the default death test style.\n"
   4575 #endif  // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
   4576 "  @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n"
   4577 "      Turn assertion failures into debugger break-points.\n"
   4578 "  @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n"
   4579 "      Turn assertion failures into C++ exceptions.\n"
   4580 "  @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n"
   4581 "      Do not report exceptions as test failures. Instead, allow them\n"
   4582 "      to crash the program or throw a pop-up (on Windows).\n"
   4583 "\n"
   4584 "Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set "
   4585     "the corresponding\n"
   4586 "environment variable of a flag (all letters in upper-case). For example, to\n"
   4587 "disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_
   4588     "color=no@D or set\n"
   4589 "the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n"
   4590 "\n"
   4591 "For more information, please read the " GTEST_NAME_ " documentation at\n"
   4592 "@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n"
   4593 "(not one in your own code or tests), please report it to\n"
   4594 "@G<" GTEST_DEV_EMAIL_ ">@D.\n";
   4595 
   4596 // Parses the command line for Google Test flags, without initializing
   4597 // other parts of Google Test.  The type parameter CharType can be
   4598 // instantiated to either char or wchar_t.
   4599 template <typename CharType>
   4600 void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
   4601   for (int i = 1; i < *argc; i++) {
   4602     const std::string arg_string = StreamableToString(argv[i]);
   4603     const char* const arg = arg_string.c_str();
   4604 
   4605     using internal::ParseBoolFlag;
   4606     using internal::ParseInt32Flag;
   4607     using internal::ParseStringFlag;
   4608 
   4609     // Do we see a Google Test flag?
   4610     if (ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,
   4611                       &GTEST_FLAG(also_run_disabled_tests)) ||
   4612         ParseBoolFlag(arg, kBreakOnFailureFlag,
   4613                       &GTEST_FLAG(break_on_failure)) ||
   4614         ParseBoolFlag(arg, kCatchExceptionsFlag,
   4615                       &GTEST_FLAG(catch_exceptions)) ||
   4616         ParseStringFlag(arg, kColorFlag, &GTEST_FLAG(color)) ||
   4617         ParseStringFlag(arg, kDeathTestStyleFlag,
   4618                         &GTEST_FLAG(death_test_style)) ||
   4619         ParseBoolFlag(arg, kDeathTestUseFork,
   4620                       &GTEST_FLAG(death_test_use_fork)) ||
   4621         ParseStringFlag(arg, kFilterFlag, &GTEST_FLAG(filter)) ||
   4622         ParseStringFlag(arg, kInternalRunDeathTestFlag,
   4623                         &GTEST_FLAG(internal_run_death_test)) ||
   4624         ParseBoolFlag(arg, kListTestsFlag, &GTEST_FLAG(list_tests)) ||
   4625         ParseStringFlag(arg, kOutputFlag, &GTEST_FLAG(output)) ||
   4626         ParseBoolFlag(arg, kPrintTimeFlag, &GTEST_FLAG(print_time)) ||
   4627         ParseInt32Flag(arg, kRandomSeedFlag, &GTEST_FLAG(random_seed)) ||
   4628         ParseInt32Flag(arg, kRepeatFlag, &GTEST_FLAG(repeat)) ||
   4629         ParseBoolFlag(arg, kShuffleFlag, &GTEST_FLAG(shuffle)) ||
   4630         ParseInt32Flag(arg, kStackTraceDepthFlag,
   4631                        &GTEST_FLAG(stack_trace_depth)) ||
   4632         ParseStringFlag(arg, kStreamResultToFlag,
   4633                         &GTEST_FLAG(stream_result_to)) ||
   4634         ParseBoolFlag(arg, kThrowOnFailureFlag,
   4635                       &GTEST_FLAG(throw_on_failure))
   4636         ) {
   4637       // Yes.  Shift the remainder of the argv list left by one.  Note
   4638       // that argv has (*argc + 1) elements, the last one always being
   4639       // NULL.  The following loop moves the trailing NULL element as
   4640       // well.
   4641       for (int j = i; j != *argc; j++) {
   4642         argv[j] = argv[j + 1];
   4643       }
   4644 
   4645       // Decrements the argument count.
   4646       (*argc)--;
   4647 
   4648       // We also need to decrement the iterator as we just removed
   4649       // an element.
   4650       i--;
   4651     } else if (arg_string == "--help" || arg_string == "-h" ||
   4652                arg_string == "-?" || arg_string == "/?" ||
   4653                HasGoogleTestFlagPrefix(arg)) {
   4654       // Both help flag and unrecognized Google Test flags (excluding
   4655       // internal ones) trigger help display.
   4656       g_help_flag = true;
   4657     }
   4658   }
   4659 
   4660   if (g_help_flag) {
   4661     // We print the help here instead of in RUN_ALL_TESTS(), as the
   4662     // latter may not be called at all if the user is using Google
   4663     // Test with another testing framework.
   4664     PrintColorEncoded(kColorEncodedHelpMessage);
   4665   }
   4666 }
   4667 
   4668 // Parses the command line for Google Test flags, without initializing
   4669 // other parts of Google Test.
   4670 void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
   4671   ParseGoogleTestFlagsOnlyImpl(argc, argv);
   4672 }
   4673 void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {
   4674   ParseGoogleTestFlagsOnlyImpl(argc, argv);
   4675 }
   4676 
   4677 // The internal implementation of InitGoogleTest().
   4678 //
   4679 // The type parameter CharType can be instantiated to either char or
   4680 // wchar_t.
   4681 template <typename CharType>
   4682 void InitGoogleTestImpl(int* argc, CharType** argv) {
   4683   g_init_gtest_count++;
   4684 
   4685   // We don't want to run the initialization code twice.
   4686   if (g_init_gtest_count != 1) return;
   4687 
   4688   if (*argc <= 0) return;
   4689 
   4690   internal::g_executable_path = internal::StreamableToString(argv[0]);
   4691 
   4692 #if GTEST_HAS_DEATH_TEST
   4693 
   4694   g_argvs.clear();
   4695   for (int i = 0; i != *argc; i++) {
   4696     g_argvs.push_back(StreamableToString(argv[i]));
   4697   }
   4698 
   4699 #endif  // GTEST_HAS_DEATH_TEST
   4700 
   4701   ParseGoogleTestFlagsOnly(argc, argv);
   4702   GetUnitTestImpl()->PostFlagParsingInit();
   4703 }
   4704 
   4705 }  // namespace internal
   4706 
   4707 // Initializes Google Test.  This must be called before calling
   4708 // RUN_ALL_TESTS().  In particular, it parses a command line for the
   4709 // flags that Google Test recognizes.  Whenever a Google Test flag is
   4710 // seen, it is removed from argv, and *argc is decremented.
   4711 //
   4712 // No value is returned.  Instead, the Google Test flag variables are
   4713 // updated.
   4714 //
   4715 // Calling the function for the second time has no user-visible effect.
   4716 void InitGoogleTest(int* argc, char** argv) {
   4717   internal::InitGoogleTestImpl(argc, argv);
   4718 }
   4719 
   4720 // This overloaded version can be used in Windows programs compiled in
   4721 // UNICODE mode.
   4722 void InitGoogleTest(int* argc, wchar_t** argv) {
   4723   internal::InitGoogleTestImpl(argc, argv);
   4724 }
   4725 
   4726 }  // namespace testing
   4727