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


rc_visard_driver
Author(s): Heiko Hirschmueller , Christian Emmerich , Felix Ruess
autogenerated on Thu Jun 6 2019 20:43:04