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


ros_opcua_impl_freeopcua
Author(s): Denis Štogl
autogenerated on Sat Jun 8 2019 18:24:48