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 a terminal type that supports colors.");
    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 std::string& xml_element,
   1720                                 const TestProperty& test_property) {
   1721   if (!ValidateTestProperty(xml_element, test_property)) {
   1722     return;
   1723   }
   1724   internal::MutexLock lock(&test_properites_mutex_);
   1725   const std::vector<TestProperty>::iterator property_with_matching_key =
   1726       std::find_if(test_properties_.begin(), test_properties_.end(),
   1727                    internal::TestPropertyKeyIs(test_property.key()));
   1728   if (property_with_matching_key == test_properties_.end()) {
   1729     test_properties_.push_back(test_property);
   1730     return;
   1731   }
   1732   property_with_matching_key->SetValue(test_property.value());
   1733 }
   1734 
   1735 // The list of reserved attributes used in the <testsuites> element of XML
   1736 // output.
   1737 static const char* const kReservedTestSuitesAttributes[] = {
   1738   "disabled",
   1739   "errors",
   1740   "failures",
   1741   "name",
   1742   "random_seed",
   1743   "tests",
   1744   "time",
   1745   "timestamp"
   1746 };
   1747 
   1748 // The list of reserved attributes used in the <testsuite> element of XML
   1749 // output.
   1750 static const char* const kReservedTestSuiteAttributes[] = {
   1751   "disabled",
   1752   "errors",
   1753   "failures",
   1754   "name",
   1755   "tests",
   1756   "time"
   1757 };
   1758 
   1759 // The list of reserved attributes used in the <testcase> element of XML output.
   1760 static const char* const kReservedTestCaseAttributes[] = {
   1761   "classname",
   1762   "name",
   1763   "status",
   1764   "time",
   1765   "type_param",
   1766   "value_param"
   1767 };
   1768 
   1769 template <int kSize>
   1770 std::vector<std::string> ArrayAsVector(const char* const (&array)[kSize]) {
   1771   return std::vector<std::string>(array, array + kSize);
   1772 }
   1773 
   1774 static std::vector<std::string> GetReservedAttributesForElement(
   1775     const std::string& xml_element) {
   1776   if (xml_element == "testsuites") {
   1777     return ArrayAsVector(kReservedTestSuitesAttributes);
   1778   } else if (xml_element == "testsuite") {
   1779     return ArrayAsVector(kReservedTestSuiteAttributes);
   1780   } else if (xml_element == "testcase") {
   1781     return ArrayAsVector(kReservedTestCaseAttributes);
   1782   } else {
   1783     GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element;
   1784   }
   1785   // This code is unreachable but some compilers may not realizes that.
   1786   return std::vector<std::string>();
   1787 }
   1788 
   1789 static std::string FormatWordList(const std::vector<std::string>& words) {
   1790   Message word_list;
   1791   for (size_t i = 0; i < words.size(); ++i) {
   1792     if (i > 0 && words.size() > 2) {
   1793       word_list << ", ";
   1794     }
   1795     if (i == words.size() - 1) {
   1796       word_list << "and ";
   1797     }
   1798     word_list << "'" << words[i] << "'";
   1799   }
   1800   return word_list.GetString();
   1801 }
   1802 
   1803 bool ValidateTestPropertyName(const std::string& property_name,
   1804                               const std::vector<std::string>& reserved_names) {
   1805   if (std::find(reserved_names.begin(), reserved_names.end(), property_name) !=
   1806           reserved_names.end()) {
   1807     ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name
   1808                   << " (" << FormatWordList(reserved_names)
   1809                   << " are reserved by " << GTEST_NAME_ << ")";
   1810     return false;
   1811   }
   1812   return true;
   1813 }
   1814 
   1815 // Adds a failure if the key is a reserved attribute of the element named
   1816 // xml_element.  Returns true if the property is valid.
   1817 bool TestResult::ValidateTestProperty(const std::string& xml_element,
   1818                                       const TestProperty& test_property) {
   1819   return ValidateTestPropertyName(test_property.key(),
   1820                                   GetReservedAttributesForElement(xml_element));
   1821 }
   1822 
   1823 // Clears the object.
   1824 void TestResult::Clear() {
   1825   test_part_results_.clear();
   1826   test_properties_.clear();
   1827   death_test_count_ = 0;
   1828   elapsed_time_ = 0;
   1829 }
   1830 
   1831 // Returns true iff the test failed.
   1832 bool TestResult::Failed() const {
   1833   for (int i = 0; i < total_part_count(); ++i) {
   1834     if (GetTestPartResult(i).failed())
   1835       return true;
   1836   }
   1837   return false;
   1838 }
   1839 
   1840 // Returns true iff the test part fatally failed.
   1841 static bool TestPartFatallyFailed(const TestPartResult& result) {
   1842   return result.fatally_failed();
   1843 }
   1844 
   1845 // Returns true iff the test fatally failed.
   1846 bool TestResult::HasFatalFailure() const {
   1847   return CountIf(test_part_results_, TestPartFatallyFailed) > 0;
   1848 }
   1849 
   1850 // Returns true iff the test part non-fatally failed.
   1851 static bool TestPartNonfatallyFailed(const TestPartResult& result) {
   1852   return result.nonfatally_failed();
   1853 }
   1854 
   1855 // Returns true iff the test has a non-fatal failure.
   1856 bool TestResult::HasNonfatalFailure() const {
   1857   return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0;
   1858 }
   1859 
   1860 // Gets the number of all test parts.  This is the sum of the number
   1861 // of successful test parts and the number of failed test parts.
   1862 int TestResult::total_part_count() const {
   1863   return static_cast<int>(test_part_results_.size());
   1864 }
   1865 
   1866 // Returns the number of the test properties.
   1867 int TestResult::test_property_count() const {
   1868   return static_cast<int>(test_properties_.size());
   1869 }
   1870 
   1871 // class Test
   1872 
   1873 // Creates a Test object.
   1874 
   1875 // The c'tor saves the values of all Google Test flags.
   1876 Test::Test()
   1877     : gtest_flag_saver_(new internal::GTestFlagSaver) {
   1878 }
   1879 
   1880 // The d'tor restores the values of all Google Test flags.
   1881 Test::~Test() {
   1882   delete gtest_flag_saver_;
   1883 }
   1884 
   1885 // Sets up the test fixture.
   1886 //
   1887 // A sub-class may override this.
   1888 void Test::SetUp() {
   1889 }
   1890 
   1891 // Tears down the test fixture.
   1892 //
   1893 // A sub-class may override this.
   1894 void Test::TearDown() {
   1895 }
   1896 
   1897 // Allows user supplied key value pairs to be recorded for later output.
   1898 void Test::RecordProperty(const std::string& key, const std::string& value) {
   1899   UnitTest::GetInstance()->RecordProperty(key, value);
   1900 }
   1901 
   1902 // Allows user supplied key value pairs to be recorded for later output.
   1903 void Test::RecordProperty(const std::string& key, int value) {
   1904   Message value_message;
   1905   value_message << value;
   1906   RecordProperty(key, value_message.GetString().c_str());
   1907 }
   1908 
   1909 namespace internal {
   1910 
   1911 void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
   1912                                     const std::string& message) {
   1913   // This function is a friend of UnitTest and as such has access to
   1914   // AddTestPartResult.
   1915   UnitTest::GetInstance()->AddTestPartResult(
   1916       result_type,
   1917       NULL,  // No info about the source file where the exception occurred.
   1918       -1,    // We have no info on which line caused the exception.
   1919       message,
   1920       "");   // No stack trace, either.
   1921 }
   1922 
   1923 }  // namespace internal
   1924 
   1925 // Google Test requires all tests in the same test case to use the same test
   1926 // fixture class.  This function checks if the current test has the
   1927 // same fixture class as the first test in the current test case.  If
   1928 // yes, it returns true; otherwise it generates a Google Test failure and
   1929 // returns false.
   1930 bool Test::HasSameFixtureClass() {
   1931   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
   1932   const TestCase* const test_case = impl->current_test_case();
   1933 
   1934   // Info about the first test in the current test case.
   1935   const TestInfo* const first_test_info = test_case->test_info_list()[0];
   1936   const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_;
   1937   const char* const first_test_name = first_test_info->name();
   1938 
   1939   // Info about the current test.
   1940   const TestInfo* const this_test_info = impl->current_test_info();
   1941   const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_;
   1942   const char* const this_test_name = this_test_info->name();
   1943 
   1944   if (this_fixture_id != first_fixture_id) {
   1945     // Is the first test defined using TEST?
   1946     const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();
   1947     // Is this test defined using TEST?
   1948     const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();
   1949 
   1950     if (first_is_TEST || this_is_TEST) {
   1951       // The user mixed TEST and TEST_F in this test case - we'll tell
   1952       // him/her how to fix it.
   1953 
   1954       // Gets the name of the TEST and the name of the TEST_F.  Note
   1955       // that first_is_TEST and this_is_TEST cannot both be true, as
   1956       // the fixture IDs are different for the two tests.
   1957       const char* const TEST_name =
   1958           first_is_TEST ? first_test_name : this_test_name;
   1959       const char* const TEST_F_name =
   1960           first_is_TEST ? this_test_name : first_test_name;
   1961 
   1962       ADD_FAILURE()
   1963           << "All tests in the same test case must use the same test fixture\n"
   1964           << "class, so mixing TEST_F and TEST in the same test case is\n"
   1965           << "illegal.  In test case " << this_test_info->test_case_name()
   1966           << ",\n"
   1967           << "test " << TEST_F_name << " is defined using TEST_F but\n"
   1968           << "test " << TEST_name << " is defined using TEST.  You probably\n"
   1969           << "want to change the TEST to TEST_F or move it to another test\n"
   1970           << "case.";
   1971     } else {
   1972       // The user defined two fixture classes with the same name in
   1973       // two namespaces - we'll tell him/her how to fix it.
   1974       ADD_FAILURE()
   1975           << "All tests in the same test case must use the same test fixture\n"
   1976           << "class.  However, in test case "
   1977           << this_test_info->test_case_name() << ",\n"
   1978           << "you defined test " << first_test_name
   1979           << " and test " << this_test_name << "\n"
   1980           << "using two different test fixture classes.  This can happen if\n"
   1981           << "the two classes are from different namespaces or translation\n"
   1982           << "units and have the same name.  You should probably rename one\n"
   1983           << "of the classes to put the tests into different test cases.";
   1984     }
   1985     return false;
   1986   }
   1987 
   1988   return true;
   1989 }
   1990 
   1991 #if GTEST_HAS_SEH
   1992 
   1993 // Adds an "exception thrown" fatal failure to the current test.  This
   1994 // function returns its result via an output parameter pointer because VC++
   1995 // prohibits creation of objects with destructors on stack in functions
   1996 // using __try (see error C2712).
   1997 static std::string* FormatSehExceptionMessage(DWORD exception_code,
   1998                                               const char* location) {
   1999   Message message;
   2000   message << "SEH exception with code 0x" << std::setbase(16) <<
   2001     exception_code << std::setbase(10) << " thrown in " << location << ".";
   2002 
   2003   return new std::string(message.GetString());
   2004 }
   2005 
   2006 #endif  // GTEST_HAS_SEH
   2007 
   2008 namespace internal {
   2009 
   2010 #if GTEST_HAS_EXCEPTIONS
   2011 
   2012 // Adds an "exception thrown" fatal failure to the current test.
   2013 static std::string FormatCxxExceptionMessage(const char* description,
   2014                                              const char* location) {
   2015   Message message;
   2016   if (description != NULL) {
   2017     message << "C++ exception with description \"" << description << "\"";
   2018   } else {
   2019     message << "Unknown C++ exception";
   2020   }
   2021   message << " thrown in " << location << ".";
   2022 
   2023   return message.GetString();
   2024 }
   2025 
   2026 static std::string PrintTestPartResultToString(
   2027     const TestPartResult& test_part_result);
   2028 
   2029 GoogleTestFailureException::GoogleTestFailureException(
   2030     const TestPartResult& failure)
   2031     : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
   2032 
   2033 #endif  // GTEST_HAS_EXCEPTIONS
   2034 
   2035 // We put these helper functions in the internal namespace as IBM's xlC
   2036 // compiler rejects the code if they were declared static.
   2037 
   2038 // Runs the given method and handles SEH exceptions it throws, when
   2039 // SEH is supported; returns the 0-value for type Result in case of an
   2040 // SEH exception.  (Microsoft compilers cannot handle SEH and C++
   2041 // exceptions in the same function.  Therefore, we provide a separate
   2042 // wrapper function for handling SEH exceptions.)
   2043 template <class T, typename Result>
   2044 Result HandleSehExceptionsInMethodIfSupported(
   2045     T* object, Result (T::*method)(), const char* location) {
   2046 #if GTEST_HAS_SEH
   2047   __try {
   2048     return (object->*method)();
   2049   } __except (internal::UnitTestOptions::GTestShouldProcessSEH(  // NOLINT
   2050       GetExceptionCode())) {
   2051     // We create the exception message on the heap because VC++ prohibits
   2052     // creation of objects with destructors on stack in functions using __try
   2053     // (see error C2712).
   2054     std::string* exception_message = FormatSehExceptionMessage(
   2055         GetExceptionCode(), location);
   2056     internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
   2057                                              *exception_message);
   2058     delete exception_message;
   2059     return static_cast<Result>(0);
   2060   }
   2061 #else
   2062   (void)location;
   2063   return (object->*method)();
   2064 #endif  // GTEST_HAS_SEH
   2065 }
   2066 
   2067 // Runs the given method and catches and reports C++ and/or SEH-style
   2068 // exceptions, if they are supported; returns the 0-value for type
   2069 // Result in case of an SEH exception.
   2070 template <class T, typename Result>
   2071 Result HandleExceptionsInMethodIfSupported(
   2072     T* object, Result (T::*method)(), const char* location) {
   2073   // NOTE: The user code can affect the way in which Google Test handles
   2074   // exceptions by setting GTEST_FLAG(catch_exceptions), but only before
   2075   // RUN_ALL_TESTS() starts. It is technically possible to check the flag
   2076   // after the exception is caught and either report or re-throw the
   2077   // exception based on the flag's value:
   2078   //
   2079   // try {
   2080   //   // Perform the test method.
   2081   // } catch (...) {
   2082   //   if (GTEST_FLAG(catch_exceptions))
   2083   //     // Report the exception as failure.
   2084   //   else
   2085   //     throw;  // Re-throws the original exception.
   2086   // }
   2087   //
   2088   // However, the purpose of this flag is to allow the program to drop into
   2089   // the debugger when the exception is thrown. On most platforms, once the
   2090   // control enters the catch block, the exception origin information is
   2091   // lost and the debugger will stop the program at the point of the
   2092   // re-throw in this function -- instead of at the point of the original
   2093   // throw statement in the code under test.  For this reason, we perform
   2094   // the check early, sacrificing the ability to affect Google Test's
   2095   // exception handling in the method where the exception is thrown.
   2096   if (internal::GetUnitTestImpl()->catch_exceptions()) {
   2097 #if GTEST_HAS_EXCEPTIONS
   2098     try {
   2099       return HandleSehExceptionsInMethodIfSupported(object, method, location);
   2100     } catch (const internal::GoogleTestFailureException&) {  // NOLINT
   2101       // This exception type can only be thrown by a failed Google
   2102       // Test assertion with the intention of letting another testing
   2103       // framework catch it.  Therefore we just re-throw it.
   2104       throw;
   2105     } catch (const std::exception& e) {  // NOLINT
   2106       internal::ReportFailureInUnknownLocation(
   2107           TestPartResult::kFatalFailure,
   2108           FormatCxxExceptionMessage(e.what(), location));
   2109     } catch (...) {  // NOLINT
   2110       internal::ReportFailureInUnknownLocation(
   2111           TestPartResult::kFatalFailure,
   2112           FormatCxxExceptionMessage(NULL, location));
   2113     }
   2114     return static_cast<Result>(0);
   2115 #else
   2116     return HandleSehExceptionsInMethodIfSupported(object, method, location);
   2117 #endif  // GTEST_HAS_EXCEPTIONS
   2118   } else {
   2119     return (object->*method)();
   2120   }
   2121 }
   2122 
   2123 }  // namespace internal
   2124 
   2125 // Runs the test and updates the test result.
   2126 void Test::Run() {
   2127   if (!HasSameFixtureClass()) return;
   2128 
   2129   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
   2130   impl->os_stack_trace_getter()->UponLeavingGTest();
   2131   internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()");
   2132   // We will run the test only if SetUp() was successful.
   2133   if (!HasFatalFailure()) {
   2134     impl->os_stack_trace_getter()->UponLeavingGTest();
   2135     internal::HandleExceptionsInMethodIfSupported(
   2136         this, &Test::TestBody, "the test body");
   2137   }
   2138 
   2139   // However, we want to clean up as much as possible.  Hence we will
   2140   // always call TearDown(), even if SetUp() or the test body has
   2141   // failed.
   2142   impl->os_stack_trace_getter()->UponLeavingGTest();
   2143   internal::HandleExceptionsInMethodIfSupported(
   2144       this, &Test::TearDown, "TearDown()");
   2145 }
   2146 
   2147 // Returns true iff the current test has a fatal failure.
   2148 bool Test::HasFatalFailure() {
   2149   return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
   2150 }
   2151 
   2152 // Returns true iff the current test has a non-fatal failure.
   2153 bool Test::HasNonfatalFailure() {
   2154   return internal::GetUnitTestImpl()->current_test_result()->
   2155       HasNonfatalFailure();
   2156 }
   2157 
   2158 // class TestInfo
   2159 
   2160 // Constructs a TestInfo object. It assumes ownership of the test factory
   2161 // object.
   2162 TestInfo::TestInfo(const std::string& a_test_case_name,
   2163                    const std::string& a_name,
   2164                    const char* a_type_param,
   2165                    const char* a_value_param,
   2166                    internal::TypeId fixture_class_id,
   2167                    internal::TestFactoryBase* factory)
   2168     : test_case_name_(a_test_case_name),
   2169       name_(a_name),
   2170       type_param_(a_type_param ? new std::string(a_type_param) : NULL),
   2171       value_param_(a_value_param ? new std::string(a_value_param) : NULL),
   2172       fixture_class_id_(fixture_class_id),
   2173       should_run_(false),
   2174       is_disabled_(false),
   2175       matches_filter_(false),
   2176       factory_(factory),
   2177       result_() {}
   2178 
   2179 // Destructs a TestInfo object.
   2180 TestInfo::~TestInfo() { delete factory_; }
   2181 
   2182 namespace internal {
   2183 
   2184 // Creates a new TestInfo object and registers it with Google Test;
   2185 // returns the created object.
   2186 //
   2187 // Arguments:
   2188 //
   2189 //   test_case_name:   name of the test case
   2190 //   name:             name of the test
   2191 //   type_param:       the name of the test's type parameter, or NULL if
   2192 //                     this is not a typed or a type-parameterized test.
   2193 //   value_param:      text representation of the test's value parameter,
   2194 //                     or NULL if this is not a value-parameterized test.
   2195 //   fixture_class_id: ID of the test fixture class
   2196 //   set_up_tc:        pointer to the function that sets up the test case
   2197 //   tear_down_tc:     pointer to the function that tears down the test case
   2198 //   factory:          pointer to the factory that creates a test object.
   2199 //                     The newly created TestInfo instance will assume
   2200 //                     ownership of the factory object.
   2201 TestInfo* MakeAndRegisterTestInfo(
   2202     const char* test_case_name,
   2203     const char* name,
   2204     const char* type_param,
   2205     const char* value_param,
   2206     TypeId fixture_class_id,
   2207     SetUpTestCaseFunc set_up_tc,
   2208     TearDownTestCaseFunc tear_down_tc,
   2209     TestFactoryBase* factory) {
   2210   TestInfo* const test_info =
   2211       new TestInfo(test_case_name, name, type_param, value_param,
   2212                    fixture_class_id, factory);
   2213   GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
   2214   return test_info;
   2215 }
   2216 
   2217 #if GTEST_HAS_PARAM_TEST
   2218 void ReportInvalidTestCaseType(const char* test_case_name,
   2219                                const char* file, int line) {
   2220   Message errors;
   2221   errors
   2222       << "Attempted redefinition of test case " << test_case_name << ".\n"
   2223       << "All tests in the same test case must use the same test fixture\n"
   2224       << "class.  However, in test case " << test_case_name << ", you tried\n"
   2225       << "to define a test using a fixture class different from the one\n"
   2226       << "used earlier. This can happen if the two fixture classes are\n"
   2227       << "from different namespaces and have the same name. You should\n"
   2228       << "probably rename one of the classes to put the tests into different\n"
   2229       << "test cases.";
   2230 
   2231   fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
   2232           errors.GetString().c_str());
   2233 }
   2234 #endif  // GTEST_HAS_PARAM_TEST
   2235 
   2236 }  // namespace internal
   2237 
   2238 namespace {
   2239 
   2240 // A predicate that checks the test name of a TestInfo against a known
   2241 // value.
   2242 //
   2243 // This is used for implementation of the TestCase class only.  We put
   2244 // it in the anonymous namespace to prevent polluting the outer
   2245 // namespace.
   2246 //
   2247 // TestNameIs is copyable.
   2248 class TestNameIs {
   2249  public:
   2250   // Constructor.
   2251   //
   2252   // TestNameIs has NO default constructor.
   2253   explicit TestNameIs(const char* name)
   2254       : name_(name) {}
   2255 
   2256   // Returns true iff the test name of test_info matches name_.
   2257   bool operator()(const TestInfo * test_info) const {
   2258     return test_info && test_info->name() == name_;
   2259   }
   2260 
   2261  private:
   2262   std::string name_;
   2263 };
   2264 
   2265 }  // namespace
   2266 
   2267 namespace internal {
   2268 
   2269 // This method expands all parameterized tests registered with macros TEST_P
   2270 // and INSTANTIATE_TEST_CASE_P into regular tests and registers those.
   2271 // This will be done just once during the program runtime.
   2272 void UnitTestImpl::RegisterParameterizedTests() {
   2273 #if GTEST_HAS_PARAM_TEST
   2274   if (!parameterized_tests_registered_) {
   2275     parameterized_test_registry_.RegisterTests();
   2276     parameterized_tests_registered_ = true;
   2277   }
   2278 #endif
   2279 }
   2280 
   2281 }  // namespace internal
   2282 
   2283 // Creates the test object, runs it, records its result, and then
   2284 // deletes it.
   2285 void TestInfo::Run() {
   2286   if (!should_run_) return;
   2287 
   2288   // Tells UnitTest where to store test result.
   2289   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
   2290   impl->set_current_test_info(this);
   2291 
   2292   TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
   2293 
   2294   // Notifies the unit test event listeners that a test is about to start.
   2295   repeater->OnTestStart(*this);
   2296 
   2297   const TimeInMillis start = internal::GetTimeInMillis();
   2298 
   2299   impl->os_stack_trace_getter()->UponLeavingGTest();
   2300 
   2301   // Creates the test object.
   2302   Test* const test = internal::HandleExceptionsInMethodIfSupported(
   2303       factory_, &internal::TestFactoryBase::CreateTest,
   2304       "the test fixture's constructor");
   2305 
   2306   // Runs the test only if the test object was created and its
   2307   // constructor didn't generate a fatal failure.
   2308   if ((test != NULL) && !Test::HasFatalFailure()) {
   2309     // This doesn't throw as all user code that can throw are wrapped into
   2310     // exception handling code.
   2311     test->Run();
   2312   }
   2313 
   2314   // Deletes the test object.
   2315   impl->os_stack_trace_getter()->UponLeavingGTest();
   2316   internal::HandleExceptionsInMethodIfSupported(
   2317       test, &Test::DeleteSelf_, "the test fixture's destructor");
   2318 
   2319   result_.set_elapsed_time(internal::GetTimeInMillis() - start);
   2320 
   2321   // Notifies the unit test event listener that a test has just finished.
   2322   repeater->OnTestEnd(*this);
   2323 
   2324   // Tells UnitTest to stop associating assertion results to this
   2325   // test.
   2326   impl->set_current_test_info(NULL);
   2327 }
   2328 
   2329 // class TestCase
   2330 
   2331 // Gets the number of successful tests in this test case.
   2332 int TestCase::successful_test_count() const {
   2333   return CountIf(test_info_list_, TestPassed);
   2334 }
   2335 
   2336 // Gets the number of failed tests in this test case.
   2337 int TestCase::failed_test_count() const {
   2338   return CountIf(test_info_list_, TestFailed);
   2339 }
   2340 
   2341 int TestCase::disabled_test_count() const {
   2342   return CountIf(test_info_list_, TestDisabled);
   2343 }
   2344 
   2345 // Get the number of tests in this test case that should run.
   2346 int TestCase::test_to_run_count() const {
   2347   return CountIf(test_info_list_, ShouldRunTest);
   2348 }
   2349 
   2350 // Gets the number of all tests.
   2351 int TestCase::total_test_count() const {
   2352   return static_cast<int>(test_info_list_.size());
   2353 }
   2354 
   2355 // Creates a TestCase with the given name.
   2356 //
   2357 // Arguments:
   2358 //
   2359 //   name:         name of the test case
   2360 //   a_type_param: the name of the test case's type parameter, or NULL if
   2361 //                 this is not a typed or a type-parameterized test case.
   2362 //   set_up_tc:    pointer to the function that sets up the test case
   2363 //   tear_down_tc: pointer to the function that tears down the test case
   2364 TestCase::TestCase(const char* a_name, const char* a_type_param,
   2365                    Test::SetUpTestCaseFunc set_up_tc,
   2366                    Test::TearDownTestCaseFunc tear_down_tc)
   2367     : name_(a_name),
   2368       type_param_(a_type_param ? new std::string(a_type_param) : NULL),
   2369       set_up_tc_(set_up_tc),
   2370       tear_down_tc_(tear_down_tc),
   2371       should_run_(false),
   2372       elapsed_time_(0) {
   2373 }
   2374 
   2375 // Destructor of TestCase.
   2376 TestCase::~TestCase() {
   2377   // Deletes every Test in the collection.
   2378   ForEach(test_info_list_, internal::Delete<TestInfo>);
   2379 }
   2380 
   2381 // Returns the i-th test among all the tests. i can range from 0 to
   2382 // total_test_count() - 1. If i is not in that range, returns NULL.
   2383 const TestInfo* TestCase::GetTestInfo(int i) const {
   2384   const int index = GetElementOr(test_indices_, i, -1);
   2385   return index < 0 ? NULL : test_info_list_[index];
   2386 }
   2387 
   2388 // Returns the i-th test among all the tests. i can range from 0 to
   2389 // total_test_count() - 1. If i is not in that range, returns NULL.
   2390 TestInfo* TestCase::GetMutableTestInfo(int i) {
   2391   const int index = GetElementOr(test_indices_, i, -1);
   2392   return index < 0 ? NULL : test_info_list_[index];
   2393 }
   2394 
   2395 // Adds a test to this test case.  Will delete the test upon
   2396 // destruction of the TestCase object.
   2397 void TestCase::AddTestInfo(TestInfo * test_info) {
   2398   test_info_list_.push_back(test_info);
   2399   test_indices_.push_back(static_cast<int>(test_indices_.size()));
   2400 }
   2401 
   2402 // Runs every test in this TestCase.
   2403 void TestCase::Run() {
   2404   if (!should_run_) return;
   2405 
   2406   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
   2407   impl->set_current_test_case(this);
   2408 
   2409   TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
   2410 
   2411   repeater->OnTestCaseStart(*this);
   2412   impl->os_stack_trace_getter()->UponLeavingGTest();
   2413   internal::HandleExceptionsInMethodIfSupported(
   2414       this, &TestCase::RunSetUpTestCase, "SetUpTestCase()");
   2415 
   2416   const internal::TimeInMillis start = internal::GetTimeInMillis();
   2417   for (int i = 0; i < total_test_count(); i++) {
   2418     GetMutableTestInfo(i)->Run();
   2419   }
   2420   elapsed_time_ = internal::GetTimeInMillis() - start;
   2421 
   2422   impl->os_stack_trace_getter()->UponLeavingGTest();
   2423   internal::HandleExceptionsInMethodIfSupported(
   2424       this, &TestCase::RunTearDownTestCase, "TearDownTestCase()");
   2425 
   2426   repeater->OnTestCaseEnd(*this);
   2427   impl->set_current_test_case(NULL);
   2428 }
   2429 
   2430 // Clears the results of all tests in this test case.
   2431 void TestCase::ClearResult() {
   2432   ad_hoc_test_result_.Clear();
   2433   ForEach(test_info_list_, TestInfo::ClearTestResult);
   2434 }
   2435 
   2436 // Shuffles the tests in this test case.
   2437 void TestCase::ShuffleTests(internal::Random* random) {
   2438   Shuffle(random, &test_indices_);
   2439 }
   2440 
   2441 // Restores the test order to before the first shuffle.
   2442 void TestCase::UnshuffleTests() {
   2443   for (size_t i = 0; i < test_indices_.size(); i++) {
   2444     test_indices_[i] = static_cast<int>(i);
   2445   }
   2446 }
   2447 
   2448 // Formats a countable noun.  Depending on its quantity, either the
   2449 // singular form or the plural form is used. e.g.
   2450 //
   2451 // FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
   2452 // FormatCountableNoun(5, "book", "books") returns "5 books".
   2453 static std::string FormatCountableNoun(int count,
   2454                                        const char * singular_form,
   2455                                        const char * plural_form) {
   2456   return internal::StreamableToString(count) + " " +
   2457       (count == 1 ? singular_form : plural_form);
   2458 }
   2459 
   2460 // Formats the count of tests.
   2461 static std::string FormatTestCount(int test_count) {
   2462   return FormatCountableNoun(test_count, "test", "tests");
   2463 }
   2464 
   2465 // Formats the count of test cases.
   2466 static std::string FormatTestCaseCount(int test_case_count) {
   2467   return FormatCountableNoun(test_case_count, "test case", "test cases");
   2468 }
   2469 
   2470 // Converts a TestPartResult::Type enum to human-friendly string
   2471 // representation.  Both kNonFatalFailure and kFatalFailure are translated
   2472 // to "Failure", as the user usually doesn't care about the difference
   2473 // between the two when viewing the test result.
   2474 static const char * TestPartResultTypeToString(TestPartResult::Type type) {
   2475   switch (type) {
   2476     case TestPartResult::kSuccess:
   2477       return "Success";
   2478 
   2479     case TestPartResult::kNonFatalFailure:
   2480     case TestPartResult::kFatalFailure:
   2481 #ifdef _MSC_VER
   2482       return "error: ";
   2483 #else
   2484       return "Failure\n";
   2485 #endif
   2486     default:
   2487       return "Unknown result type";
   2488   }
   2489 }
   2490 
   2491 namespace internal {
   2492 
   2493 // Prints a TestPartResult to an std::string.
   2494 static std::string PrintTestPartResultToString(
   2495     const TestPartResult& test_part_result) {
   2496   return (Message()
   2497           << internal::FormatFileLocation(test_part_result.file_name(),
   2498                                           test_part_result.line_number())
   2499           << " " << TestPartResultTypeToString(test_part_result.type())
   2500           << test_part_result.message()).GetString();
   2501 }
   2502 
   2503 // Prints a TestPartResult.
   2504 static void PrintTestPartResult(const TestPartResult& test_part_result) {
   2505   const std::string& result =
   2506       PrintTestPartResultToString(test_part_result);
   2507   printf("%s\n", result.c_str());
   2508   fflush(stdout);
   2509   // If the test program runs in Visual Studio or a debugger, the
   2510   // following statements add the test part result message to the Output
   2511   // window such that the user can double-click on it to jump to the
   2512   // corresponding source code location; otherwise they do nothing.
   2513 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
   2514   // We don't call OutputDebugString*() on Windows Mobile, as printing
   2515   // to stdout is done by OutputDebugString() there already - we don't
   2516   // want the same message printed twice.
   2517   ::OutputDebugStringA(result.c_str());
   2518   ::OutputDebugStringA("\n");
   2519 #endif
   2520 }
   2521 
   2522 // class PrettyUnitTestResultPrinter
   2523 
   2524 enum GTestColor {
   2525   COLOR_DEFAULT,
   2526   COLOR_RED,
   2527   COLOR_GREEN,
   2528   COLOR_YELLOW
   2529 };
   2530 
   2531 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
   2532 
   2533 // Returns the character attribute for the given color.
   2534 WORD GetColorAttribute(GTestColor color) {
   2535   switch (color) {
   2536     case COLOR_RED:    return FOREGROUND_RED;
   2537     case COLOR_GREEN:  return FOREGROUND_GREEN;
   2538     case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
   2539     default:           return 0;
   2540   }
   2541 }
   2542 
   2543 #else
   2544 
   2545 // Returns the ANSI color code for the given color.  COLOR_DEFAULT is
   2546 // an invalid input.
   2547 const char* GetAnsiColorCode(GTestColor color) {
   2548   switch (color) {
   2549     case COLOR_RED:     return "1";
   2550     case COLOR_GREEN:   return "2";
   2551     case COLOR_YELLOW:  return "3";
   2552     default:            return NULL;
   2553   };
   2554 }
   2555 
   2556 #endif  // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
   2557 
   2558 // Returns true iff Google Test should use colors in the output.
   2559 bool ShouldUseColor(bool stdout_is_tty) {
   2560   const char* const gtest_color = GTEST_FLAG(color).c_str();
   2561 
   2562   if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
   2563 #if GTEST_OS_WINDOWS
   2564     // On Windows the TERM variable is usually not set, but the
   2565     // console there does support colors.
   2566     return stdout_is_tty;
   2567 #else
   2568     // On non-Windows platforms, we rely on the TERM variable.
   2569     const char* const term = posix::GetEnv("TERM");
   2570     const bool term_supports_color =
   2571         String::CStringEquals(term, "xterm") ||
   2572         String::CStringEquals(term, "xterm-color") ||
   2573         String::CStringEquals(term, "xterm-256color") ||
   2574         String::CStringEquals(term, "screen") ||
   2575         String::CStringEquals(term, "screen-256color") ||
   2576         String::CStringEquals(term, "linux") ||
   2577         String::CStringEquals(term, "cygwin");
   2578     return stdout_is_tty && term_supports_color;
   2579 #endif  // GTEST_OS_WINDOWS
   2580   }
   2581 
   2582   return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
   2583       String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
   2584       String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
   2585       String::CStringEquals(gtest_color, "1");
   2586   // We take "yes", "true", "t", and "1" as meaning "yes".  If the
   2587   // value is neither one of these nor "auto", we treat it as "no" to
   2588   // be conservative.
   2589 }
   2590 
   2591 // Helpers for printing colored strings to stdout. Note that on Windows, we
   2592 // cannot simply emit special characters and have the terminal change colors.
   2593 // This routine must actually emit the characters rather than return a string
   2594 // that would be colored when printed, as can be done on Linux.
   2595 void ColoredPrintf(GTestColor color, const char* fmt, ...) {
   2596   va_list args;
   2597   va_start(args, fmt);
   2598 
   2599 #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS || GTEST_OS_IOS
   2600   const bool use_color = false;
   2601 #else
   2602   static const bool in_color_mode =
   2603       ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
   2604   const bool use_color = in_color_mode && (color != COLOR_DEFAULT);
   2605 #endif  // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
   2606   // The '!= 0' comparison is necessary to satisfy MSVC 7.1.
   2607 
   2608   if (!use_color) {
   2609     vprintf(fmt, args);
   2610     va_end(args);
   2611     return;
   2612   }
   2613 
   2614 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
   2615   const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
   2616 
   2617   // Gets the current text color.
   2618   CONSOLE_SCREEN_BUFFER_INFO buffer_info;
   2619   GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
   2620   const WORD old_color_attrs = buffer_info.wAttributes;
   2621 
   2622   // We need to flush the stream buffers into the console before each
   2623   // SetConsoleTextAttribute call lest it affect the text that is already
   2624   // printed but has not yet reached the console.
   2625   fflush(stdout);
   2626   SetConsoleTextAttribute(stdout_handle,
   2627                           GetColorAttribute(color) | FOREGROUND_INTENSITY);
   2628   vprintf(fmt, args);
   2629 
   2630   fflush(stdout);
   2631   // Restores the text color.
   2632   SetConsoleTextAttribute(stdout_handle, old_color_attrs);
   2633 #else
   2634   printf("\033[0;3%sm", GetAnsiColorCode(color));
   2635   vprintf(fmt, args);
   2636   printf("\033[m");  // Resets the terminal to default.
   2637 #endif  // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
   2638   va_end(args);
   2639 }
   2640 
   2641 // Text printed in Google Test's text output and --gunit_list_tests
   2642 // output to label the type parameter and value parameter for a test.
   2643 static const char kTypeParamLabel[] = "TypeParam";
   2644 static const char kValueParamLabel[] = "GetParam()";
   2645 
   2646 void PrintFullTestCommentIfPresent(const TestInfo& test_info) {
   2647   const char* const type_param = test_info.type_param();
   2648   const char* const value_param = test_info.value_param();
   2649 
   2650   if (type_param != NULL || value_param != NULL) {
   2651     printf(", where ");
   2652     if (type_param != NULL) {
   2653       printf("%s = %s", kTypeParamLabel, type_param);
   2654       if (value_param != NULL)
   2655         printf(" and ");
   2656     }
   2657     if (value_param != NULL) {
   2658       printf("%s = %s", kValueParamLabel, value_param);
   2659     }
   2660   }
   2661 }
   2662 
   2663 // This class implements the TestEventListener interface.
   2664 //
   2665 // Class PrettyUnitTestResultPrinter is copyable.
   2666 class PrettyUnitTestResultPrinter : public TestEventListener {
   2667  public:
   2668   PrettyUnitTestResultPrinter() {}
   2669   static void PrintTestName(const char * test_case, const char * test) {
   2670     printf("%s.%s", test_case, test);
   2671   }
   2672 
   2673   // The following methods override what's in the TestEventListener class.
   2674   virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {}
   2675   virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
   2676   virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
   2677   virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {}
   2678   virtual void OnTestCaseStart(const TestCase& test_case);
   2679   virtual void OnTestStart(const TestInfo& test_info);
   2680   virtual void OnTestPartResult(const TestPartResult& result);
   2681   virtual void OnTestEnd(const TestInfo& test_info);
   2682   virtual void OnTestCaseEnd(const TestCase& test_case);
   2683   virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
   2684   virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {}
   2685   virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
   2686   virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {}
   2687 
   2688  private:
   2689   static void PrintFailedTests(const UnitTest& unit_test);
   2690 };
   2691 
   2692   // Fired before each iteration of tests starts.
   2693 void PrettyUnitTestResultPrinter::OnTestIterationStart(
   2694     const UnitTest& unit_test, int iteration) {
   2695   if (GTEST_FLAG(repeat) != 1)
   2696     printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
   2697 
   2698   const char* const filter = GTEST_FLAG(filter).c_str();
   2699 
   2700   // Prints the filter if it's not *.  This reminds the user that some
   2701   // tests may be skipped.
   2702   if (!String::CStringEquals(filter, kUniversalFilter)) {
   2703     ColoredPrintf(COLOR_YELLOW,
   2704                   "Note: %s filter = %s\n", GTEST_NAME_, filter);
   2705   }
   2706 
   2707   if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
   2708     const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
   2709     ColoredPrintf(COLOR_YELLOW,
   2710                   "Note: This is test shard %d of %s.\n",
   2711                   static_cast<int>(shard_index) + 1,
   2712                   internal::posix::GetEnv(kTestTotalShards));
   2713   }
   2714 
   2715   if (GTEST_FLAG(shuffle)) {
   2716     ColoredPrintf(COLOR_YELLOW,
   2717                   "Note: Randomizing tests' orders with a seed of %d .\n",
   2718                   unit_test.random_seed());
   2719   }
   2720 
   2721   ColoredPrintf(COLOR_GREEN,  "[==========] ");
   2722   printf("Running %s from %s.\n",
   2723          FormatTestCount(unit_test.test_to_run_count()).c_str(),
   2724          FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
   2725   fflush(stdout);
   2726 }
   2727 
   2728 void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
   2729     const UnitTest& /*unit_test*/) {
   2730   ColoredPrintf(COLOR_GREEN,  "[----------] ");
   2731   printf("Global test environment set-up.\n");
   2732   fflush(stdout);
   2733 }
   2734 
   2735 void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {
   2736   const std::string counts =
   2737       FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
   2738   ColoredPrintf(COLOR_GREEN, "[----------] ");
   2739   printf("%s from %s", counts.c_str(), test_case.name());
   2740   if (test_case.type_param() == NULL) {
   2741     printf("\n");
   2742   } else {
   2743     printf(", where %s = %s\n", kTypeParamLabel, test_case.type_param());
   2744   }
   2745   fflush(stdout);
   2746 }
   2747 
   2748 void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
   2749   ColoredPrintf(COLOR_GREEN,  "[ RUN      ] ");
   2750   PrintTestName(test_info.test_case_name(), test_info.name());
   2751   printf("\n");
   2752   fflush(stdout);
   2753 }
   2754 
   2755 // Called after an assertion failure.
   2756 void PrettyUnitTestResultPrinter::OnTestPartResult(
   2757     const TestPartResult& result) {
   2758   // If the test part succeeded, we don't need to do anything.
   2759   if (result.type() == TestPartResult::kSuccess)
   2760     return;
   2761 
   2762   // Print failure message from the assertion (e.g. expected this and got that).
   2763   PrintTestPartResult(result);
   2764   fflush(stdout);
   2765 }
   2766 
   2767 void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
   2768   if (test_info.result()->Passed()) {
   2769     ColoredPrintf(COLOR_GREEN, "[       OK ] ");
   2770   } else {
   2771     ColoredPrintf(COLOR_RED, "[  FAILED  ] ");
   2772   }
   2773   PrintTestName(test_info.test_case_name(), test_info.name());
   2774   if (test_info.result()->Failed())
   2775     PrintFullTestCommentIfPresent(test_info);
   2776 
   2777   if (GTEST_FLAG(print_time)) {
   2778     printf(" (%s ms)\n", internal::StreamableToString(
   2779            test_info.result()->elapsed_time()).c_str());
   2780   } else {
   2781     printf("\n");
   2782   }
   2783   fflush(stdout);
   2784 }
   2785 
   2786 void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {
   2787   if (!GTEST_FLAG(print_time)) return;
   2788 
   2789   const std::string counts =
   2790       FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
   2791   ColoredPrintf(COLOR_GREEN, "[----------] ");
   2792   printf("%s from %s (%s ms total)\n\n",
   2793          counts.c_str(), test_case.name(),
   2794          internal::StreamableToString(test_case.elapsed_time()).c_str());
   2795   fflush(stdout);
   2796 }
   2797 
   2798 void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
   2799     const UnitTest& /*unit_test*/) {
   2800   ColoredPrintf(COLOR_GREEN,  "[----------] ");
   2801   printf("Global test environment tear-down\n");
   2802   fflush(stdout);
   2803 }
   2804 
   2805 // Internal helper for printing the list of failed tests.
   2806 void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
   2807   const int failed_test_count = unit_test.failed_test_count();
   2808   if (failed_test_count == 0) {
   2809     return;
   2810   }
   2811 
   2812   for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
   2813     const TestCase& test_case = *unit_test.GetTestCase(i);
   2814     if (!test_case.should_run() || (test_case.failed_test_count() == 0)) {
   2815       continue;
   2816     }
   2817     for (int j = 0; j < test_case.total_test_count(); ++j) {
   2818       const TestInfo& test_info = *test_case.GetTestInfo(j);
   2819       if (!test_info.should_run() || test_info.result()->Passed()) {
   2820         continue;
   2821       }
   2822       ColoredPrintf(COLOR_RED, "[  FAILED  ] ");
   2823       printf("%s.%s", test_case.name(), test_info.name());
   2824       PrintFullTestCommentIfPresent(test_info);
   2825       printf("\n");
   2826     }
   2827   }
   2828 }
   2829 
   2830 void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
   2831                                                      int /*iteration*/) {
   2832   ColoredPrintf(COLOR_GREEN,  "[==========] ");
   2833   printf("%s from %s ran.",
   2834          FormatTestCount(unit_test.test_to_run_count()).c_str(),
   2835          FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
   2836   if (GTEST_FLAG(print_time)) {
   2837     printf(" (%s ms total)",
   2838            internal::StreamableToString(unit_test.elapsed_time()).c_str());
   2839   }
   2840   printf("\n");
   2841   ColoredPrintf(COLOR_GREEN,  "[  PASSED  ] ");
   2842   printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
   2843 
   2844   int num_failures = unit_test.failed_test_count();
   2845   if (!unit_test.Passed()) {
   2846     const int failed_test_count = unit_test.failed_test_count();
   2847     ColoredPrintf(COLOR_RED,  "[  FAILED  ] ");
   2848     printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
   2849     PrintFailedTests(unit_test);
   2850     printf("\n%2d FAILED %s\n", num_failures,
   2851                         num_failures == 1 ? "TEST" : "TESTS");
   2852   }
   2853 
   2854   int num_disabled = unit_test.disabled_test_count();
   2855   if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
   2856     if (!num_failures) {
   2857       printf("\n");  // Add a spacer if no FAILURE banner is displayed.
   2858     }
   2859     ColoredPrintf(COLOR_YELLOW,
   2860                   "  YOU HAVE %d DISABLED %s\n\n",
   2861                   num_disabled,
   2862                   num_disabled == 1 ? "TEST" : "TESTS");
   2863   }
   2864   // Ensure that Google Test output is printed before, e.g., heapchecker output.
   2865   fflush(stdout);
   2866 }
   2867 
   2868 // End PrettyUnitTestResultPrinter
   2869 
   2870 // class TestEventRepeater
   2871 //
   2872 // This class forwards events to other event listeners.
   2873 class TestEventRepeater : public TestEventListener {
   2874  public:
   2875   TestEventRepeater() : forwarding_enabled_(true) {}
   2876   virtual ~TestEventRepeater();
   2877   void Append(TestEventListener *listener);
   2878   TestEventListener* Release(TestEventListener* listener);
   2879 
   2880   // Controls whether events will be forwarded to listeners_. Set to false
   2881   // in death test child processes.
   2882   bool forwarding_enabled() const { return forwarding_enabled_; }
   2883   void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }
   2884 
   2885   virtual void OnTestProgramStart(const UnitTest& unit_test);
   2886   virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
   2887   virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
   2888   virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test);
   2889   virtual void OnTestCaseStart(const TestCase& test_case);
   2890   virtual void OnTestStart(const TestInfo& test_info);
   2891   virtual void OnTestPartResult(const TestPartResult& result);
   2892   virtual void OnTestEnd(const TestInfo& test_info);
   2893   virtual void OnTestCaseEnd(const TestCase& test_case);
   2894   virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
   2895   virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test);
   2896   virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
   2897   virtual void OnTestProgramEnd(const UnitTest& unit_test);
   2898 
   2899  private:
   2900   // Controls whether events will be forwarded to listeners_. Set to false
   2901   // in death test child processes.
   2902   bool forwarding_enabled_;
   2903   // The list of listeners that receive events.
   2904   std::vector<TestEventListener*> listeners_;
   2905 
   2906   GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater);
   2907 };
   2908 
   2909 TestEventRepeater::~TestEventRepeater() {
   2910   ForEach(listeners_, Delete<TestEventListener>);
   2911 }
   2912 
   2913 void TestEventRepeater::Append(TestEventListener *listener) {
   2914   listeners_.push_back(listener);
   2915 }
   2916 
   2917 // TODO(vladl (at) google.com): Factor the search functionality into Vector::Find.
   2918 TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {
   2919   for (size_t i = 0; i < listeners_.size(); ++i) {
   2920     if (listeners_[i] == listener) {
   2921       listeners_.erase(listeners_.begin() + i);
   2922       return listener;
   2923     }
   2924   }
   2925 
   2926   return NULL;
   2927 }
   2928 
   2929 // Since most methods are very similar, use macros to reduce boilerplate.
   2930 // This defines a member that forwards the call to all listeners.
   2931 #define GTEST_REPEATER_METHOD_(Name, Type) \
   2932 void TestEventRepeater::Name(const Type& parameter) { \
   2933   if (forwarding_enabled_) { \
   2934     for (size_t i = 0; i < listeners_.size(); i++) { \
   2935       listeners_[i]->Name(parameter); \
   2936     } \
   2937   } \
   2938 }
   2939 // This defines a member that forwards the call to all listeners in reverse
   2940 // order.
   2941 #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
   2942 void TestEventRepeater::Name(const Type& parameter) { \
   2943   if (forwarding_enabled_) { \
   2944     for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \
   2945       listeners_[i]->Name(parameter); \
   2946     } \
   2947   } \
   2948 }
   2949 
   2950 GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)
   2951 GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)
   2952 GTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase)
   2953 GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
   2954 GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)
   2955 GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)
   2956 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)
   2957 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)
   2958 GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)
   2959 GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestCase)
   2960 GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)
   2961 
   2962 #undef GTEST_REPEATER_METHOD_
   2963 #undef GTEST_REVERSE_REPEATER_METHOD_
   2964 
   2965 void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,
   2966                                              int iteration) {
   2967   if (forwarding_enabled_) {
   2968     for (size_t i = 0; i < listeners_.size(); i++) {
   2969       listeners_[i]->OnTestIterationStart(unit_test, iteration);
   2970     }
   2971   }
   2972 }
   2973 
   2974 void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,
   2975                                            int iteration) {
   2976   if (forwarding_enabled_) {
   2977     for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) {
   2978       listeners_[i]->OnTestIterationEnd(unit_test, iteration);
   2979     }
   2980   }
   2981 }
   2982 
   2983 // End TestEventRepeater
   2984 
   2985 // This class generates an XML output file.
   2986 class XmlUnitTestResultPrinter : public EmptyTestEventListener {
   2987  public:
   2988   explicit XmlUnitTestResultPrinter(const char* output_file);
   2989 
   2990   virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
   2991 
   2992  private:
   2993   // Is c a whitespace character that is normalized to a space character
   2994   // when it appears in an XML attribute value?
   2995   static bool IsNormalizableWhitespace(char c) {
   2996     return c == 0x9 || c == 0xA || c == 0xD;
   2997   }
   2998 
   2999   // May c appear in a well-formed XML document?
   3000   static bool IsValidXmlCharacter(char c) {
   3001     return IsNormalizableWhitespace(c) || c >= 0x20;
   3002   }
   3003 
   3004   // Returns an XML-escaped copy of the input string str.  If
   3005   // is_attribute is true, the text is meant to appear as an attribute
   3006   // value, and normalizable whitespace is preserved by replacing it
   3007   // with character references.
   3008   static std::string EscapeXml(const std::string& str, bool is_attribute);
   3009 
   3010   // Returns the given string with all characters invalid in XML removed.
   3011   static std::string RemoveInvalidXmlCharacters(const std::string& str);
   3012 
   3013   // Convenience wrapper around EscapeXml when str is an attribute value.
   3014   static std::string EscapeXmlAttribute(const std::string& str) {
   3015     return EscapeXml(str, true);
   3016   }
   3017 
   3018   // Convenience wrapper around EscapeXml when str is not an attribute value.
   3019   static std::string EscapeXmlText(const char* str) {
   3020     return EscapeXml(str, false);
   3021   }
   3022 
   3023   // Verifies that the given attribute belongs to the given element and
   3024   // streams the attribute as XML.
   3025   static void OutputXmlAttribute(std::ostream* stream,
   3026                                  const std::string& element_name,
   3027                                  const std::string& name,
   3028                                  const std::string& value);
   3029 
   3030   // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
   3031   static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
   3032 
   3033   // Streams an XML representation of a TestInfo object.
   3034   static void OutputXmlTestInfo(::std::ostream* stream,
   3035                                 const char* test_case_name,
   3036                                 const TestInfo& test_info);
   3037 
   3038   // Prints an XML representation of a TestCase object
   3039   static void PrintXmlTestCase(::std::ostream* stream,
   3040                                const TestCase& test_case);
   3041 
   3042   // Prints an XML summary of unit_test to output stream out.
   3043   static void PrintXmlUnitTest(::std::ostream* stream,
   3044                                const UnitTest& unit_test);
   3045 
   3046   // Produces a string representing the test properties in a result as space
   3047   // delimited XML attributes based on the property key="value" pairs.
   3048   // When the std::string is not empty, it includes a space at the beginning,
   3049   // to delimit this attribute from prior attributes.
   3050   static std::string TestPropertiesAsXmlAttributes(const TestResult& result);
   3051 
   3052   // The output file.
   3053   const std::string output_file_;
   3054 
   3055   GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);
   3056 };
   3057 
   3058 // Creates a new XmlUnitTestResultPrinter.
   3059 XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
   3060     : output_file_(output_file) {
   3061   if (output_file_.c_str() == NULL || output_file_.empty()) {
   3062     fprintf(stderr, "XML output file may not be null\n");
   3063     fflush(stderr);
   3064     exit(EXIT_FAILURE);
   3065   }
   3066 }
   3067 
   3068 // Called after the unit test ends.
   3069 void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
   3070                                                   int /*iteration*/) {
   3071   FILE* xmlout = NULL;
   3072   FilePath output_file(output_file_);
   3073   FilePath output_dir(output_file.RemoveFileName());
   3074 
   3075   if (output_dir.CreateDirectoriesRecursively()) {
   3076     xmlout = posix::FOpen(output_file_.c_str(), "w");
   3077   }
   3078   if (xmlout == NULL) {
   3079     // TODO(wan): report the reason of the failure.
   3080     //
   3081     // We don't do it for now as:
   3082     //
   3083     //   1. There is no urgent need for it.
   3084     //   2. It's a bit involved to make the errno variable thread-safe on
   3085     //      all three operating systems (Linux, Windows, and Mac OS).
   3086     //   3. To interpret the meaning of errno in a thread-safe way,
   3087     //      we need the strerror_r() function, which is not available on
   3088     //      Windows.
   3089     fprintf(stderr,
   3090             "Unable to open file \"%s\"\n",
   3091             output_file_.c_str());
   3092     fflush(stderr);
   3093     exit(EXIT_FAILURE);
   3094   }
   3095   std::stringstream stream;
   3096   PrintXmlUnitTest(&stream, unit_test);
   3097   fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
   3098   fclose(xmlout);
   3099 }
   3100 
   3101 // Returns an XML-escaped copy of the input string str.  If is_attribute
   3102 // is true, the text is meant to appear as an attribute value, and
   3103 // normalizable whitespace is preserved by replacing it with character
   3104 // references.
   3105 //
   3106 // Invalid XML characters in str, if any, are stripped from the output.
   3107 // It is expected that most, if not all, of the text processed by this
   3108 // module will consist of ordinary English text.
   3109 // If this module is ever modified to produce version 1.1 XML output,
   3110 // most invalid characters can be retained using character references.
   3111 // TODO(wan): It might be nice to have a minimally invasive, human-readable
   3112 // escaping scheme for invalid characters, rather than dropping them.
   3113 std::string XmlUnitTestResultPrinter::EscapeXml(
   3114     const std::string& str, bool is_attribute) {
   3115   Message m;
   3116 
   3117   for (size_t i = 0; i < str.size(); ++i) {
   3118     const char ch = str[i];
   3119     switch (ch) {
   3120       case '<':
   3121         m << "&lt;";
   3122         break;
   3123       case '>':
   3124         m << "&gt;";
   3125         break;
   3126       case '&':
   3127         m << "&amp;";
   3128         break;
   3129       case '\'':
   3130         if (is_attribute)
   3131           m << "&apos;";
   3132         else
   3133           m << '\'';
   3134         break;
   3135       case '"':
   3136         if (is_attribute)
   3137           m << "&quot;";
   3138         else
   3139           m << '"';
   3140         break;
   3141       default:
   3142         if (IsValidXmlCharacter(ch)) {
   3143           if (is_attribute && IsNormalizableWhitespace(ch))
   3144             m << "&#x" << String::FormatByte(static_cast<unsigned char>(ch))
   3145               << ";";
   3146           else
   3147             m << ch;
   3148         }
   3149         break;
   3150     }
   3151   }
   3152 
   3153   return m.GetString();
   3154 }
   3155 
   3156 // Returns the given string with all characters invalid in XML removed.
   3157 // Currently invalid characters are dropped from the string. An
   3158 // alternative is to replace them with certain characters such as . or ?.
   3159 std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(
   3160     const std::string& str) {
   3161   std::string output;
   3162   output.reserve(str.size());
   3163   for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
   3164     if (IsValidXmlCharacter(*it))
   3165       output.push_back(*it);
   3166 
   3167   return output;
   3168 }
   3169 
   3170 // The following routines generate an XML representation of a UnitTest
   3171 // object.
   3172 //
   3173 // This is how Google Test concepts map to the DTD:
   3174 //
   3175 // <testsuites name="AllTests">        <-- corresponds to a UnitTest object
   3176 //   <testsuite name="testcase-name">  <-- corresponds to a TestCase object
   3177 //     <testcase name="test-name">     <-- corresponds to a TestInfo object
   3178 //       <failure message="...">...</failure>
   3179 //       <failure message="...">...</failure>
   3180 //       <failure message="...">...</failure>
   3181 //                                     <-- individual assertion failures
   3182 //     </testcase>
   3183 //   </testsuite>
   3184 // </testsuites>
   3185 
   3186 // Formats the given time in milliseconds as seconds.
   3187 std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {
   3188   ::std::stringstream ss;
   3189   ss << ms/1000.0;
   3190   return ss.str();
   3191 }
   3192 
   3193 // Converts the given epoch time in milliseconds to a date string in the ISO
   3194 // 8601 format, without the timezone information.
   3195 std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) {
   3196   // Using non-reentrant version as localtime_r is not portable.
   3197   time_t seconds = static_cast<time_t>(ms / 1000);
   3198 #ifdef _MSC_VER
   3199 # pragma warning(push)          // Saves the current warning state.
   3200 # pragma warning(disable:4996)  // Temporarily disables warning 4996
   3201                                 // (function or variable may be unsafe).
   3202   const struct tm* const time_struct = localtime(&seconds);  // NOLINT
   3203 # pragma warning(pop)           // Restores the warning state again.
   3204 #else
   3205   const struct tm* const time_struct = localtime(&seconds);  // NOLINT
   3206 #endif
   3207   if (time_struct == NULL)
   3208     return "";  // Invalid ms value
   3209 
   3210   // YYYY-MM-DDThh:mm:ss
   3211   return StreamableToString(time_struct->tm_year + 1900) + "-" +
   3212       String::FormatIntWidth2(time_struct->tm_mon + 1) + "-" +
   3213       String::FormatIntWidth2(time_struct->tm_mday) + "T" +
   3214       String::FormatIntWidth2(time_struct->tm_hour) + ":" +
   3215       String::FormatIntWidth2(time_struct->tm_min) + ":" +
   3216       String::FormatIntWidth2(time_struct->tm_sec);
   3217 }
   3218 
   3219 // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
   3220 void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
   3221                                                      const char* data) {
   3222   const char* segment = data;
   3223   *stream << "<![CDATA[";
   3224   for (;;) {
   3225     const char* const next_segment = strstr(segment, "]]>");
   3226     if (next_segment != NULL) {
   3227       stream->write(
   3228           segment, static_cast<std::streamsize>(next_segment - segment));
   3229       *stream << "]]>]]&gt;<![CDATA[";
   3230       segment = next_segment + strlen("]]>");
   3231     } else {
   3232       *stream << segment;
   3233       break;
   3234     }
   3235   }
   3236   *stream << "]]>";
   3237 }
   3238 
   3239 void XmlUnitTestResultPrinter::OutputXmlAttribute(
   3240     std::ostream* stream,
   3241     const std::string& element_name,
   3242     const std::string& name,
   3243     const std::string& value) {
   3244   const std::vector<std::string>& allowed_names =
   3245       GetReservedAttributesForElement(element_name);
   3246 
   3247   GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
   3248                    allowed_names.end())
   3249       << "Attribute " << name << " is not allowed for element <" << element_name
   3250       << ">.";
   3251 
   3252   *stream << " " << name << "=\"" << EscapeXmlAttribute(value) << "\"";
   3253 }
   3254 
   3255 // Prints an XML representation of a TestInfo object.
   3256 // TODO(wan): There is also value in printing properties with the plain printer.
   3257 void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
   3258                                                  const char* test_case_name,
   3259                                                  const TestInfo& test_info) {
   3260   const TestResult& result = *test_info.result();
   3261   const std::string kTestcase = "testcase";
   3262 
   3263   *stream << "    <testcase";
   3264   OutputXmlAttribute(stream, kTestcase, "name", test_info.name());
   3265 
   3266   if (test_info.value_param() != NULL) {
   3267     OutputXmlAttribute(stream, kTestcase, "value_param",
   3268                        test_info.value_param());
   3269   }
   3270   if (test_info.type_param() != NULL) {
   3271     OutputXmlAttribute(stream, kTestcase, "type_param", test_info.type_param());
   3272   }
   3273 
   3274   OutputXmlAttribute(stream, kTestcase, "status",
   3275                      test_info.should_run() ? "run" : "notrun");
   3276   OutputXmlAttribute(stream, kTestcase, "time",
   3277                      FormatTimeInMillisAsSeconds(result.elapsed_time()));
   3278   OutputXmlAttribute(stream, kTestcase, "classname", test_case_name);
   3279   *stream << TestPropertiesAsXmlAttributes(result);
   3280 
   3281   int failures = 0;
   3282   for (int i = 0; i < result.total_part_count(); ++i) {
   3283     const TestPartResult& part = result.GetTestPartResult(i);
   3284     if (part.failed()) {
   3285       if (++failures == 1) {
   3286         *stream << ">\n";
   3287       }
   3288       const string location = internal::FormatCompilerIndependentFileLocation(
   3289           part.file_name(), part.line_number());
   3290       const string summary = location + "\n" + part.summary();
   3291       *stream << "      <failure message=\""
   3292               << EscapeXmlAttribute(summary.c_str())
   3293               << "\" type=\"\">";
   3294       const string detail = location + "\n" + part.message();
   3295       OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
   3296       *stream << "</failure>\n";
   3297     }
   3298   }
   3299 
   3300   if (failures == 0)
   3301     *stream << " />\n";
   3302   else
   3303     *stream << "    </testcase>\n";
   3304 }
   3305 
   3306 // Prints an XML representation of a TestCase object
   3307 void XmlUnitTestResultPrinter::PrintXmlTestCase(std::ostream* stream,
   3308                                                 const TestCase& test_case) {
   3309   const std::string kTestsuite = "testsuite";
   3310   *stream << "  <" << kTestsuite;
   3311   OutputXmlAttribute(stream, kTestsuite, "name", test_case.name());
   3312   OutputXmlAttribute(stream, kTestsuite, "tests",
   3313                      StreamableToString(test_case.total_test_count()));
   3314   OutputXmlAttribute(stream, kTestsuite, "failures",
   3315                      StreamableToString(test_case.failed_test_count()));
   3316   OutputXmlAttribute(stream, kTestsuite, "disabled",
   3317                      StreamableToString(test_case.disabled_test_count()));
   3318   OutputXmlAttribute(stream, kTestsuite, "errors", "0");
   3319   OutputXmlAttribute(stream, kTestsuite, "time",
   3320                      FormatTimeInMillisAsSeconds(test_case.elapsed_time()));
   3321   *stream << TestPropertiesAsXmlAttributes(test_case.ad_hoc_test_result())
   3322           << ">\n";
   3323 
   3324   for (int i = 0; i < test_case.total_test_count(); ++i)
   3325     OutputXmlTestInfo(stream, test_case.name(), *test_case.GetTestInfo(i));
   3326   *stream << "  </" << kTestsuite << ">\n";
   3327 }
   3328 
   3329 // Prints an XML summary of unit_test to output stream out.
   3330 void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream,
   3331                                                 const UnitTest& unit_test) {
   3332   const std::string kTestsuites = "testsuites";
   3333 
   3334   *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
   3335   *stream << "<" << kTestsuites;
   3336 
   3337   OutputXmlAttribute(stream, kTestsuites, "tests",
   3338                      StreamableToString(unit_test.total_test_count()));
   3339   OutputXmlAttribute(stream, kTestsuites, "failures",
   3340                      StreamableToString(unit_test.failed_test_count()));
   3341   OutputXmlAttribute(stream, kTestsuites, "disabled",
   3342                      StreamableToString(unit_test.disabled_test_count()));
   3343   OutputXmlAttribute(stream, kTestsuites, "errors", "0");
   3344   OutputXmlAttribute(
   3345       stream, kTestsuites, "timestamp",
   3346       FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp()));
   3347   OutputXmlAttribute(stream, kTestsuites, "time",
   3348                      FormatTimeInMillisAsSeconds(unit_test.elapsed_time()));
   3349 
   3350   if (GTEST_FLAG(shuffle)) {
   3351     OutputXmlAttribute(stream, kTestsuites, "random_seed",
   3352                        StreamableToString(unit_test.random_seed()));
   3353   }
   3354 
   3355   *stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result());
   3356 
   3357   OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
   3358   *stream << ">\n";
   3359 
   3360 
   3361   for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
   3362     PrintXmlTestCase(stream, *unit_test.GetTestCase(i));
   3363   }
   3364   *stream << "</" << kTestsuites << ">\n";
   3365 }
   3366 
   3367 // Produces a string representing the test properties in a result as space
   3368 // delimited XML attributes based on the property key="value" pairs.
   3369 std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
   3370     const TestResult& result) {
   3371   Message attributes;
   3372   for (int i = 0; i < result.test_property_count(); ++i) {
   3373     const TestProperty& property = result.GetTestProperty(i);
   3374     attributes << " " << property.key() << "="
   3375         << "\"" << EscapeXmlAttribute(property.value()) << "\"";
   3376   }
   3377   return attributes.GetString();
   3378 }
   3379 
   3380 // End XmlUnitTestResultPrinter
   3381 
   3382 #if GTEST_CAN_STREAM_RESULTS_
   3383 
   3384 // Checks if str contains '=', '&', '%' or '\n' characters. If yes,
   3385 // replaces them by "%xx" where xx is their hexadecimal value. For
   3386 // example, replaces "=" with "%3D".  This algorithm is O(strlen(str))
   3387 // in both time and space -- important as the input str may contain an
   3388 // arbitrarily long test failure message and stack trace.
   3389 string StreamingListener::UrlEncode(const char* str) {
   3390   string result;
   3391   result.reserve(strlen(str) + 1);
   3392   for (char ch = *str; ch != '\0'; ch = *++str) {
   3393     switch (ch) {
   3394       case '%':
   3395       case '=':
   3396       case '&':
   3397       case '\n':
   3398         result.append("%" + String::FormatByte(static_cast<unsigned char>(ch)));
   3399         break;
   3400       default:
   3401         result.push_back(ch);
   3402         break;
   3403     }
   3404   }
   3405   return result;
   3406 }
   3407 
   3408 void StreamingListener::SocketWriter::MakeConnection() {
   3409   GTEST_CHECK_(sockfd_ == -1)
   3410       << "MakeConnection() can't be called when there is already a connection.";
   3411 
   3412   addrinfo hints;
   3413   memset(&hints, 0, sizeof(hints));
   3414   hints.ai_family = AF_UNSPEC;    // To allow both IPv4 and IPv6 addresses.
   3415   hints.ai_socktype = SOCK_STREAM;
   3416   addrinfo* servinfo = NULL;
   3417 
   3418   // Use the getaddrinfo() to get a linked list of IP addresses for
   3419   // the given host name.
   3420   const int error_num = getaddrinfo(
   3421       host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
   3422   if (error_num != 0) {
   3423     GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: "
   3424                         << gai_strerror(error_num);
   3425   }
   3426 
   3427   // Loop through all the results and connect to the first we can.
   3428   for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != NULL;
   3429        cur_addr = cur_addr->ai_next) {
   3430     sockfd_ = socket(
   3431         cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol);
   3432     if (sockfd_ != -1) {
   3433       // Connect the client socket to the server socket.
   3434       if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
   3435         close(sockfd_);
   3436         sockfd_ = -1;
   3437       }
   3438     }
   3439   }
   3440 
   3441   freeaddrinfo(servinfo);  // all done with this structure
   3442 
   3443   if (sockfd_ == -1) {
   3444     GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to "
   3445                         << host_name_ << ":" << port_num_;
   3446   }
   3447 }
   3448 
   3449 // End of class Streaming Listener
   3450 #endif  // GTEST_CAN_STREAM_RESULTS__
   3451 
   3452 // Class ScopedTrace
   3453 
   3454 // Pushes the given source file location and message onto a per-thread
   3455 // trace stack maintained by Google Test.
   3456 ScopedTrace::ScopedTrace(const char* file, int line, const Message& message)
   3457     GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
   3458   TraceInfo trace;
   3459   trace.file = file;
   3460   trace.line = line;
   3461   trace.message = message.GetString();
   3462 
   3463   UnitTest::GetInstance()->PushGTestTrace(trace);
   3464 }
   3465 
   3466 // Pops the info pushed by the c'tor.
   3467 ScopedTrace::~ScopedTrace()
   3468     GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
   3469   UnitTest::GetInstance()->PopGTestTrace();
   3470 }
   3471 
   3472 
   3473 // class OsStackTraceGetter
   3474 
   3475 // Returns the current OS stack trace as an std::string.  Parameters:
   3476 //
   3477 //   max_depth  - the maximum number of stack frames to be included
   3478 //                in the trace.
   3479 //   skip_count - the number of top frames to be skipped; doesn't count
   3480 //                against max_depth.
   3481 //
   3482 string OsStackTraceGetter::CurrentStackTrace(int /* max_depth */,
   3483                                              int /* skip_count */)
   3484     GTEST_LOCK_EXCLUDED_(mutex_) {
   3485   return "";
   3486 }
   3487 
   3488 void OsStackTraceGetter::UponLeavingGTest()
   3489     GTEST_LOCK_EXCLUDED_(mutex_) {
   3490 }
   3491 
   3492 const char* const
   3493 OsStackTraceGetter::kElidedFramesMarker =
   3494     "... " GTEST_NAME_ " internal frames ...";
   3495 
   3496 }  // namespace internal
   3497 
   3498 // class TestEventListeners
   3499 
   3500 TestEventListeners::TestEventListeners()
   3501     : repeater_(new internal::TestEventRepeater()),
   3502       default_result_printer_(NULL),
   3503       default_xml_generator_(NULL) {
   3504 }
   3505 
   3506 TestEventListeners::~TestEventListeners() { delete repeater_; }
   3507 
   3508 // Returns the standard listener responsible for the default console
   3509 // output.  Can be removed from the listeners list to shut down default
   3510 // console output.  Note that removing this object from the listener list
   3511 // with Release transfers its ownership to the user.
   3512 void TestEventListeners::Append(TestEventListener* listener) {
   3513   repeater_->Append(listener);
   3514 }
   3515 
   3516 // Removes the given event listener from the list and returns it.  It then
   3517 // becomes the caller's responsibility to delete the listener. Returns
   3518 // NULL if the listener is not found in the list.
   3519 TestEventListener* TestEventListeners::Release(TestEventListener* listener) {
   3520   if (listener == default_result_printer_)
   3521     default_result_printer_ = NULL;
   3522   else if (listener == default_xml_generator_)
   3523     default_xml_generator_ = NULL;
   3524   return repeater_->Release(listener);
   3525 }
   3526 
   3527 // Returns repeater that broadcasts the TestEventListener events to all
   3528 // subscribers.
   3529 TestEventListener* TestEventListeners::repeater() { return repeater_; }
   3530 
   3531 // Sets the default_result_printer attribute to the provided listener.
   3532 // The listener is also added to the listener list and previous
   3533 // default_result_printer is removed from it and deleted. The listener can
   3534 // also be NULL in which case it will not be added to the list. Does
   3535 // nothing if the previous and the current listener objects are the same.
   3536 void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
   3537   if (default_result_printer_ != listener) {
   3538     // It is an error to pass this method a listener that is already in the
   3539     // list.
   3540     delete Release(default_result_printer_);
   3541     default_result_printer_ = listener;
   3542     if (listener != NULL)
   3543       Append(listener);
   3544   }
   3545 }
   3546 
   3547 // Sets the default_xml_generator attribute to the provided listener.  The
   3548 // listener is also added to the listener list and previous
   3549 // default_xml_generator is removed from it and deleted. The listener can
   3550 // also be NULL in which case it will not be added to the list. Does
   3551 // nothing if the previous and the current listener objects are the same.
   3552 void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
   3553   if (default_xml_generator_ != listener) {
   3554     // It is an error to pass this method a listener that is already in the
   3555     // list.
   3556     delete Release(default_xml_generator_);
   3557     default_xml_generator_ = listener;
   3558     if (listener != NULL)
   3559       Append(listener);
   3560   }
   3561 }
   3562 
   3563 // Controls whether events will be forwarded by the repeater to the
   3564 // listeners in the list.
   3565 bool TestEventListeners::EventForwardingEnabled() const {
   3566   return repeater_->forwarding_enabled();
   3567 }
   3568 
   3569 void TestEventListeners::SuppressEventForwarding() {
   3570   repeater_->set_forwarding_enabled(false);
   3571 }
   3572 
   3573 // class UnitTest
   3574 
   3575 // Gets the singleton UnitTest object.  The first time this method is
   3576 // called, a UnitTest object is constructed and returned.  Consecutive
   3577 // calls will return the same object.
   3578 //
   3579 // We don't protect this under mutex_ as a user is not supposed to
   3580 // call this before main() starts, from which point on the return
   3581 // value will never change.
   3582 UnitTest* UnitTest::GetInstance() {
   3583   // When compiled with MSVC 7.1 in optimized mode, destroying the
   3584   // UnitTest object upon exiting the program messes up the exit code,
   3585   // causing successful tests to appear failed.  We have to use a
   3586   // different implementation in this case to bypass the compiler bug.
   3587   // This implementation makes the compiler happy, at the cost of
   3588   // leaking the UnitTest object.
   3589 
   3590   // CodeGear C++Builder insists on a public destructor for the
   3591   // default implementation.  Use this implementation to keep good OO
   3592   // design with private destructor.
   3593 
   3594 #if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
   3595   static UnitTest* const instance = new UnitTest;
   3596   return instance;
   3597 #else
   3598   static UnitTest instance;
   3599   return &instance;
   3600 #endif  // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
   3601 }
   3602 
   3603 // Gets the number of successful test cases.
   3604 int UnitTest::successful_test_case_count() const {
   3605   return impl()->successful_test_case_count();
   3606 }
   3607 
   3608 // Gets the number of failed test cases.
   3609 int UnitTest::failed_test_case_count() const {
   3610   return impl()->failed_test_case_count();
   3611 }
   3612 
   3613 // Gets the number of all test cases.
   3614 int UnitTest::total_test_case_count() const {
   3615   return impl()->total_test_case_count();
   3616 }
   3617 
   3618 // Gets the number of all test cases that contain at least one test
   3619 // that should run.
   3620 int UnitTest::test_case_to_run_count() const {
   3621   return impl()->test_case_to_run_count();
   3622 }
   3623 
   3624 // Gets the number of successful tests.
   3625 int UnitTest::successful_test_count() const {
   3626   return impl()->successful_test_count();
   3627 }
   3628 
   3629 // Gets the number of failed tests.
   3630 int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
   3631 
   3632 // Gets the number of disabled tests.
   3633 int UnitTest::disabled_test_count() const {
   3634   return impl()->disabled_test_count();
   3635 }
   3636 
   3637 // Gets the number of all tests.
   3638 int UnitTest::total_test_count() const { return impl()->total_test_count(); }
   3639 
   3640 // Gets the number of tests that should run.
   3641 int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
   3642 
   3643 // Gets the time of the test program start, in ms from the start of the
   3644 // UNIX epoch.
   3645 internal::TimeInMillis UnitTest::start_timestamp() const {
   3646     return impl()->start_timestamp();
   3647 }
   3648 
   3649 // Gets the elapsed time, in milliseconds.
   3650 internal::TimeInMillis UnitTest::elapsed_time() const {
   3651   return impl()->elapsed_time();
   3652 }
   3653 
   3654 // Returns true iff the unit test passed (i.e. all test cases passed).
   3655 bool UnitTest::Passed() const { return impl()->Passed(); }
   3656 
   3657 // Returns true iff the unit test failed (i.e. some test case failed
   3658 // or something outside of all tests failed).
   3659 bool UnitTest::Failed() const { return impl()->Failed(); }
   3660 
   3661 // Gets the i-th test case among all the test cases. i can range from 0 to
   3662 // total_test_case_count() - 1. If i is not in that range, returns NULL.
   3663 const TestCase* UnitTest::GetTestCase(int i) const {
   3664   return impl()->GetTestCase(i);
   3665 }
   3666 
   3667 // Returns the TestResult containing information on test failures and
   3668 // properties logged outside of individual test cases.
   3669 const TestResult& UnitTest::ad_hoc_test_result() const {
   3670   return *impl()->ad_hoc_test_result();
   3671 }
   3672 
   3673 // Gets the i-th test case among all the test cases. i can range from 0 to
   3674 // total_test_case_count() - 1. If i is not in that range, returns NULL.
   3675 TestCase* UnitTest::GetMutableTestCase(int i) {
   3676   return impl()->GetMutableTestCase(i);
   3677 }
   3678 
   3679 // Returns the list of event listeners that can be used to track events
   3680 // inside Google Test.
   3681 TestEventListeners& UnitTest::listeners() {
   3682   return *impl()->listeners();
   3683 }
   3684 
   3685 // Registers and returns a global test environment.  When a test
   3686 // program is run, all global test environments will be set-up in the
   3687 // order they were registered.  After all tests in the program have
   3688 // finished, all global test environments will be torn-down in the
   3689 // *reverse* order they were registered.
   3690 //
   3691 // The UnitTest object takes ownership of the given environment.
   3692 //
   3693 // We don't protect this under mutex_, as we only support calling it
   3694 // from the main thread.
   3695 Environment* UnitTest::AddEnvironment(Environment* env) {
   3696   if (env == NULL) {
   3697     return NULL;
   3698   }
   3699 
   3700   impl_->environments().push_back(env);
   3701   return env;
   3702 }
   3703 
   3704 // Adds a TestPartResult to the current TestResult object.  All Google Test
   3705 // assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
   3706 // this to report their results.  The user code should use the
   3707 // assertion macros instead of calling this directly.
   3708 void UnitTest::AddTestPartResult(
   3709     TestPartResult::Type result_type,
   3710     const char* file_name,
   3711     int line_number,
   3712     const std::string& message,
   3713     const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_) {
   3714   Message msg;
   3715   msg << message;
   3716 
   3717   internal::MutexLock lock(&mutex_);
   3718   if (impl_->gtest_trace_stack().size() > 0) {
   3719     msg << "\n" << GTEST_NAME_ << " trace:";
   3720 
   3721     for (int i = static_cast<int>(impl_->gtest_trace_stack().size());
   3722          i > 0; --i) {
   3723       const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
   3724       msg << "\n" << internal::FormatFileLocation(trace.file, trace.line)
   3725           << " " << trace.message;
   3726     }
   3727   }
   3728 
   3729   if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) {
   3730     msg << internal::kStackTraceMarker << os_stack_trace;
   3731   }
   3732 
   3733   const TestPartResult result =
   3734     TestPartResult(result_type, file_name, line_number,
   3735                    msg.GetString().c_str());
   3736   impl_->GetTestPartResultReporterForCurrentThread()->
   3737       ReportTestPartResult(result);
   3738 
   3739   if (result_type != TestPartResult::kSuccess) {
   3740     // gtest_break_on_failure takes precedence over
   3741     // gtest_throw_on_failure.  This allows a user to set the latter
   3742     // in the code (perhaps in order to use Google Test assertions
   3743     // with another testing framework) and specify the former on the
   3744     // command line for debugging.
   3745     if (GTEST_FLAG(break_on_failure)) {
   3746 #if GTEST_OS_WINDOWS
   3747       // Using DebugBreak on Windows allows gtest to still break into a debugger
   3748       // when a failure happens and both the --gtest_break_on_failure and
   3749       // the --gtest_catch_exceptions flags are specified.
   3750       DebugBreak();
   3751 #else
   3752       // Dereference NULL through a volatile pointer to prevent the compiler
   3753       // from removing. We use this rather than abort() or __builtin_trap() for
   3754       // portability: Symbian doesn't implement abort() well, and some debuggers
   3755       // don't correctly trap abort().
   3756       *static_cast<volatile int*>(NULL) = 1;
   3757 #endif  // GTEST_OS_WINDOWS
   3758     } else if (GTEST_FLAG(throw_on_failure)) {
   3759 #if GTEST_HAS_EXCEPTIONS
   3760       throw internal::GoogleTestFailureException(result);
   3761 #else
   3762       // We cannot call abort() as it generates a pop-up in debug mode
   3763       // that cannot be suppressed in VC 7.1 or below.
   3764       exit(1);
   3765 #endif
   3766     }
   3767   }
   3768 }
   3769 
   3770 // Adds a TestProperty to the current TestResult object when invoked from
   3771 // inside a test, to current TestCase's ad_hoc_test_result_ when invoked
   3772 // from SetUpTestCase or TearDownTestCase, or to the global property set
   3773 // when invoked elsewhere.  If the result already contains a property with
   3774 // the same key, the value will be updated.
   3775 void UnitTest::RecordProperty(const std::string& key,
   3776                               const std::string& value) {
   3777   impl_->RecordProperty(TestProperty(key, value));
   3778 }
   3779 
   3780 // Runs all tests in this UnitTest object and prints the result.
   3781 // Returns 0 if successful, or 1 otherwise.
   3782 //
   3783 // We don't protect this under mutex_, as we only support calling it
   3784 // from the main thread.
   3785 int UnitTest::Run() {
   3786   // Captures the value of GTEST_FLAG(catch_exceptions).  This value will be
   3787   // used for the duration of the program.
   3788   impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions));
   3789 
   3790 #if GTEST_HAS_SEH
   3791   const bool in_death_test_child_process =
   3792       internal::GTEST_FLAG(internal_run_death_test).length() > 0;
   3793 
   3794   // Either the user wants Google Test to catch exceptions thrown by the
   3795   // tests or this is executing in the context of death test child
   3796   // process. In either case the user does not want to see pop-up dialogs
   3797   // about crashes - they are expected.
   3798   if (impl()->catch_exceptions() || in_death_test_child_process) {
   3799 # if !GTEST_OS_WINDOWS_MOBILE
   3800     // SetErrorMode doesn't exist on CE.
   3801     SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
   3802                  SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
   3803 # endif  // !GTEST_OS_WINDOWS_MOBILE
   3804 
   3805 # if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
   3806     // Death test children can be terminated with _abort().  On Windows,
   3807     // _abort() can show a dialog with a warning message.  This forces the
   3808     // abort message to go to stderr instead.
   3809     _set_error_mode(_OUT_TO_STDERR);
   3810 # endif
   3811 
   3812 # if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
   3813     // In the debug version, Visual Studio pops up a separate dialog
   3814     // offering a choice to debug the aborted program. We need to suppress
   3815     // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
   3816     // executed. Google Test will notify the user of any unexpected
   3817     // failure via stderr.
   3818     //
   3819     // VC++ doesn't define _set_abort_behavior() prior to the version 8.0.
   3820     // Users of prior VC versions shall suffer the agony and pain of
   3821     // clicking through the countless debug dialogs.
   3822     // TODO(vladl (at) google.com): find a way to suppress the abort dialog() in the
   3823     // debug mode when compiled with VC 7.1 or lower.
   3824     if (!GTEST_FLAG(break_on_failure))
   3825       _set_abort_behavior(
   3826           0x0,                                    // Clear the following flags:
   3827           _WRITE_ABORT_MSG | _CALL_REPORTFAULT);  // pop-up window, core dump.
   3828 # endif
   3829   }
   3830 #endif  // GTEST_HAS_SEH
   3831 
   3832   return internal::HandleExceptionsInMethodIfSupported(
   3833       impl(),
   3834       &internal::UnitTestImpl::RunAllTests,
   3835       "auxiliary test code (environments or event listeners)") ? 0 : 1;
   3836 }
   3837 
   3838 // Returns the working directory when the first TEST() or TEST_F() was
   3839 // executed.
   3840 const char* UnitTest::original_working_dir() const {
   3841   return impl_->original_working_dir_.c_str();
   3842 }
   3843 
   3844 // Returns the TestCase object for the test that's currently running,
   3845 // or NULL if no test is running.
   3846 const TestCase* UnitTest::current_test_case() const
   3847     GTEST_LOCK_EXCLUDED_(mutex_) {
   3848   internal::MutexLock lock(&mutex_);
   3849   return impl_->current_test_case();
   3850 }
   3851 
   3852 // Returns the TestInfo object for the test that's currently running,
   3853 // or NULL if no test is running.
   3854 const TestInfo* UnitTest::current_test_info() const
   3855     GTEST_LOCK_EXCLUDED_(mutex_) {
   3856   internal::MutexLock lock(&mutex_);
   3857   return impl_->current_test_info();
   3858 }
   3859 
   3860 // Returns the random seed used at the start of the current test run.
   3861 int UnitTest::random_seed() const { return impl_->random_seed(); }
   3862 
   3863 #if GTEST_HAS_PARAM_TEST
   3864 // Returns ParameterizedTestCaseRegistry object used to keep track of
   3865 // value-parameterized tests and instantiate and register them.
   3866 internal::ParameterizedTestCaseRegistry&
   3867     UnitTest::parameterized_test_registry()
   3868         GTEST_LOCK_EXCLUDED_(mutex_) {
   3869   return impl_->parameterized_test_registry();
   3870 }
   3871 #endif  // GTEST_HAS_PARAM_TEST
   3872 
   3873 // Creates an empty UnitTest.
   3874 UnitTest::UnitTest() {
   3875   impl_ = new internal::UnitTestImpl(this);
   3876 }
   3877 
   3878 // Destructor of UnitTest.
   3879 UnitTest::~UnitTest() {
   3880   delete impl_;
   3881 }
   3882 
   3883 // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
   3884 // Google Test trace stack.
   3885 void UnitTest::PushGTestTrace(const internal::TraceInfo& trace)
   3886     GTEST_LOCK_EXCLUDED_(mutex_) {
   3887   internal::MutexLock lock(&mutex_);
   3888   impl_->gtest_trace_stack().push_back(trace);
   3889 }
   3890 
   3891 // Pops a trace from the per-thread Google Test trace stack.
   3892 void UnitTest::PopGTestTrace()
   3893     GTEST_LOCK_EXCLUDED_(mutex_) {
   3894   internal::MutexLock lock(&mutex_);
   3895   impl_->gtest_trace_stack().pop_back();
   3896 }
   3897 
   3898 namespace internal {
   3899 
   3900 UnitTestImpl::UnitTestImpl(UnitTest* parent)
   3901     : parent_(parent),
   3902 #ifdef _MSC_VER
   3903 # pragma warning(push)                    // Saves the current warning state.
   3904 # pragma warning(disable:4355)            // Temporarily disables warning 4355
   3905                                          // (using this in initializer).
   3906       default_global_test_part_result_reporter_(this),
   3907       default_per_thread_test_part_result_reporter_(this),
   3908 # pragma warning(pop)                     // Restores the warning state again.
   3909 #else
   3910       default_global_test_part_result_reporter_(this),
   3911       default_per_thread_test_part_result_reporter_(this),
   3912 #endif  // _MSC_VER
   3913       global_test_part_result_repoter_(
   3914           &default_global_test_part_result_reporter_),
   3915       per_thread_test_part_result_reporter_(
   3916           &default_per_thread_test_part_result_reporter_),
   3917 #if GTEST_HAS_PARAM_TEST
   3918       parameterized_test_registry_(),
   3919       parameterized_tests_registered_(false),
   3920 #endif  // GTEST_HAS_PARAM_TEST
   3921       last_death_test_case_(-1),
   3922       current_test_case_(NULL),
   3923       current_test_info_(NULL),
   3924       ad_hoc_test_result_(),
   3925       os_stack_trace_getter_(NULL),
   3926       post_flag_parse_init_performed_(false),
   3927       random_seed_(0),  // Will be overridden by the flag before first use.
   3928       random_(0),  // Will be reseeded before first use.
   3929       start_timestamp_(0),
   3930       elapsed_time_(0),
   3931 #if GTEST_HAS_DEATH_TEST
   3932       internal_run_death_test_flag_(NULL),
   3933       death_test_factory_(new DefaultDeathTestFactory),
   3934 #endif
   3935       // Will be overridden by the flag before first use.
   3936       catch_exceptions_(false) {
   3937   listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);
   3938 }
   3939 
   3940 UnitTestImpl::~UnitTestImpl() {
   3941   // Deletes every TestCase.
   3942   ForEach(test_cases_, internal::Delete<TestCase>);
   3943 
   3944   // Deletes every Environment.
   3945   ForEach(environments_, internal::Delete<Environment>);
   3946 
   3947   delete os_stack_trace_getter_;
   3948 }
   3949 
   3950 // Adds a TestProperty to the current TestResult object when invoked in a
   3951 // context of a test, to current test case's ad_hoc_test_result when invoke
   3952 // from SetUpTestCase/TearDownTestCase, or to the global property set
   3953 // otherwise.  If the result already contains a property with the same key,
   3954 // the value will be updated.
   3955 void UnitTestImpl::RecordProperty(const TestProperty& test_property) {
   3956   std::string xml_element;
   3957   TestResult* test_result;  // TestResult appropriate for property recording.
   3958 
   3959   if (current_test_info_ != NULL) {
   3960     xml_element = "testcase";
   3961     test_result = &(current_test_info_->result_);
   3962   } else if (current_test_case_ != NULL) {
   3963     xml_element = "testsuite";
   3964     test_result = &(current_test_case_->ad_hoc_test_result_);
   3965   } else {
   3966     xml_element = "testsuites";
   3967     test_result = &ad_hoc_test_result_;
   3968   }
   3969   test_result->RecordProperty(xml_element, test_property);
   3970 }
   3971 
   3972 #if GTEST_HAS_DEATH_TEST
   3973 // Disables event forwarding if the control is currently in a death test
   3974 // subprocess. Must not be called before InitGoogleTest.
   3975 void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
   3976   if (internal_run_death_test_flag_.get() != NULL)
   3977     listeners()->SuppressEventForwarding();
   3978 }
   3979 #endif  // GTEST_HAS_DEATH_TEST
   3980 
   3981 // Initializes event listeners performing XML output as specified by
   3982 // UnitTestOptions. Must not be called before InitGoogleTest.
   3983 void UnitTestImpl::ConfigureXmlOutput() {
   3984   const std::string& output_format = UnitTestOptions::GetOutputFormat();
   3985   if (output_format == "xml") {
   3986     listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
   3987         UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
   3988   } else if (output_format != "") {
   3989     printf("WARNING: unrecognized output format \"%s\" ignored.\n",
   3990            output_format.c_str());
   3991     fflush(stdout);
   3992   }
   3993 }
   3994 
   3995 #if GTEST_CAN_STREAM_RESULTS_
   3996 // Initializes event listeners for streaming test results in string form.
   3997 // Must not be called before InitGoogleTest.
   3998 void UnitTestImpl::ConfigureStreamingOutput() {
   3999   const std::string& target = GTEST_FLAG(stream_result_to);
   4000   if (!target.empty()) {
   4001     const size_t pos = target.find(':');
   4002     if (pos != std::string::npos) {
   4003       listeners()->Append(new StreamingListener(target.substr(0, pos),
   4004                                                 target.substr(pos+1)));
   4005     } else {
   4006       printf("WARNING: unrecognized streaming target \"%s\" ignored.\n",
   4007              target.c_str());
   4008       fflush(stdout);
   4009     }
   4010   }
   4011 }
   4012 #endif  // GTEST_CAN_STREAM_RESULTS_
   4013 
   4014 // Performs initialization dependent upon flag values obtained in
   4015 // ParseGoogleTestFlagsOnly.  Is called from InitGoogleTest after the call to
   4016 // ParseGoogleTestFlagsOnly.  In case a user neglects to call InitGoogleTest
   4017 // this function is also called from RunAllTests.  Since this function can be
   4018 // called more than once, it has to be idempotent.
   4019 void UnitTestImpl::PostFlagParsingInit() {
   4020   // Ensures that this function does not execute more than once.
   4021   if (!post_flag_parse_init_performed_) {
   4022     post_flag_parse_init_performed_ = true;
   4023 
   4024 #if GTEST_HAS_DEATH_TEST
   4025     InitDeathTestSubprocessControlInfo();
   4026     SuppressTestEventsIfInSubprocess();
   4027 #endif  // GTEST_HAS_DEATH_TEST
   4028 
   4029     // Registers parameterized tests. This makes parameterized tests
   4030     // available to the UnitTest reflection API without running
   4031     // RUN_ALL_TESTS.
   4032     RegisterParameterizedTests();
   4033 
   4034     // Configures listeners for XML output. This makes it possible for users
   4035     // to shut down the default XML output before invoking RUN_ALL_TESTS.
   4036     ConfigureXmlOutput();
   4037 
   4038 #if GTEST_CAN_STREAM_RESULTS_
   4039     // Configures listeners for streaming test results to the specified server.
   4040     ConfigureStreamingOutput();
   4041 #endif  // GTEST_CAN_STREAM_RESULTS_
   4042   }
   4043 }
   4044 
   4045 // A predicate that checks the name of a TestCase against a known
   4046 // value.
   4047 //
   4048 // This is used for implementation of the UnitTest class only.  We put
   4049 // it in the anonymous namespace to prevent polluting the outer
   4050 // namespace.
   4051 //
   4052 // TestCaseNameIs is copyable.
   4053 class TestCaseNameIs {
   4054  public:
   4055   // Constructor.
   4056   explicit TestCaseNameIs(const std::string& name)
   4057       : name_(name) {}
   4058 
   4059   // Returns true iff the name of test_case matches name_.
   4060   bool operator()(const TestCase* test_case) const {
   4061     return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0;
   4062   }
   4063 
   4064  private:
   4065   std::string name_;
   4066 };
   4067 
   4068 // Finds and returns a TestCase with the given name.  If one doesn't
   4069 // exist, creates one and returns it.  It's the CALLER'S
   4070 // RESPONSIBILITY to ensure that this function is only called WHEN THE
   4071 // TESTS ARE NOT SHUFFLED.
   4072 //
   4073 // Arguments:
   4074 //
   4075 //   test_case_name: name of the test case
   4076 //   type_param:     the name of the test case's type parameter, or NULL if
   4077 //                   this is not a typed or a type-parameterized test case.
   4078 //   set_up_tc:      pointer to the function that sets up the test case
   4079 //   tear_down_tc:   pointer to the function that tears down the test case
   4080 TestCase* UnitTestImpl::GetTestCase(const char* test_case_name,
   4081                                     const char* type_param,
   4082                                     Test::SetUpTestCaseFunc set_up_tc,
   4083                                     Test::TearDownTestCaseFunc tear_down_tc) {
   4084   // Can we find a TestCase with the given name?
   4085   const std::vector<TestCase*>::const_iterator test_case =
   4086       std::find_if(test_cases_.begin(), test_cases_.end(),
   4087                    TestCaseNameIs(test_case_name));
   4088 
   4089   if (test_case != test_cases_.end())
   4090     return *test_case;
   4091 
   4092   // No.  Let's create one.
   4093   TestCase* const new_test_case =
   4094       new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc);
   4095 
   4096   // Is this a death test case?
   4097   if (internal::UnitTestOptions::MatchesFilter(test_case_name,
   4098                                                kDeathTestCaseFilter)) {
   4099     // Yes.  Inserts the test case after the last death test case
   4100     // defined so far.  This only works when the test cases haven't
   4101     // been shuffled.  Otherwise we may end up running a death test
   4102     // after a non-death test.
   4103     ++last_death_test_case_;
   4104     test_cases_.insert(test_cases_.begin() + last_death_test_case_,
   4105                        new_test_case);
   4106   } else {
   4107     // No.  Appends to the end of the list.
   4108     test_cases_.push_back(new_test_case);
   4109   }
   4110 
   4111   test_case_indices_.push_back(static_cast<int>(test_case_indices_.size()));
   4112   return new_test_case;
   4113 }
   4114 
   4115 // Helpers for setting up / tearing down the given environment.  They
   4116 // are for use in the ForEach() function.
   4117 static void SetUpEnvironment(Environment* env) { env->SetUp(); }
   4118 static void TearDownEnvironment(Environment* env) { env->TearDown(); }
   4119 
   4120 // Runs all tests in this UnitTest object, prints the result, and
   4121 // returns true if all tests are successful.  If any exception is
   4122 // thrown during a test, the test is considered to be failed, but the
   4123 // rest of the tests will still be run.
   4124 //
   4125 // When parameterized tests are enabled, it expands and registers
   4126 // parameterized tests first in RegisterParameterizedTests().
   4127 // All other functions called from RunAllTests() may safely assume that
   4128 // parameterized tests are ready to be counted and run.
   4129 bool UnitTestImpl::RunAllTests() {
   4130   // Makes sure InitGoogleTest() was called.
   4131   if (!GTestIsInitialized()) {
   4132     printf("%s",
   4133            "\nThis test program did NOT call ::testing::InitGoogleTest "
   4134            "before calling RUN_ALL_TESTS().  Please fix it.\n");
   4135     return false;
   4136   }
   4137 
   4138   // Do not run any test if the --help flag was specified.
   4139   if (g_help_flag)
   4140     return true;
   4141 
   4142   // Repeats the call to the post-flag parsing initialization in case the
   4143   // user didn't call InitGoogleTest.
   4144   PostFlagParsingInit();
   4145 
   4146   // Even if sharding is not on, test runners may want to use the
   4147   // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
   4148   // protocol.
   4149   internal::WriteToShardStatusFileIfNeeded();
   4150 
   4151   // True iff we are in a subprocess for running a thread-safe-style
   4152   // death test.
   4153   bool in_subprocess_for_death_test = false;
   4154 
   4155 #if GTEST_HAS_DEATH_TEST
   4156   in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL);
   4157 #endif  // GTEST_HAS_DEATH_TEST
   4158 
   4159   const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
   4160                                         in_subprocess_for_death_test);
   4161 
   4162   // Compares the full test names with the filter to decide which
   4163   // tests to run.
   4164   const bool has_tests_to_run = FilterTests(should_shard
   4165                                               ? HONOR_SHARDING_PROTOCOL
   4166                                               : IGNORE_SHARDING_PROTOCOL) > 0;
   4167 
   4168   // Lists the tests and exits if the --gtest_list_tests flag was specified.
   4169   if (GTEST_FLAG(list_tests)) {
   4170     // This must be called *after* FilterTests() has been called.
   4171     ListTestsMatchingFilter();
   4172     return true;
   4173   }
   4174 
   4175   random_seed_ = GTEST_FLAG(shuffle) ?
   4176       GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;
   4177 
   4178   // True iff at least one test has failed.
   4179   bool failed = false;
   4180 
   4181   TestEventListener* repeater = listeners()->repeater();
   4182 
   4183   start_timestamp_ = GetTimeInMillis();
   4184   repeater->OnTestProgramStart(*parent_);
   4185 
   4186   // How many times to repeat the tests?  We don't want to repeat them
   4187   // when we are inside the subprocess of a death test.
   4188   const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);
   4189   // Repeats forever if the repeat count is negative.
   4190   const bool forever = repeat < 0;
   4191   for (int i = 0; forever || i != repeat; i++) {
   4192     // We want to preserve failures generated by ad-hoc test
   4193     // assertions executed before RUN_ALL_TESTS().
   4194     ClearNonAdHocTestResult();
   4195 
   4196     const TimeInMillis start = GetTimeInMillis();
   4197 
   4198     // Shuffles test cases and tests if requested.
   4199     if (has_tests_to_run && GTEST_FLAG(shuffle)) {
   4200       random()->Reseed(random_seed_);
   4201       // This should be done before calling OnTestIterationStart(),
   4202       // such that a test event listener can see the actual test order
   4203       // in the event.
   4204       ShuffleTests();
   4205     }
   4206 
   4207     // Tells the unit test event listeners that the tests are about to start.
   4208     repeater->OnTestIterationStart(*parent_, i);
   4209 
   4210     // Runs each test case if there is at least one test to run.
   4211     if (has_tests_to_run) {
   4212       // Sets up all environments beforehand.
   4213       repeater->OnEnvironmentsSetUpStart(*parent_);
   4214       ForEach(environments_, SetUpEnvironment);
   4215       repeater->OnEnvironmentsSetUpEnd(*parent_);
   4216 
   4217       // Runs the tests only if there was no fatal failure during global
   4218       // set-up.
   4219       if (!Test::HasFatalFailure()) {
   4220         for (int test_index = 0; test_index < total_test_case_count();
   4221              test_index++) {
   4222           GetMutableTestCase(test_index)->Run();
   4223         }
   4224       }
   4225 
   4226       // Tears down all environments in reverse order afterwards.
   4227       repeater->OnEnvironmentsTearDownStart(*parent_);
   4228       std::for_each(environments_.rbegin(), environments_.rend(),
   4229                     TearDownEnvironment);
   4230       repeater->OnEnvironmentsTearDownEnd(*parent_);
   4231     }
   4232 
   4233     elapsed_time_ = GetTimeInMillis() - start;
   4234 
   4235     // Tells the unit test event listener that the tests have just finished.
   4236     repeater->OnTestIterationEnd(*parent_, i);
   4237 
   4238     // Gets the result and clears it.
   4239     if (!Passed()) {
   4240       failed = true;
   4241     }
   4242 
   4243     // Restores the original test order after the iteration.  This
   4244     // allows the user to quickly repro a failure that happens in the
   4245     // N-th iteration without repeating the first (N - 1) iterations.
   4246     // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in
   4247     // case the user somehow changes the value of the flag somewhere
   4248     // (it's always safe to unshuffle the tests).
   4249     UnshuffleTests();
   4250 
   4251     if (GTEST_FLAG(shuffle)) {
   4252       // Picks a new random seed for each iteration.
   4253       random_seed_ = GetNextRandomSeed(random_seed_);
   4254     }
   4255   }
   4256 
   4257   repeater->OnTestProgramEnd(*parent_);
   4258 
   4259   return !failed;
   4260 }
   4261 
   4262 // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
   4263 // if the variable is present. If a file already exists at this location, this
   4264 // function will write over it. If the variable is present, but the file cannot
   4265 // be created, prints an error and exits.
   4266 void WriteToShardStatusFileIfNeeded() {
   4267   const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);
   4268   if (test_shard_file != NULL) {
   4269     FILE* const file = posix::FOpen(test_shard_file, "w");
   4270     if (file == NULL) {
   4271       ColoredPrintf(COLOR_RED,
   4272                     "Could not write to the test shard status file \"%s\" "
   4273                     "specified by the %s environment variable.\n",
   4274                     test_shard_file, kTestShardStatusFile);
   4275       fflush(stdout);
   4276       exit(EXIT_FAILURE);
   4277     }
   4278     fclose(file);
   4279   }
   4280 }
   4281 
   4282 // Checks whether sharding is enabled by examining the relevant
   4283 // environment variable values. If the variables are present,
   4284 // but inconsistent (i.e., shard_index >= total_shards), prints
   4285 // an error and exits. If in_subprocess_for_death_test, sharding is
   4286 // disabled because it must only be applied to the original test
   4287 // process. Otherwise, we could filter out death tests we intended to execute.
   4288 bool ShouldShard(const char* total_shards_env,
   4289                  const char* shard_index_env,
   4290                  bool in_subprocess_for_death_test) {
   4291   if (in_subprocess_for_death_test) {
   4292     return false;
   4293   }
   4294 
   4295   const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1);
   4296   const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1);
   4297 
   4298   if (total_shards == -1 && shard_index == -1) {
   4299     return false;
   4300   } else if (total_shards == -1 && shard_index != -1) {
   4301     const Message msg = Message()
   4302       << "Invalid environment variables: you have "
   4303       << kTestShardIndex << " = " << shard_index
   4304       << ", but have left " << kTestTotalShards << " unset.\n";
   4305     ColoredPrintf(COLOR_RED, msg.GetString().c_str());
   4306     fflush(stdout);
   4307     exit(EXIT_FAILURE);
   4308   } else if (total_shards != -1 && shard_index == -1) {
   4309     const Message msg = Message()
   4310       << "Invalid environment variables: you have "
   4311       << kTestTotalShards << " = " << total_shards
   4312       << ", but have left " << kTestShardIndex << " unset.\n";
   4313     ColoredPrintf(COLOR_RED, msg.GetString().c_str());
   4314     fflush(stdout);
   4315     exit(EXIT_FAILURE);
   4316   } else if (shard_index < 0 || shard_index >= total_shards) {
   4317     const Message msg = Message()
   4318       << "Invalid environment variables: we require 0 <= "
   4319       << kTestShardIndex << " < " << kTestTotalShards
   4320       << ", but you have " << kTestShardIndex << "=" << shard_index
   4321       << ", " << kTestTotalShards << "=" << total_shards << ".\n";
   4322     ColoredPrintf(COLOR_RED, msg.GetString().c_str());
   4323     fflush(stdout);
   4324     exit(EXIT_FAILURE);
   4325   }
   4326 
   4327   return total_shards > 1;
   4328 }
   4329 
   4330 // Parses the environment variable var as an Int32. If it is unset,
   4331 // returns default_val. If it is not an Int32, prints an error
   4332 // and aborts.
   4333 Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) {
   4334   const char* str_val = posix::GetEnv(var);
   4335   if (str_val == NULL) {
   4336     return default_val;
   4337   }
   4338 
   4339   Int32 result;
   4340   if (!ParseInt32(Message() << "The value of environment variable " << var,
   4341                   str_val, &result)) {
   4342     exit(EXIT_FAILURE);
   4343   }
   4344   return result;
   4345 }
   4346 
   4347 // Given the total number of shards, the shard index, and the test id,
   4348 // returns true iff the test should be run on this shard. The test id is
   4349 // some arbitrary but unique non-negative integer assigned to each test
   4350 // method. Assumes that 0 <= shard_index < total_shards.
   4351 bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
   4352   return (test_id % total_shards) == shard_index;
   4353 }
   4354 
   4355 // Compares the name of each test with the user-specified filter to
   4356 // decide whether the test should be run, then records the result in
   4357 // each TestCase and TestInfo object.
   4358 // If shard_tests == true, further filters tests based on sharding
   4359 // variables in the environment - see
   4360 // http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide.
   4361 // Returns the number of tests that should run.
   4362 int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
   4363   const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?
   4364       Int32FromEnvOrDie(kTestTotalShards, -1) : -1;
   4365   const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?
   4366       Int32FromEnvOrDie(kTestShardIndex, -1) : -1;
   4367 
   4368   // num_runnable_tests are the number of tests that will
   4369   // run across all shards (i.e., match filter and are not disabled).
   4370   // num_selected_tests are the number of tests to be run on
   4371   // this shard.
   4372   int num_runnable_tests = 0;
   4373   int num_selected_tests = 0;
   4374   for (size_t i = 0; i < test_cases_.size(); i++) {
   4375     TestCase* const test_case = test_cases_[i];
   4376     const std::string &test_case_name = test_case->name();
   4377     test_case->set_should_run(false);
   4378 
   4379     for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
   4380       TestInfo* const test_info = test_case->test_info_list()[j];
   4381       const std::string test_name(test_info->name());
   4382       // A test is disabled if test case name or test name matches
   4383       // kDisableTestFilter.
   4384       const bool is_disabled =
   4385           internal::UnitTestOptions::MatchesFilter(test_case_name,
   4386                                                    kDisableTestFilter) ||
   4387           internal::UnitTestOptions::MatchesFilter(test_name,
   4388                                                    kDisableTestFilter);
   4389       test_info->is_disabled_ = is_disabled;
   4390 
   4391       const bool matches_filter =
   4392           internal::UnitTestOptions::FilterMatchesTest(test_case_name,
   4393                                                        test_name);
   4394       test_info->matches_filter_ = matches_filter;
   4395 
   4396       const bool is_runnable =
   4397           (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
   4398           matches_filter;
   4399 
   4400       const bool is_selected = is_runnable &&
   4401           (shard_tests == IGNORE_SHARDING_PROTOCOL ||
   4402            ShouldRunTestOnShard(total_shards, shard_index,
   4403                                 num_runnable_tests));
   4404 
   4405       num_runnable_tests += is_runnable;
   4406       num_selected_tests += is_selected;
   4407 
   4408       test_info->should_run_ = is_selected;
   4409       test_case->set_should_run(test_case->should_run() || is_selected);
   4410     }
   4411   }
   4412   return num_selected_tests;
   4413 }
   4414 
   4415 // Prints the given C-string on a single line by replacing all '\n'
   4416 // characters with string "\\n".  If the output takes more than
   4417 // max_length characters, only prints the first max_length characters
   4418 // and "...".
   4419 static void PrintOnOneLine(const char* str, int max_length) {
   4420   if (str != NULL) {
   4421     for (int i = 0; *str != '\0'; ++str) {
   4422       if (i >= max_length) {
   4423         printf("...");
   4424         break;
   4425       }
   4426       if (*str == '\n') {
   4427         printf("\\n");
   4428         i += 2;
   4429       } else {
   4430         printf("%c", *str);
   4431         ++i;
   4432       }
   4433     }
   4434   }
   4435 }
   4436 
   4437 // Prints the names of the tests matching the user-specified filter flag.
   4438 void UnitTestImpl::ListTestsMatchingFilter() {
   4439   // Print at most this many characters for each type/value parameter.
   4440   const int kMaxParamLength = 250;
   4441 
   4442   for (size_t i = 0; i < test_cases_.size(); i++) {
   4443     const TestCase* const test_case = test_cases_[i];
   4444     bool printed_test_case_name = false;
   4445 
   4446     for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
   4447       const TestInfo* const test_info =
   4448           test_case->test_info_list()[j];
   4449       if (test_info->matches_filter_) {
   4450         if (!printed_test_case_name) {
   4451           printed_test_case_name = true;
   4452           printf("%s.", test_case->name());
   4453           if (test_case->type_param() != NULL) {
   4454             printf("  # %s = ", kTypeParamLabel);
   4455             // We print the type parameter on a single line to make
   4456             // the output easy to parse by a program.
   4457             PrintOnOneLine(test_case->type_param(), kMaxParamLength);
   4458           }
   4459           printf("\n");
   4460         }
   4461         printf("  %s", test_info->name());
   4462         if (test_info->value_param() != NULL) {
   4463           printf("  # %s = ", kValueParamLabel);
   4464           // We print the value parameter on a single line to make the
   4465           // output easy to parse by a program.
   4466           PrintOnOneLine(test_info->value_param(), kMaxParamLength);
   4467         }
   4468         printf("\n");
   4469       }
   4470     }
   4471   }
   4472   fflush(stdout);
   4473 }
   4474 
   4475 // Sets the OS stack trace getter.
   4476 //
   4477 // Does nothing if the input and the current OS stack trace getter are
   4478 // the same; otherwise, deletes the old getter and makes the input the
   4479 // current getter.
   4480 void UnitTestImpl::set_os_stack_trace_getter(
   4481     OsStackTraceGetterInterface* getter) {
   4482   if (os_stack_trace_getter_ != getter) {
   4483     delete os_stack_trace_getter_;
   4484     os_stack_trace_getter_ = getter;
   4485   }
   4486 }
   4487 
   4488 // Returns the current OS stack trace getter if it is not NULL;
   4489 // otherwise, creates an OsStackTraceGetter, makes it the current
   4490 // getter, and returns it.
   4491 OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
   4492   if (os_stack_trace_getter_ == NULL) {
   4493     os_stack_trace_getter_ = new OsStackTraceGetter;
   4494   }
   4495 
   4496   return os_stack_trace_getter_;
   4497 }
   4498 
   4499 // Returns the TestResult for the test that's currently running, or
   4500 // the TestResult for the ad hoc test if no test is running.
   4501 TestResult* UnitTestImpl::current_test_result() {
   4502   return current_test_info_ ?
   4503       &(current_test_info_->result_) : &ad_hoc_test_result_;
   4504 }
   4505 
   4506 // Shuffles all test cases, and the tests within each test case,
   4507 // making sure that death tests are still run first.
   4508 void UnitTestImpl::ShuffleTests() {
   4509   // Shuffles the death test cases.
   4510   ShuffleRange(random(), 0, last_death_test_case_ + 1, &test_case_indices_);
   4511 
   4512   // Shuffles the non-death test cases.
   4513   ShuffleRange(random(), last_death_test_case_ + 1,
   4514                static_cast<int>(test_cases_.size()), &test_case_indices_);
   4515 
   4516   // Shuffles the tests inside each test case.
   4517   for (size_t i = 0; i < test_cases_.size(); i++) {
   4518     test_cases_[i]->ShuffleTests(random());
   4519   }
   4520 }
   4521 
   4522 // Restores the test cases and tests to their order before the first shuffle.
   4523 void UnitTestImpl::UnshuffleTests() {
   4524   for (size_t i = 0; i < test_cases_.size(); i++) {
   4525     // Unshuffles the tests in each test case.
   4526     test_cases_[i]->UnshuffleTests();
   4527     // Resets the index of each test case.
   4528     test_case_indices_[i] = static_cast<int>(i);
   4529   }
   4530 }
   4531 
   4532 // Returns the current OS stack trace as an std::string.
   4533 //
   4534 // The maximum number of stack frames to be included is specified by
   4535 // the gtest_stack_trace_depth flag.  The skip_count parameter
   4536 // specifies the number of top frames to be skipped, which doesn't
   4537 // count against the number of frames to be included.
   4538 //
   4539 // For example, if Foo() calls Bar(), which in turn calls
   4540 // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
   4541 // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
   4542 std::string GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/,
   4543                                             int skip_count) {
   4544   // We pass skip_count + 1 to skip this wrapper function in addition
   4545   // to what the user really wants to skip.
   4546   return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
   4547 }
   4548 
   4549 // Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to
   4550 // suppress unreachable code warnings.
   4551 namespace {
   4552 class ClassUniqueToAlwaysTrue {};
   4553 }
   4554 
   4555 bool IsTrue(bool condition) { return condition; }
   4556 
   4557 bool AlwaysTrue() {
   4558 #if GTEST_HAS_EXCEPTIONS
   4559   // This condition is always false so AlwaysTrue() never actually throws,
   4560   // but it makes the compiler think that it may throw.
   4561   if (IsTrue(false))
   4562     throw ClassUniqueToAlwaysTrue();
   4563 #endif  // GTEST_HAS_EXCEPTIONS
   4564   return true;
   4565 }
   4566 
   4567 // If *pstr starts with the given prefix, modifies *pstr to be right
   4568 // past the prefix and returns true; otherwise leaves *pstr unchanged
   4569 // and returns false.  None of pstr, *pstr, and prefix can be NULL.
   4570 bool SkipPrefix(const char* prefix, const char** pstr) {
   4571   const size_t prefix_len = strlen(prefix);
   4572   if (strncmp(*pstr, prefix, prefix_len) == 0) {
   4573     *pstr += prefix_len;
   4574     return true;
   4575   }
   4576   return false;
   4577 }
   4578 
   4579 // Parses a string as a command line flag.  The string should have
   4580 // the format "--flag=value".  When def_optional is true, the "=value"
   4581 // part can be omitted.
   4582 //
   4583 // Returns the value of the flag, or NULL if the parsing failed.
   4584 const char* ParseFlagValue(const char* str,
   4585                            const char* flag,
   4586                            bool def_optional) {
   4587   // str and flag must not be NULL.
   4588   if (str == NULL || flag == NULL) return NULL;
   4589 
   4590   // The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
   4591   const std::string flag_str = std::string("--") + GTEST_FLAG_PREFIX_ + flag;
   4592   const size_t flag_len = flag_str.length();
   4593   if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;
   4594 
   4595   // Skips the flag name.
   4596   const char* flag_end = str + flag_len;
   4597 
   4598   // When def_optional is true, it's OK to not have a "=value" part.
   4599   if (def_optional && (flag_end[0] == '\0')) {
   4600     return flag_end;
   4601   }
   4602 
   4603   // If def_optional is true and there are more characters after the
   4604   // flag name, or if def_optional is false, there must be a '=' after
   4605   // the flag name.
   4606   if (flag_end[0] != '=') return NULL;
   4607 
   4608   // Returns the string after "=".
   4609   return flag_end + 1;
   4610 }
   4611 
   4612 // Parses a string for a bool flag, in the form of either
   4613 // "--flag=value" or "--flag".
   4614 //
   4615 // In the former case, the value is taken as true as long as it does
   4616 // not start with '0', 'f', or 'F'.
   4617 //
   4618 // In the latter case, the value is taken as true.
   4619 //
   4620 // On success, stores the value of the flag in *value, and returns
   4621 // true.  On failure, returns false without changing *value.
   4622 bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
   4623   // Gets the value of the flag as a string.
   4624   const char* const value_str = ParseFlagValue(str, flag, true);
   4625 
   4626   // Aborts if the parsing failed.
   4627   if (value_str == NULL) return false;
   4628 
   4629   // Converts the string value to a bool.
   4630   *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
   4631   return true;
   4632 }
   4633 
   4634 // Parses a string for an Int32 flag, in the form of
   4635 // "--flag=value".
   4636 //
   4637 // On success, stores the value of the flag in *value, and returns
   4638 // true.  On failure, returns false without changing *value.
   4639 bool ParseInt32Flag(const char* str, const char* flag, Int32* value) {
   4640   // Gets the value of the flag as a string.
   4641   const char* const value_str = ParseFlagValue(str, flag, false);
   4642 
   4643   // Aborts if the parsing failed.
   4644   if (value_str == NULL) return false;
   4645 
   4646   // Sets *value to the value of the flag.
   4647   return ParseInt32(Message() << "The value of flag --" << flag,
   4648                     value_str, value);
   4649 }
   4650 
   4651 // Parses a string for a string flag, in the form of
   4652 // "--flag=value".
   4653 //
   4654 // On success, stores the value of the flag in *value, and returns
   4655 // true.  On failure, returns false without changing *value.
   4656 bool ParseStringFlag(const char* str, const char* flag, std::string* value) {
   4657   // Gets the value of the flag as a string.
   4658   const char* const value_str = ParseFlagValue(str, flag, false);
   4659 
   4660   // Aborts if the parsing failed.
   4661   if (value_str == NULL) return false;
   4662 
   4663   // Sets *value to the value of the flag.
   4664   *value = value_str;
   4665   return true;
   4666 }
   4667 
   4668 // Determines whether a string has a prefix that Google Test uses for its
   4669 // flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.
   4670 // If Google Test detects that a command line flag has its prefix but is not
   4671 // recognized, it will print its help message. Flags starting with
   4672 // GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
   4673 // internal flags and do not trigger the help message.
   4674 static bool HasGoogleTestFlagPrefix(const char* str) {
   4675   return (SkipPrefix("--", &str) ||
   4676           SkipPrefix("-", &str) ||
   4677           SkipPrefix("/", &str)) &&
   4678          !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
   4679          (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
   4680           SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str));
   4681 }
   4682 
   4683 // Prints a string containing code-encoded text.  The following escape
   4684 // sequences can be used in the string to control the text color:
   4685 //
   4686 //   @@    prints a single '@' character.
   4687 //   @R    changes the color to red.
   4688 //   @G    changes the color to green.
   4689 //   @Y    changes the color to yellow.
   4690 //   @D    changes to the default terminal text color.
   4691 //
   4692 // TODO(wan (at) google.com): Write tests for this once we add stdout
   4693 // capturing to Google Test.
   4694 static void PrintColorEncoded(const char* str) {
   4695   GTestColor color = COLOR_DEFAULT;  // The current color.
   4696 
   4697   // Conceptually, we split the string into segments divided by escape
   4698   // sequences.  Then we print one segment at a time.  At the end of
   4699   // each iteration, the str pointer advances to the beginning of the
   4700   // next segment.
   4701   for (;;) {
   4702     const char* p = strchr(str, '@');
   4703     if (p == NULL) {
   4704       ColoredPrintf(color, "%s", str);
   4705       return;
   4706     }
   4707 
   4708     ColoredPrintf(color, "%s", std::string(str, p).c_str());
   4709 
   4710     const char ch = p[1];
   4711     str = p + 2;
   4712     if (ch == '@') {
   4713       ColoredPrintf(color, "@");
   4714     } else if (ch == 'D') {
   4715       color = COLOR_DEFAULT;
   4716     } else if (ch == 'R') {
   4717       color = COLOR_RED;
   4718     } else if (ch == 'G') {
   4719       color = COLOR_GREEN;
   4720     } else if (ch == 'Y') {
   4721       color = COLOR_YELLOW;
   4722     } else {
   4723       --str;
   4724     }
   4725   }
   4726 }
   4727 
   4728 static const char kColorEncodedHelpMessage[] =
   4729 "This program contains tests written using " GTEST_NAME_ ". You can use the\n"
   4730 "following command line flags to control its behavior:\n"
   4731 "\n"
   4732 "Test Selection:\n"
   4733 "  @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n"
   4734 "      List the names of all tests instead of running them. The name of\n"
   4735 "      TEST(Foo, Bar) is \"Foo.Bar\".\n"
   4736 "  @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS"
   4737     "[@G-@YNEGATIVE_PATTERNS]@D\n"
   4738 "      Run only the tests whose name matches one of the positive patterns but\n"
   4739 "      none of the negative patterns. '?' matches any single character; '*'\n"
   4740 "      matches any substring; ':' separates two patterns.\n"
   4741 "  @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n"
   4742 "      Run all disabled tests too.\n"
   4743 "\n"
   4744 "Test Execution:\n"
   4745 "  @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n"
   4746 "      Run the tests repeatedly; use a negative count to repeat forever.\n"
   4747 "  @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n"
   4748 "      Randomize tests' orders on every iteration.\n"
   4749 "  @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n"
   4750 "      Random number seed to use for shuffling test orders (between 1 and\n"
   4751 "      99999, or 0 to use a seed based on the current time).\n"
   4752 "\n"
   4753 "Test Output:\n"
   4754 "  @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
   4755 "      Enable/disable colored output. The default is @Gauto@D.\n"
   4756 "  -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n"
   4757 "      Don't print the elapsed time of each test.\n"
   4758 "  @G--" GTEST_FLAG_PREFIX_ "output=xml@Y[@G:@YDIRECTORY_PATH@G"
   4759     GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n"
   4760 "      Generate an XML report in the given directory or with the given file\n"
   4761 "      name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n"
   4762 #if GTEST_CAN_STREAM_RESULTS_
   4763 "  @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n"
   4764 "      Stream test results to the given server.\n"
   4765 #endif  // GTEST_CAN_STREAM_RESULTS_
   4766 "\n"
   4767 "Assertion Behavior:\n"
   4768 #if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
   4769 "  @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
   4770 "      Set the default death test style.\n"
   4771 #endif  // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
   4772 "  @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n"
   4773 "      Turn assertion failures into debugger break-points.\n"
   4774 "  @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n"
   4775 "      Turn assertion failures into C++ exceptions.\n"
   4776 "  @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n"
   4777 "      Do not report exceptions as test failures. Instead, allow them\n"
   4778 "      to crash the program or throw a pop-up (on Windows).\n"
   4779 "\n"
   4780 "Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set "
   4781     "the corresponding\n"
   4782 "environment variable of a flag (all letters in upper-case). For example, to\n"
   4783 "disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_
   4784     "color=no@D or set\n"
   4785 "the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n"
   4786 "\n"
   4787 "For more information, please read the " GTEST_NAME_ " documentation at\n"
   4788 "@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n"
   4789 "(not one in your own code or tests), please report it to\n"
   4790 "@G<" GTEST_DEV_EMAIL_ ">@D.\n";
   4791 
   4792 // Parses the command line for Google Test flags, without initializing
   4793 // other parts of Google Test.  The type parameter CharType can be
   4794 // instantiated to either char or wchar_t.
   4795 template <typename CharType>
   4796 void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
   4797   for (int i = 1; i < *argc; i++) {
   4798     const std::string arg_string = StreamableToString(argv[i]);
   4799     const char* const arg = arg_string.c_str();
   4800 
   4801     using internal::ParseBoolFlag;
   4802     using internal::ParseInt32Flag;
   4803     using internal::ParseStringFlag;
   4804 
   4805     // Do we see a Google Test flag?
   4806     if (ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,
   4807                       &GTEST_FLAG(also_run_disabled_tests)) ||
   4808         ParseBoolFlag(arg, kBreakOnFailureFlag,
   4809                       &GTEST_FLAG(break_on_failure)) ||
   4810         ParseBoolFlag(arg, kCatchExceptionsFlag,
   4811                       &GTEST_FLAG(catch_exceptions)) ||
   4812         ParseStringFlag(arg, kColorFlag, &GTEST_FLAG(color)) ||
   4813         ParseStringFlag(arg, kDeathTestStyleFlag,
   4814                         &GTEST_FLAG(death_test_style)) ||
   4815         ParseBoolFlag(arg, kDeathTestUseFork,
   4816                       &GTEST_FLAG(death_test_use_fork)) ||
   4817         ParseStringFlag(arg, kFilterFlag, &GTEST_FLAG(filter)) ||
   4818         ParseStringFlag(arg, kInternalRunDeathTestFlag,
   4819                         &GTEST_FLAG(internal_run_death_test)) ||
   4820         ParseBoolFlag(arg, kListTestsFlag, &GTEST_FLAG(list_tests)) ||
   4821         ParseStringFlag(arg, kOutputFlag, &GTEST_FLAG(output)) ||
   4822         ParseBoolFlag(arg, kPrintTimeFlag, &GTEST_FLAG(print_time)) ||
   4823         ParseInt32Flag(arg, kRandomSeedFlag, &GTEST_FLAG(random_seed)) ||
   4824         ParseInt32Flag(arg, kRepeatFlag, &GTEST_FLAG(repeat)) ||
   4825         ParseBoolFlag(arg, kShuffleFlag, &GTEST_FLAG(shuffle)) ||
   4826         ParseInt32Flag(arg, kStackTraceDepthFlag,
   4827                        &GTEST_FLAG(stack_trace_depth)) ||
   4828         ParseStringFlag(arg, kStreamResultToFlag,
   4829                         &GTEST_FLAG(stream_result_to)) ||
   4830         ParseBoolFlag(arg, kThrowOnFailureFlag,
   4831                       &GTEST_FLAG(throw_on_failure))
   4832         ) {
   4833       // Yes.  Shift the remainder of the argv list left by one.  Note
   4834       // that argv has (*argc + 1) elements, the last one always being
   4835       // NULL.  The following loop moves the trailing NULL element as
   4836       // well.
   4837       for (int j = i; j != *argc; j++) {
   4838         argv[j] = argv[j + 1];
   4839       }
   4840 
   4841       // Decrements the argument count.
   4842       (*argc)--;
   4843 
   4844       // We also need to decrement the iterator as we just removed
   4845       // an element.
   4846       i--;
   4847     } else if (arg_string == "--help" || arg_string == "-h" ||
   4848                arg_string == "-?" || arg_string == "/?" ||
   4849                HasGoogleTestFlagPrefix(arg)) {
   4850       // Both help flag and unrecognized Google Test flags (excluding
   4851       // internal ones) trigger help display.
   4852       g_help_flag = true;
   4853     }
   4854   }
   4855 
   4856   if (g_help_flag) {
   4857     // We print the help here instead of in RUN_ALL_TESTS(), as the
   4858     // latter may not be called at all if the user is using Google
   4859     // Test with another testing framework.
   4860     PrintColorEncoded(kColorEncodedHelpMessage);
   4861   }
   4862 }
   4863 
   4864 // Parses the command line for Google Test flags, without initializing
   4865 // other parts of Google Test.
   4866 void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
   4867   ParseGoogleTestFlagsOnlyImpl(argc, argv);
   4868 }
   4869 void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {
   4870   ParseGoogleTestFlagsOnlyImpl(argc, argv);
   4871 }
   4872 
   4873 // The internal implementation of InitGoogleTest().
   4874 //
   4875 // The type parameter CharType can be instantiated to either char or
   4876 // wchar_t.
   4877 template <typename CharType>
   4878 void InitGoogleTestImpl(int* argc, CharType** argv) {
   4879   g_init_gtest_count++;
   4880 
   4881   // We don't want to run the initialization code twice.
   4882   if (g_init_gtest_count != 1) return;
   4883 
   4884   if (*argc <= 0) return;
   4885 
   4886   internal::g_executable_path = internal::StreamableToString(argv[0]);
   4887 
   4888 #if GTEST_HAS_DEATH_TEST
   4889 
   4890   g_argvs.clear();
   4891   for (int i = 0; i != *argc; i++) {
   4892     g_argvs.push_back(StreamableToString(argv[i]));
   4893   }
   4894 
   4895 #endif  // GTEST_HAS_DEATH_TEST
   4896 
   4897   ParseGoogleTestFlagsOnly(argc, argv);
   4898   GetUnitTestImpl()->PostFlagParsingInit();
   4899 }
   4900 
   4901 }  // namespace internal
   4902 
   4903 // Initializes Google Test.  This must be called before calling
   4904 // RUN_ALL_TESTS().  In particular, it parses a command line for the
   4905 // flags that Google Test recognizes.  Whenever a Google Test flag is
   4906 // seen, it is removed from argv, and *argc is decremented.
   4907 //
   4908 // No value is returned.  Instead, the Google Test flag variables are
   4909 // updated.
   4910 //
   4911 // Calling the function for the second time has no user-visible effect.
   4912 void InitGoogleTest(int* argc, char** argv) {
   4913   internal::InitGoogleTestImpl(argc, argv);
   4914 }
   4915 
   4916 // This overloaded version can be used in Windows programs compiled in
   4917 // UNICODE mode.
   4918 void InitGoogleTest(int* argc, wchar_t** argv) {
   4919   internal::InitGoogleTestImpl(argc, argv);
   4920 }
   4921 
   4922 }  // namespace testing
   4923