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