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


pcl
Author(s): Open Perception
autogenerated on Wed Aug 26 2015 15:24:40