gtest-all.cc
Go to the documentation of this file.
00001 // Copyright 2008, 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: mheule@google.com (Markus Heule)
00031 //
00032 // Google C++ Testing Framework (Google Test)
00033 //
00034 // Sometimes it's desirable to build Google Test by compiling a single file.
00035 // This file serves this purpose.
00036 
00037 // This line ensures that gtest.h can be compiled on its own, even
00038 // when it's fused.
00039 #include "gtest/gtest.h"
00040 
00041 // The following lines pull in the real gtest *.cc files.
00042 // Copyright 2005, Google Inc.
00043 // All rights reserved.
00044 //
00045 // Redistribution and use in source and binary forms, with or without
00046 // modification, are permitted provided that the following conditions are
00047 // met:
00048 //
00049 //     * Redistributions of source code must retain the above copyright
00050 // notice, this list of conditions and the following disclaimer.
00051 //     * Redistributions in binary form must reproduce the above
00052 // copyright notice, this list of conditions and the following disclaimer
00053 // in the documentation and/or other materials provided with the
00054 // distribution.
00055 //     * Neither the name of Google Inc. nor the names of its
00056 // contributors may be used to endorse or promote products derived from
00057 // this software without specific prior written permission.
00058 //
00059 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
00060 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
00061 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
00062 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
00063 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
00064 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
00065 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
00066 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
00067 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
00068 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
00069 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
00070 //
00071 // Author: wan@google.com (Zhanyong Wan)
00072 //
00073 // The Google C++ Testing Framework (Google Test)
00074 
00075 // Copyright 2007, Google Inc.
00076 // All rights reserved.
00077 //
00078 // Redistribution and use in source and binary forms, with or without
00079 // modification, are permitted provided that the following conditions are
00080 // met:
00081 //
00082 //     * Redistributions of source code must retain the above copyright
00083 // notice, this list of conditions and the following disclaimer.
00084 //     * Redistributions in binary form must reproduce the above
00085 // copyright notice, this list of conditions and the following disclaimer
00086 // in the documentation and/or other materials provided with the
00087 // distribution.
00088 //     * Neither the name of Google Inc. nor the names of its
00089 // contributors may be used to endorse or promote products derived from
00090 // this software without specific prior written permission.
00091 //
00092 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
00093 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
00094 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
00095 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
00096 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
00097 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
00098 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
00099 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
00100 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
00101 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
00102 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
00103 //
00104 // Author: wan@google.com (Zhanyong Wan)
00105 //
00106 // Utilities for testing Google Test itself and code that uses Google Test
00107 // (e.g. frameworks built on top of Google Test).
00108 
00109 #ifndef GTEST_INCLUDE_GTEST_GTEST_SPI_H_
00110 #define GTEST_INCLUDE_GTEST_GTEST_SPI_H_
00111 
00112 
00113 namespace testing {
00114 
00115 // This helper class can be used to mock out Google Test failure reporting
00116 // so that we can test Google Test or code that builds on Google Test.
00117 //
00118 // An object of this class appends a TestPartResult object to the
00119 // TestPartResultArray object given in the constructor whenever a Google Test
00120 // failure is reported. It can either intercept only failures that are
00121 // generated in the same thread that created this object or it can intercept
00122 // all generated failures. The scope of this mock object can be controlled with
00123 // the second argument to the two arguments constructor.
00124 class GTEST_API_ ScopedFakeTestPartResultReporter
00125     : public TestPartResultReporterInterface {
00126  public:
00127   // The two possible mocking modes of this object.
00128   enum InterceptMode {
00129     INTERCEPT_ONLY_CURRENT_THREAD,  // Intercepts only thread local failures.
00130     INTERCEPT_ALL_THREADS           // Intercepts all failures.
00131   };
00132 
00133   // The c'tor sets this object as the test part result reporter used
00134   // by Google Test.  The 'result' parameter specifies where to report the
00135   // results. This reporter will only catch failures generated in the current
00136   // thread. DEPRECATED
00137   explicit ScopedFakeTestPartResultReporter(TestPartResultArray* result);
00138 
00139   // Same as above, but you can choose the interception scope of this object.
00140   ScopedFakeTestPartResultReporter(InterceptMode intercept_mode,
00141                                    TestPartResultArray* result);
00142 
00143   // The d'tor restores the previous test part result reporter.
00144   virtual ~ScopedFakeTestPartResultReporter();
00145 
00146   // Appends the TestPartResult object to the TestPartResultArray
00147   // received in the constructor.
00148   //
00149   // This method is from the TestPartResultReporterInterface
00150   // interface.
00151   virtual void ReportTestPartResult(const TestPartResult& result);
00152  private:
00153   void Init();
00154 
00155   const InterceptMode intercept_mode_;
00156   TestPartResultReporterInterface* old_reporter_;
00157   TestPartResultArray* const result_;
00158 
00159   GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedFakeTestPartResultReporter);
00160 };
00161 
00162 namespace internal {
00163 
00164 // A helper class for implementing EXPECT_FATAL_FAILURE() and
00165 // EXPECT_NONFATAL_FAILURE().  Its destructor verifies that the given
00166 // TestPartResultArray contains exactly one failure that has the given
00167 // type and contains the given substring.  If that's not the case, a
00168 // non-fatal failure will be generated.
00169 class GTEST_API_ SingleFailureChecker {
00170  public:
00171   // The constructor remembers the arguments.
00172   SingleFailureChecker(const TestPartResultArray* results,
00173                        TestPartResult::Type type,
00174                        const string& substr);
00175   ~SingleFailureChecker();
00176  private:
00177   const TestPartResultArray* const results_;
00178   const TestPartResult::Type type_;
00179   const string substr_;
00180 
00181   GTEST_DISALLOW_COPY_AND_ASSIGN_(SingleFailureChecker);
00182 };
00183 
00184 }  // namespace internal
00185 
00186 }  // namespace testing
00187 
00188 // A set of macros for testing Google Test assertions or code that's expected
00189 // to generate Google Test fatal failures.  It verifies that the given
00190 // statement will cause exactly one fatal Google Test failure with 'substr'
00191 // being part of the failure message.
00192 //
00193 // There are two different versions of this macro. EXPECT_FATAL_FAILURE only
00194 // affects and considers failures generated in the current thread and
00195 // EXPECT_FATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
00196 //
00197 // The verification of the assertion is done correctly even when the statement
00198 // throws an exception or aborts the current function.
00199 //
00200 // Known restrictions:
00201 //   - 'statement' cannot reference local non-static variables or
00202 //     non-static members of the current object.
00203 //   - 'statement' cannot return a value.
00204 //   - You cannot stream a failure message to this macro.
00205 //
00206 // Note that even though the implementations of the following two
00207 // macros are much alike, we cannot refactor them to use a common
00208 // helper macro, due to some peculiarity in how the preprocessor
00209 // works.  The AcceptsMacroThatExpandsToUnprotectedComma test in
00210 // gtest_unittest.cc will fail to compile if we do that.
00211 #define EXPECT_FATAL_FAILURE(statement, substr) \
00212   do { \
00213     class GTestExpectFatalFailureHelper {\
00214      public:\
00215       static void Execute() { statement; }\
00216     };\
00217     ::testing::TestPartResultArray gtest_failures;\
00218     ::testing::internal::SingleFailureChecker gtest_checker(\
00219         &gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
00220     {\
00221       ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
00222           ::testing::ScopedFakeTestPartResultReporter:: \
00223           INTERCEPT_ONLY_CURRENT_THREAD, &gtest_failures);\
00224       GTestExpectFatalFailureHelper::Execute();\
00225     }\
00226   } while (::testing::internal::AlwaysFalse())
00227 
00228 #define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
00229   do { \
00230     class GTestExpectFatalFailureHelper {\
00231      public:\
00232       static void Execute() { statement; }\
00233     };\
00234     ::testing::TestPartResultArray gtest_failures;\
00235     ::testing::internal::SingleFailureChecker gtest_checker(\
00236         &gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
00237     {\
00238       ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
00239           ::testing::ScopedFakeTestPartResultReporter:: \
00240           INTERCEPT_ALL_THREADS, &gtest_failures);\
00241       GTestExpectFatalFailureHelper::Execute();\
00242     }\
00243   } while (::testing::internal::AlwaysFalse())
00244 
00245 // A macro for testing Google Test assertions or code that's expected to
00246 // generate Google Test non-fatal failures.  It asserts that the given
00247 // statement will cause exactly one non-fatal Google Test failure with 'substr'
00248 // being part of the failure message.
00249 //
00250 // There are two different versions of this macro. EXPECT_NONFATAL_FAILURE only
00251 // affects and considers failures generated in the current thread and
00252 // EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
00253 //
00254 // 'statement' is allowed to reference local variables and members of
00255 // the current object.
00256 //
00257 // The verification of the assertion is done correctly even when the statement
00258 // throws an exception or aborts the current function.
00259 //
00260 // Known restrictions:
00261 //   - You cannot stream a failure message to this macro.
00262 //
00263 // Note that even though the implementations of the following two
00264 // macros are much alike, we cannot refactor them to use a common
00265 // helper macro, due to some peculiarity in how the preprocessor
00266 // works.  If we do that, the code won't compile when the user gives
00267 // EXPECT_NONFATAL_FAILURE() a statement that contains a macro that
00268 // expands to code containing an unprotected comma.  The
00269 // AcceptsMacroThatExpandsToUnprotectedComma test in gtest_unittest.cc
00270 // catches that.
00271 //
00272 // For the same reason, we have to write
00273 //   if (::testing::internal::AlwaysTrue()) { statement; }
00274 // instead of
00275 //   GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)
00276 // to avoid an MSVC warning on unreachable code.
00277 #define EXPECT_NONFATAL_FAILURE(statement, substr) \
00278   do {\
00279     ::testing::TestPartResultArray gtest_failures;\
00280     ::testing::internal::SingleFailureChecker gtest_checker(\
00281         &gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \
00282         (substr));\
00283     {\
00284       ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
00285           ::testing::ScopedFakeTestPartResultReporter:: \
00286           INTERCEPT_ONLY_CURRENT_THREAD, &gtest_failures);\
00287       if (::testing::internal::AlwaysTrue()) { statement; }\
00288     }\
00289   } while (::testing::internal::AlwaysFalse())
00290 
00291 #define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
00292   do {\
00293     ::testing::TestPartResultArray gtest_failures;\
00294     ::testing::internal::SingleFailureChecker gtest_checker(\
00295         &gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \
00296         (substr));\
00297     {\
00298       ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
00299           ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \
00300           &gtest_failures);\
00301       if (::testing::internal::AlwaysTrue()) { statement; }\
00302     }\
00303   } while (::testing::internal::AlwaysFalse())
00304 
00305 #endif  // GTEST_INCLUDE_GTEST_GTEST_SPI_H_
00306 
00307 #include <ctype.h>
00308 #include <math.h>
00309 #include <stdarg.h>
00310 #include <stdio.h>
00311 #include <stdlib.h>
00312 #include <time.h>
00313 #include <wchar.h>
00314 #include <wctype.h>
00315 
00316 #include <algorithm>
00317 #include <iomanip>
00318 #include <limits>
00319 #include <ostream>  // NOLINT
00320 #include <sstream>
00321 #include <vector>
00322 
00323 #if GTEST_OS_LINUX
00324 
00325 // TODO(kenton@google.com): Use autoconf to detect availability of
00326 // gettimeofday().
00327 # define GTEST_HAS_GETTIMEOFDAY_ 1
00328 
00329 # include <fcntl.h>  // NOLINT
00330 # include <limits.h>  // NOLINT
00331 # include <sched.h>  // NOLINT
00332 // Declares vsnprintf().  This header is not available on Windows.
00333 # include <strings.h>  // NOLINT
00334 # include <sys/mman.h>  // NOLINT
00335 # include <sys/time.h>  // NOLINT
00336 # include <unistd.h>  // NOLINT
00337 # include <string>
00338 
00339 #elif GTEST_OS_SYMBIAN
00340 # define GTEST_HAS_GETTIMEOFDAY_ 1
00341 # include <sys/time.h>  // NOLINT
00342 
00343 #elif GTEST_OS_ZOS
00344 # define GTEST_HAS_GETTIMEOFDAY_ 1
00345 # include <sys/time.h>  // NOLINT
00346 
00347 // On z/OS we additionally need strings.h for strcasecmp.
00348 # include <strings.h>  // NOLINT
00349 
00350 #elif GTEST_OS_WINDOWS_MOBILE  // We are on Windows CE.
00351 
00352 # include <windows.h>  // NOLINT
00353 
00354 #elif GTEST_OS_WINDOWS  // We are on Windows proper.
00355 
00356 # include <io.h>  // NOLINT
00357 # include <sys/timeb.h>  // NOLINT
00358 # include <sys/types.h>  // NOLINT
00359 # include <sys/stat.h>  // NOLINT
00360 
00361 # if GTEST_OS_WINDOWS_MINGW
00362 // MinGW has gettimeofday() but not _ftime64().
00363 // TODO(kenton@google.com): Use autoconf to detect availability of
00364 //   gettimeofday().
00365 // TODO(kenton@google.com): There are other ways to get the time on
00366 //   Windows, like GetTickCount() or GetSystemTimeAsFileTime().  MinGW
00367 //   supports these.  consider using them instead.
00368 #  define GTEST_HAS_GETTIMEOFDAY_ 1
00369 #  include <sys/time.h>  // NOLINT
00370 # endif  // GTEST_OS_WINDOWS_MINGW
00371 
00372 // cpplint thinks that the header is already included, so we want to
00373 // silence it.
00374 # include <windows.h>  // NOLINT
00375 
00376 #else
00377 
00378 // Assume other platforms have gettimeofday().
00379 // TODO(kenton@google.com): Use autoconf to detect availability of
00380 //   gettimeofday().
00381 # define GTEST_HAS_GETTIMEOFDAY_ 1
00382 
00383 // cpplint thinks that the header is already included, so we want to
00384 // silence it.
00385 # include <sys/time.h>  // NOLINT
00386 # include <unistd.h>  // NOLINT
00387 
00388 #endif  // GTEST_OS_LINUX
00389 
00390 #if GTEST_HAS_EXCEPTIONS
00391 # include <stdexcept>
00392 #endif
00393 
00394 #if GTEST_CAN_STREAM_RESULTS_
00395 # include <arpa/inet.h>  // NOLINT
00396 # include <netdb.h>  // NOLINT
00397 #endif
00398 
00399 // Indicates that this translation unit is part of Google Test's
00400 // implementation.  It must come before gtest-internal-inl.h is
00401 // included, or there will be a compiler error.  This trick is to
00402 // prevent a user from accidentally including gtest-internal-inl.h in
00403 // his code.
00404 #define GTEST_IMPLEMENTATION_ 1
00405 // Copyright 2005, Google Inc.
00406 // All rights reserved.
00407 //
00408 // Redistribution and use in source and binary forms, with or without
00409 // modification, are permitted provided that the following conditions are
00410 // met:
00411 //
00412 //     * Redistributions of source code must retain the above copyright
00413 // notice, this list of conditions and the following disclaimer.
00414 //     * Redistributions in binary form must reproduce the above
00415 // copyright notice, this list of conditions and the following disclaimer
00416 // in the documentation and/or other materials provided with the
00417 // distribution.
00418 //     * Neither the name of Google Inc. nor the names of its
00419 // contributors may be used to endorse or promote products derived from
00420 // this software without specific prior written permission.
00421 //
00422 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
00423 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
00424 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
00425 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
00426 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
00427 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
00428 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
00429 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
00430 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
00431 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
00432 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
00433 
00434 // Utility functions and classes used by the Google C++ testing framework.
00435 //
00436 // Author: wan@google.com (Zhanyong Wan)
00437 //
00438 // This file contains purely Google Test's internal implementation.  Please
00439 // DO NOT #INCLUDE IT IN A USER PROGRAM.
00440 
00441 #ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_
00442 #define GTEST_SRC_GTEST_INTERNAL_INL_H_
00443 
00444 // GTEST_IMPLEMENTATION_ is defined to 1 iff the current translation unit is
00445 // part of Google Test's implementation; otherwise it's undefined.
00446 #if !GTEST_IMPLEMENTATION_
00447 // A user is trying to include this from his code - just say no.
00448 # error "gtest-internal-inl.h is part of Google Test's internal implementation."
00449 # error "It must not be included except by Google Test itself."
00450 #endif  // GTEST_IMPLEMENTATION_
00451 
00452 #ifndef _WIN32_WCE
00453 # include <errno.h>
00454 #endif  // !_WIN32_WCE
00455 #include <stddef.h>
00456 #include <stdlib.h>  // For strtoll/_strtoul64/malloc/free.
00457 #include <string.h>  // For memmove.
00458 
00459 #include <algorithm>
00460 #include <string>
00461 #include <vector>
00462 
00463 
00464 #if GTEST_CAN_STREAM_RESULTS_
00465 # include <arpa/inet.h>  // NOLINT
00466 # include <netdb.h>  // NOLINT
00467 #endif
00468 
00469 #if GTEST_OS_WINDOWS
00470 # include <windows.h>  // NOLINT
00471 #endif  // GTEST_OS_WINDOWS
00472 
00473 
00474 namespace testing {
00475 
00476 // Declares the flags.
00477 //
00478 // We don't want the users to modify this flag in the code, but want
00479 // Google Test's own unit tests to be able to access it. Therefore we
00480 // declare it here as opposed to in gtest.h.
00481 GTEST_DECLARE_bool_(death_test_use_fork);
00482 
00483 namespace internal {
00484 
00485 // The value of GetTestTypeId() as seen from within the Google Test
00486 // library.  This is solely for testing GetTestTypeId().
00487 GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest;
00488 
00489 // Names of the flags (needed for parsing Google Test flags).
00490 const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests";
00491 const char kBreakOnFailureFlag[] = "break_on_failure";
00492 const char kCatchExceptionsFlag[] = "catch_exceptions";
00493 const char kColorFlag[] = "color";
00494 const char kFilterFlag[] = "filter";
00495 const char kListTestsFlag[] = "list_tests";
00496 const char kOutputFlag[] = "output";
00497 const char kPrintTimeFlag[] = "print_time";
00498 const char kRandomSeedFlag[] = "random_seed";
00499 const char kRepeatFlag[] = "repeat";
00500 const char kShuffleFlag[] = "shuffle";
00501 const char kStackTraceDepthFlag[] = "stack_trace_depth";
00502 const char kStreamResultToFlag[] = "stream_result_to";
00503 const char kThrowOnFailureFlag[] = "throw_on_failure";
00504 
00505 // A valid random seed must be in [1, kMaxRandomSeed].
00506 const int kMaxRandomSeed = 99999;
00507 
00508 // g_help_flag is true iff the --help flag or an equivalent form is
00509 // specified on the command line.
00510 GTEST_API_ extern bool g_help_flag;
00511 
00512 // Returns the current time in milliseconds.
00513 GTEST_API_ TimeInMillis GetTimeInMillis();
00514 
00515 // Returns true iff Google Test should use colors in the output.
00516 GTEST_API_ bool ShouldUseColor(bool stdout_is_tty);
00517 
00518 // Formats the given time in milliseconds as seconds.
00519 GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms);
00520 
00521 // Converts the given time in milliseconds to a date string in the ISO 8601
00522 // format, without the timezone information.  N.B.: due to the use the
00523 // non-reentrant localtime() function, this function is not thread safe.  Do
00524 // not use it in any code that can be called from multiple threads.
00525 GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms);
00526 
00527 // Parses a string for an Int32 flag, in the form of "--flag=value".
00528 //
00529 // On success, stores the value of the flag in *value, and returns
00530 // true.  On failure, returns false without changing *value.
00531 GTEST_API_ bool ParseInt32Flag(
00532     const char* str, const char* flag, Int32* value);
00533 
00534 // Returns a random seed in range [1, kMaxRandomSeed] based on the
00535 // given --gtest_random_seed flag value.
00536 inline int GetRandomSeedFromFlag(Int32 random_seed_flag) {
00537   const unsigned int raw_seed = (random_seed_flag == 0) ?
00538       static_cast<unsigned int>(GetTimeInMillis()) :
00539       static_cast<unsigned int>(random_seed_flag);
00540 
00541   // Normalizes the actual seed to range [1, kMaxRandomSeed] such that
00542   // it's easy to type.
00543   const int normalized_seed =
00544       static_cast<int>((raw_seed - 1U) %
00545                        static_cast<unsigned int>(kMaxRandomSeed)) + 1;
00546   return normalized_seed;
00547 }
00548 
00549 // Returns the first valid random seed after 'seed'.  The behavior is
00550 // undefined if 'seed' is invalid.  The seed after kMaxRandomSeed is
00551 // considered to be 1.
00552 inline int GetNextRandomSeed(int seed) {
00553   GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed)
00554       << "Invalid random seed " << seed << " - must be in [1, "
00555       << kMaxRandomSeed << "].";
00556   const int next_seed = seed + 1;
00557   return (next_seed > kMaxRandomSeed) ? 1 : next_seed;
00558 }
00559 
00560 // This class saves the values of all Google Test flags in its c'tor, and
00561 // restores them in its d'tor.
00562 class GTestFlagSaver {
00563  public:
00564   // The c'tor.
00565   GTestFlagSaver() {
00566     also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests);
00567     break_on_failure_ = GTEST_FLAG(break_on_failure);
00568     catch_exceptions_ = GTEST_FLAG(catch_exceptions);
00569     color_ = GTEST_FLAG(color);
00570     death_test_style_ = GTEST_FLAG(death_test_style);
00571     death_test_use_fork_ = GTEST_FLAG(death_test_use_fork);
00572     filter_ = GTEST_FLAG(filter);
00573     internal_run_death_test_ = GTEST_FLAG(internal_run_death_test);
00574     list_tests_ = GTEST_FLAG(list_tests);
00575     output_ = GTEST_FLAG(output);
00576     print_time_ = GTEST_FLAG(print_time);
00577     random_seed_ = GTEST_FLAG(random_seed);
00578     repeat_ = GTEST_FLAG(repeat);
00579     shuffle_ = GTEST_FLAG(shuffle);
00580     stack_trace_depth_ = GTEST_FLAG(stack_trace_depth);
00581     stream_result_to_ = GTEST_FLAG(stream_result_to);
00582     throw_on_failure_ = GTEST_FLAG(throw_on_failure);
00583   }
00584 
00585   // The d'tor is not virtual.  DO NOT INHERIT FROM THIS CLASS.
00586   ~GTestFlagSaver() {
00587     GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_;
00588     GTEST_FLAG(break_on_failure) = break_on_failure_;
00589     GTEST_FLAG(catch_exceptions) = catch_exceptions_;
00590     GTEST_FLAG(color) = color_;
00591     GTEST_FLAG(death_test_style) = death_test_style_;
00592     GTEST_FLAG(death_test_use_fork) = death_test_use_fork_;
00593     GTEST_FLAG(filter) = filter_;
00594     GTEST_FLAG(internal_run_death_test) = internal_run_death_test_;
00595     GTEST_FLAG(list_tests) = list_tests_;
00596     GTEST_FLAG(output) = output_;
00597     GTEST_FLAG(print_time) = print_time_;
00598     GTEST_FLAG(random_seed) = random_seed_;
00599     GTEST_FLAG(repeat) = repeat_;
00600     GTEST_FLAG(shuffle) = shuffle_;
00601     GTEST_FLAG(stack_trace_depth) = stack_trace_depth_;
00602     GTEST_FLAG(stream_result_to) = stream_result_to_;
00603     GTEST_FLAG(throw_on_failure) = throw_on_failure_;
00604   }
00605 
00606  private:
00607   // Fields for saving the original values of flags.
00608   bool also_run_disabled_tests_;
00609   bool break_on_failure_;
00610   bool catch_exceptions_;
00611   std::string color_;
00612   std::string death_test_style_;
00613   bool death_test_use_fork_;
00614   std::string filter_;
00615   std::string internal_run_death_test_;
00616   bool list_tests_;
00617   std::string output_;
00618   bool print_time_;
00619   internal::Int32 random_seed_;
00620   internal::Int32 repeat_;
00621   bool shuffle_;
00622   internal::Int32 stack_trace_depth_;
00623   std::string stream_result_to_;
00624   bool throw_on_failure_;
00625 } GTEST_ATTRIBUTE_UNUSED_;
00626 
00627 // Converts a Unicode code point to a narrow string in UTF-8 encoding.
00628 // code_point parameter is of type UInt32 because wchar_t may not be
00629 // wide enough to contain a code point.
00630 // If the code_point is not a valid Unicode code point
00631 // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
00632 // to "(Invalid Unicode 0xXXXXXXXX)".
00633 GTEST_API_ std::string CodePointToUtf8(UInt32 code_point);
00634 
00635 // Converts a wide string to a narrow string in UTF-8 encoding.
00636 // The wide string is assumed to have the following encoding:
00637 //   UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
00638 //   UTF-32 if sizeof(wchar_t) == 4 (on Linux)
00639 // Parameter str points to a null-terminated wide string.
00640 // Parameter num_chars may additionally limit the number
00641 // of wchar_t characters processed. -1 is used when the entire string
00642 // should be processed.
00643 // If the string contains code points that are not valid Unicode code points
00644 // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
00645 // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
00646 // and contains invalid UTF-16 surrogate pairs, values in those pairs
00647 // will be encoded as individual Unicode characters from Basic Normal Plane.
00648 GTEST_API_ std::string WideStringToUtf8(const wchar_t* str, int num_chars);
00649 
00650 // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
00651 // if the variable is present. If a file already exists at this location, this
00652 // function will write over it. If the variable is present, but the file cannot
00653 // be created, prints an error and exits.
00654 void WriteToShardStatusFileIfNeeded();
00655 
00656 // Checks whether sharding is enabled by examining the relevant
00657 // environment variable values. If the variables are present,
00658 // but inconsistent (e.g., shard_index >= total_shards), prints
00659 // an error and exits. If in_subprocess_for_death_test, sharding is
00660 // disabled because it must only be applied to the original test
00661 // process. Otherwise, we could filter out death tests we intended to execute.
00662 GTEST_API_ bool ShouldShard(const char* total_shards_str,
00663                             const char* shard_index_str,
00664                             bool in_subprocess_for_death_test);
00665 
00666 // Parses the environment variable var as an Int32. If it is unset,
00667 // returns default_val. If it is not an Int32, prints an error and
00668 // and aborts.
00669 GTEST_API_ Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val);
00670 
00671 // Given the total number of shards, the shard index, and the test id,
00672 // returns true iff the test should be run on this shard. The test id is
00673 // some arbitrary but unique non-negative integer assigned to each test
00674 // method. Assumes that 0 <= shard_index < total_shards.
00675 GTEST_API_ bool ShouldRunTestOnShard(
00676     int total_shards, int shard_index, int test_id);
00677 
00678 // STL container utilities.
00679 
00680 // Returns the number of elements in the given container that satisfy
00681 // the given predicate.
00682 template <class Container, typename Predicate>
00683 inline int CountIf(const Container& c, Predicate predicate) {
00684   // Implemented as an explicit loop since std::count_if() in libCstd on
00685   // Solaris has a non-standard signature.
00686   int count = 0;
00687   for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) {
00688     if (predicate(*it))
00689       ++count;
00690   }
00691   return count;
00692 }
00693 
00694 // Applies a function/functor to each element in the container.
00695 template <class Container, typename Functor>
00696 void ForEach(const Container& c, Functor functor) {
00697   std::for_each(c.begin(), c.end(), functor);
00698 }
00699 
00700 // Returns the i-th element of the vector, or default_value if i is not
00701 // in range [0, v.size()).
00702 template <typename E>
00703 inline E GetElementOr(const std::vector<E>& v, int i, E default_value) {
00704   return (i < 0 || i >= static_cast<int>(v.size())) ? default_value : v[i];
00705 }
00706 
00707 // Performs an in-place shuffle of a range of the vector's elements.
00708 // 'begin' and 'end' are element indices as an STL-style range;
00709 // i.e. [begin, end) are shuffled, where 'end' == size() means to
00710 // shuffle to the end of the vector.
00711 template <typename E>
00712 void ShuffleRange(internal::Random* random, int begin, int end,
00713                   std::vector<E>* v) {
00714   const int size = static_cast<int>(v->size());
00715   GTEST_CHECK_(0 <= begin && begin <= size)
00716       << "Invalid shuffle range start " << begin << ": must be in range [0, "
00717       << size << "].";
00718   GTEST_CHECK_(begin <= end && end <= size)
00719       << "Invalid shuffle range finish " << end << ": must be in range ["
00720       << begin << ", " << size << "].";
00721 
00722   // Fisher-Yates shuffle, from
00723   // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
00724   for (int range_width = end - begin; range_width >= 2; range_width--) {
00725     const int last_in_range = begin + range_width - 1;
00726     const int selected = begin + random->Generate(range_width);
00727     std::swap((*v)[selected], (*v)[last_in_range]);
00728   }
00729 }
00730 
00731 // Performs an in-place shuffle of the vector's elements.
00732 template <typename E>
00733 inline void Shuffle(internal::Random* random, std::vector<E>* v) {
00734   ShuffleRange(random, 0, static_cast<int>(v->size()), v);
00735 }
00736 
00737 // A function for deleting an object.  Handy for being used as a
00738 // functor.
00739 template <typename T>
00740 static void Delete(T* x) {
00741   delete x;
00742 }
00743 
00744 // A predicate that checks the key of a TestProperty against a known key.
00745 //
00746 // TestPropertyKeyIs is copyable.
00747 class TestPropertyKeyIs {
00748  public:
00749   // Constructor.
00750   //
00751   // TestPropertyKeyIs has NO default constructor.
00752   explicit TestPropertyKeyIs(const std::string& key) : key_(key) {}
00753 
00754   // Returns true iff the test name of test property matches on key_.
00755   bool operator()(const TestProperty& test_property) const {
00756     return test_property.key() == key_;
00757   }
00758 
00759  private:
00760   std::string key_;
00761 };
00762 
00763 // Class UnitTestOptions.
00764 //
00765 // This class contains functions for processing options the user
00766 // specifies when running the tests.  It has only static members.
00767 //
00768 // In most cases, the user can specify an option using either an
00769 // environment variable or a command line flag.  E.g. you can set the
00770 // test filter using either GTEST_FILTER or --gtest_filter.  If both
00771 // the variable and the flag are present, the latter overrides the
00772 // former.
00773 class GTEST_API_ UnitTestOptions {
00774  public:
00775   // Functions for processing the gtest_output flag.
00776 
00777   // Returns the output format, or "" for normal printed output.
00778   static std::string GetOutputFormat();
00779 
00780   // Returns the absolute path of the requested output file, or the
00781   // default (test_detail.xml in the original working directory) if
00782   // none was explicitly specified.
00783   static std::string GetAbsolutePathToOutputFile();
00784 
00785   // Functions for processing the gtest_filter flag.
00786 
00787   // Returns true iff the wildcard pattern matches the string.  The
00788   // first ':' or '\0' character in pattern marks the end of it.
00789   //
00790   // This recursive algorithm isn't very efficient, but is clear and
00791   // works well enough for matching test names, which are short.
00792   static bool PatternMatchesString(const char *pattern, const char *str);
00793 
00794   // Returns true iff the user-specified filter matches the test case
00795   // name and the test name.
00796   static bool FilterMatchesTest(const std::string &test_case_name,
00797                                 const std::string &test_name);
00798 
00799 #if GTEST_OS_WINDOWS
00800   // Function for supporting the gtest_catch_exception flag.
00801 
00802   // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
00803   // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
00804   // This function is useful as an __except condition.
00805   static int GTestShouldProcessSEH(DWORD exception_code);
00806 #endif  // GTEST_OS_WINDOWS
00807 
00808   // Returns true if "name" matches the ':' separated list of glob-style
00809   // filters in "filter".
00810   static bool MatchesFilter(const std::string& name, const char* filter);
00811 };
00812 
00813 // Returns the current application's name, removing directory path if that
00814 // is present.  Used by UnitTestOptions::GetOutputFile.
00815 GTEST_API_ FilePath GetCurrentExecutableName();
00816 
00817 // The role interface for getting the OS stack trace as a string.
00818 class OsStackTraceGetterInterface {
00819  public:
00820   OsStackTraceGetterInterface() {}
00821   virtual ~OsStackTraceGetterInterface() {}
00822 
00823   // Returns the current OS stack trace as an std::string.  Parameters:
00824   //
00825   //   max_depth  - the maximum number of stack frames to be included
00826   //                in the trace.
00827   //   skip_count - the number of top frames to be skipped; doesn't count
00828   //                against max_depth.
00829   virtual string CurrentStackTrace(int max_depth, int skip_count) = 0;
00830 
00831   // UponLeavingGTest() should be called immediately before Google Test calls
00832   // user code. It saves some information about the current stack that
00833   // CurrentStackTrace() will use to find and hide Google Test stack frames.
00834   virtual void UponLeavingGTest() = 0;
00835 
00836  private:
00837   GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface);
00838 };
00839 
00840 // A working implementation of the OsStackTraceGetterInterface interface.
00841 class OsStackTraceGetter : public OsStackTraceGetterInterface {
00842  public:
00843   OsStackTraceGetter() : caller_frame_(NULL) {}
00844 
00845   virtual string CurrentStackTrace(int max_depth, int skip_count)
00846       GTEST_LOCK_EXCLUDED_(mutex_);
00847 
00848   virtual void UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_);
00849 
00850   // This string is inserted in place of stack frames that are part of
00851   // Google Test's implementation.
00852   static const char* const kElidedFramesMarker;
00853 
00854  private:
00855   Mutex mutex_;  // protects all internal state
00856 
00857   // We save the stack frame below the frame that calls user code.
00858   // We do this because the address of the frame immediately below
00859   // the user code changes between the call to UponLeavingGTest()
00860   // and any calls to CurrentStackTrace() from within the user code.
00861   void* caller_frame_;
00862 
00863   GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter);
00864 };
00865 
00866 // Information about a Google Test trace point.
00867 struct TraceInfo {
00868   const char* file;
00869   int line;
00870   std::string message;
00871 };
00872 
00873 // This is the default global test part result reporter used in UnitTestImpl.
00874 // This class should only be used by UnitTestImpl.
00875 class DefaultGlobalTestPartResultReporter
00876   : public TestPartResultReporterInterface {
00877  public:
00878   explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test);
00879   // Implements the TestPartResultReporterInterface. Reports the test part
00880   // result in the current test.
00881   virtual void ReportTestPartResult(const TestPartResult& result);
00882 
00883  private:
00884   UnitTestImpl* const unit_test_;
00885 
00886   GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter);
00887 };
00888 
00889 // This is the default per thread test part result reporter used in
00890 // UnitTestImpl. This class should only be used by UnitTestImpl.
00891 class DefaultPerThreadTestPartResultReporter
00892     : public TestPartResultReporterInterface {
00893  public:
00894   explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test);
00895   // Implements the TestPartResultReporterInterface. The implementation just
00896   // delegates to the current global test part result reporter of *unit_test_.
00897   virtual void ReportTestPartResult(const TestPartResult& result);
00898 
00899  private:
00900   UnitTestImpl* const unit_test_;
00901 
00902   GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter);
00903 };
00904 
00905 // The private implementation of the UnitTest class.  We don't protect
00906 // the methods under a mutex, as this class is not accessible by a
00907 // user and the UnitTest class that delegates work to this class does
00908 // proper locking.
00909 class GTEST_API_ UnitTestImpl {
00910  public:
00911   explicit UnitTestImpl(UnitTest* parent);
00912   virtual ~UnitTestImpl();
00913 
00914   // There are two different ways to register your own TestPartResultReporter.
00915   // You can register your own repoter to listen either only for test results
00916   // from the current thread or for results from all threads.
00917   // By default, each per-thread test result repoter just passes a new
00918   // TestPartResult to the global test result reporter, which registers the
00919   // test part result for the currently running test.
00920 
00921   // Returns the global test part result reporter.
00922   TestPartResultReporterInterface* GetGlobalTestPartResultReporter();
00923 
00924   // Sets the global test part result reporter.
00925   void SetGlobalTestPartResultReporter(
00926       TestPartResultReporterInterface* reporter);
00927 
00928   // Returns the test part result reporter for the current thread.
00929   TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread();
00930 
00931   // Sets the test part result reporter for the current thread.
00932   void SetTestPartResultReporterForCurrentThread(
00933       TestPartResultReporterInterface* reporter);
00934 
00935   // Gets the number of successful test cases.
00936   int successful_test_case_count() const;
00937 
00938   // Gets the number of failed test cases.
00939   int failed_test_case_count() const;
00940 
00941   // Gets the number of all test cases.
00942   int total_test_case_count() const;
00943 
00944   // Gets the number of all test cases that contain at least one test
00945   // that should run.
00946   int test_case_to_run_count() const;
00947 
00948   // Gets the number of successful tests.
00949   int successful_test_count() const;
00950 
00951   // Gets the number of failed tests.
00952   int failed_test_count() const;
00953 
00954   // Gets the number of disabled tests that will be reported in the XML report.
00955   int reportable_disabled_test_count() const;
00956 
00957   // Gets the number of disabled tests.
00958   int disabled_test_count() const;
00959 
00960   // Gets the number of tests to be printed in the XML report.
00961   int reportable_test_count() const;
00962 
00963   // Gets the number of all tests.
00964   int total_test_count() const;
00965 
00966   // Gets the number of tests that should run.
00967   int test_to_run_count() const;
00968 
00969   // Gets the time of the test program start, in ms from the start of the
00970   // UNIX epoch.
00971   TimeInMillis start_timestamp() const { return start_timestamp_; }
00972 
00973   // Gets the elapsed time, in milliseconds.
00974   TimeInMillis elapsed_time() const { return elapsed_time_; }
00975 
00976   // Returns true iff the unit test passed (i.e. all test cases passed).
00977   bool Passed() const { return !Failed(); }
00978 
00979   // Returns true iff the unit test failed (i.e. some test case failed
00980   // or something outside of all tests failed).
00981   bool Failed() const {
00982     return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed();
00983   }
00984 
00985   // Gets the i-th test case among all the test cases. i can range from 0 to
00986   // total_test_case_count() - 1. If i is not in that range, returns NULL.
00987   const TestCase* GetTestCase(int i) const {
00988     const int index = GetElementOr(test_case_indices_, i, -1);
00989     return index < 0 ? NULL : test_cases_[i];
00990   }
00991 
00992   // Gets the i-th test case among all the test cases. i can range from 0 to
00993   // total_test_case_count() - 1. If i is not in that range, returns NULL.
00994   TestCase* GetMutableTestCase(int i) {
00995     const int index = GetElementOr(test_case_indices_, i, -1);
00996     return index < 0 ? NULL : test_cases_[index];
00997   }
00998 
00999   // Provides access to the event listener list.
01000   TestEventListeners* listeners() { return &listeners_; }
01001 
01002   // Returns the TestResult for the test that's currently running, or
01003   // the TestResult for the ad hoc test if no test is running.
01004   TestResult* current_test_result();
01005 
01006   // Returns the TestResult for the ad hoc test.
01007   const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; }
01008 
01009   // Sets the OS stack trace getter.
01010   //
01011   // Does nothing if the input and the current OS stack trace getter
01012   // are the same; otherwise, deletes the old getter and makes the
01013   // input the current getter.
01014   void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter);
01015 
01016   // Returns the current OS stack trace getter if it is not NULL;
01017   // otherwise, creates an OsStackTraceGetter, makes it the current
01018   // getter, and returns it.
01019   OsStackTraceGetterInterface* os_stack_trace_getter();
01020 
01021   // Returns the current OS stack trace as an std::string.
01022   //
01023   // The maximum number of stack frames to be included is specified by
01024   // the gtest_stack_trace_depth flag.  The skip_count parameter
01025   // specifies the number of top frames to be skipped, which doesn't
01026   // count against the number of frames to be included.
01027   //
01028   // For example, if Foo() calls Bar(), which in turn calls
01029   // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
01030   // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
01031   std::string CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_;
01032 
01033   // Finds and returns a TestCase with the given name.  If one doesn't
01034   // exist, creates one and returns it.
01035   //
01036   // Arguments:
01037   //
01038   //   test_case_name: name of the test case
01039   //   type_param:     the name of the test's type parameter, or NULL if
01040   //                   this is not a typed or a type-parameterized test.
01041   //   set_up_tc:      pointer to the function that sets up the test case
01042   //   tear_down_tc:   pointer to the function that tears down the test case
01043   TestCase* GetTestCase(const char* test_case_name,
01044                         const char* type_param,
01045                         Test::SetUpTestCaseFunc set_up_tc,
01046                         Test::TearDownTestCaseFunc tear_down_tc);
01047 
01048   // Adds a TestInfo to the unit test.
01049   //
01050   // Arguments:
01051   //
01052   //   set_up_tc:    pointer to the function that sets up the test case
01053   //   tear_down_tc: pointer to the function that tears down the test case
01054   //   test_info:    the TestInfo object
01055   void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc,
01056                    Test::TearDownTestCaseFunc tear_down_tc,
01057                    TestInfo* test_info) {
01058     // In order to support thread-safe death tests, we need to
01059     // remember the original working directory when the test program
01060     // was first invoked.  We cannot do this in RUN_ALL_TESTS(), as
01061     // the user may have changed the current directory before calling
01062     // RUN_ALL_TESTS().  Therefore we capture the current directory in
01063     // AddTestInfo(), which is called to register a TEST or TEST_F
01064     // before main() is reached.
01065     if (original_working_dir_.IsEmpty()) {
01066       original_working_dir_.Set(FilePath::GetCurrentDir());
01067       GTEST_CHECK_(!original_working_dir_.IsEmpty())
01068           << "Failed to get the current working directory.";
01069     }
01070 
01071     GetTestCase(test_info->test_case_name(),
01072                 test_info->type_param(),
01073                 set_up_tc,
01074                 tear_down_tc)->AddTestInfo(test_info);
01075   }
01076 
01077 #if GTEST_HAS_PARAM_TEST
01078   // Returns ParameterizedTestCaseRegistry object used to keep track of
01079   // value-parameterized tests and instantiate and register them.
01080   internal::ParameterizedTestCaseRegistry& parameterized_test_registry() {
01081     return parameterized_test_registry_;
01082   }
01083 #endif  // GTEST_HAS_PARAM_TEST
01084 
01085   // Sets the TestCase object for the test that's currently running.
01086   void set_current_test_case(TestCase* a_current_test_case) {
01087     current_test_case_ = a_current_test_case;
01088   }
01089 
01090   // Sets the TestInfo object for the test that's currently running.  If
01091   // current_test_info is NULL, the assertion results will be stored in
01092   // ad_hoc_test_result_.
01093   void set_current_test_info(TestInfo* a_current_test_info) {
01094     current_test_info_ = a_current_test_info;
01095   }
01096 
01097   // Registers all parameterized tests defined using TEST_P and
01098   // INSTANTIATE_TEST_CASE_P, creating regular tests for each test/parameter
01099   // combination. This method can be called more then once; it has guards
01100   // protecting from registering the tests more then once.  If
01101   // value-parameterized tests are disabled, RegisterParameterizedTests is
01102   // present but does nothing.
01103   void RegisterParameterizedTests();
01104 
01105   // Runs all tests in this UnitTest object, prints the result, and
01106   // returns true if all tests are successful.  If any exception is
01107   // thrown during a test, this test is considered to be failed, but
01108   // the rest of the tests will still be run.
01109   bool RunAllTests();
01110 
01111   // Clears the results of all tests, except the ad hoc tests.
01112   void ClearNonAdHocTestResult() {
01113     ForEach(test_cases_, TestCase::ClearTestCaseResult);
01114   }
01115 
01116   // Clears the results of ad-hoc test assertions.
01117   void ClearAdHocTestResult() {
01118     ad_hoc_test_result_.Clear();
01119   }
01120 
01121   // Adds a TestProperty to the current TestResult object when invoked in a
01122   // context of a test or a test case, or to the global property set. If the
01123   // result already contains a property with the same key, the value will be
01124   // updated.
01125   void RecordProperty(const TestProperty& test_property);
01126 
01127   enum ReactionToSharding {
01128     HONOR_SHARDING_PROTOCOL,
01129     IGNORE_SHARDING_PROTOCOL
01130   };
01131 
01132   // Matches the full name of each test against the user-specified
01133   // filter to decide whether the test should run, then records the
01134   // result in each TestCase and TestInfo object.
01135   // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests
01136   // based on sharding variables in the environment.
01137   // Returns the number of tests that should run.
01138   int FilterTests(ReactionToSharding shard_tests);
01139 
01140   // Prints the names of the tests matching the user-specified filter flag.
01141   void ListTestsMatchingFilter();
01142 
01143   const TestCase* current_test_case() const { return current_test_case_; }
01144   TestInfo* current_test_info() { return current_test_info_; }
01145   const TestInfo* current_test_info() const { return current_test_info_; }
01146 
01147   // Returns the vector of environments that need to be set-up/torn-down
01148   // before/after the tests are run.
01149   std::vector<Environment*>& environments() { return environments_; }
01150 
01151   // Getters for the per-thread Google Test trace stack.
01152   std::vector<TraceInfo>& gtest_trace_stack() {
01153     return *(gtest_trace_stack_.pointer());
01154   }
01155   const std::vector<TraceInfo>& gtest_trace_stack() const {
01156     return gtest_trace_stack_.get();
01157   }
01158 
01159 #if GTEST_HAS_DEATH_TEST
01160   void InitDeathTestSubprocessControlInfo() {
01161     internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());
01162   }
01163   // Returns a pointer to the parsed --gtest_internal_run_death_test
01164   // flag, or NULL if that flag was not specified.
01165   // This information is useful only in a death test child process.
01166   // Must not be called before a call to InitGoogleTest.
01167   const InternalRunDeathTestFlag* internal_run_death_test_flag() const {
01168     return internal_run_death_test_flag_.get();
01169   }
01170 
01171   // Returns a pointer to the current death test factory.
01172   internal::DeathTestFactory* death_test_factory() {
01173     return death_test_factory_.get();
01174   }
01175 
01176   void SuppressTestEventsIfInSubprocess();
01177 
01178   friend class ReplaceDeathTestFactory;
01179 #endif  // GTEST_HAS_DEATH_TEST
01180 
01181   // Initializes the event listener performing XML output as specified by
01182   // UnitTestOptions. Must not be called before InitGoogleTest.
01183   void ConfigureXmlOutput();
01184 
01185 #if GTEST_CAN_STREAM_RESULTS_
01186   // Initializes the event listener for streaming test results to a socket.
01187   // Must not be called before InitGoogleTest.
01188   void ConfigureStreamingOutput();
01189 #endif
01190 
01191   // Performs initialization dependent upon flag values obtained in
01192   // ParseGoogleTestFlagsOnly.  Is called from InitGoogleTest after the call to
01193   // ParseGoogleTestFlagsOnly.  In case a user neglects to call InitGoogleTest
01194   // this function is also called from RunAllTests.  Since this function can be
01195   // called more than once, it has to be idempotent.
01196   void PostFlagParsingInit();
01197 
01198   // Gets the random seed used at the start of the current test iteration.
01199   int random_seed() const { return random_seed_; }
01200 
01201   // Gets the random number generator.
01202   internal::Random* random() { return &random_; }
01203 
01204   // Shuffles all test cases, and the tests within each test case,
01205   // making sure that death tests are still run first.
01206   void ShuffleTests();
01207 
01208   // Restores the test cases and tests to their order before the first shuffle.
01209   void UnshuffleTests();
01210 
01211   // Returns the value of GTEST_FLAG(catch_exceptions) at the moment
01212   // UnitTest::Run() starts.
01213   bool catch_exceptions() const { return catch_exceptions_; }
01214 
01215  private:
01216   friend class ::testing::UnitTest;
01217 
01218   // Used by UnitTest::Run() to capture the state of
01219   // GTEST_FLAG(catch_exceptions) at the moment it starts.
01220   void set_catch_exceptions(bool value) { catch_exceptions_ = value; }
01221 
01222   // The UnitTest object that owns this implementation object.
01223   UnitTest* const parent_;
01224 
01225   // The working directory when the first TEST() or TEST_F() was
01226   // executed.
01227   internal::FilePath original_working_dir_;
01228 
01229   // The default test part result reporters.
01230   DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_;
01231   DefaultPerThreadTestPartResultReporter
01232       default_per_thread_test_part_result_reporter_;
01233 
01234   // Points to (but doesn't own) the global test part result reporter.
01235   TestPartResultReporterInterface* global_test_part_result_repoter_;
01236 
01237   // Protects read and write access to global_test_part_result_reporter_.
01238   internal::Mutex global_test_part_result_reporter_mutex_;
01239 
01240   // Points to (but doesn't own) the per-thread test part result reporter.
01241   internal::ThreadLocal<TestPartResultReporterInterface*>
01242       per_thread_test_part_result_reporter_;
01243 
01244   // The vector of environments that need to be set-up/torn-down
01245   // before/after the tests are run.
01246   std::vector<Environment*> environments_;
01247 
01248   // The vector of TestCases in their original order.  It owns the
01249   // elements in the vector.
01250   std::vector<TestCase*> test_cases_;
01251 
01252   // Provides a level of indirection for the test case list to allow
01253   // easy shuffling and restoring the test case order.  The i-th
01254   // element of this vector is the index of the i-th test case in the
01255   // shuffled order.
01256   std::vector<int> test_case_indices_;
01257 
01258 #if GTEST_HAS_PARAM_TEST
01259   // ParameterizedTestRegistry object used to register value-parameterized
01260   // tests.
01261   internal::ParameterizedTestCaseRegistry parameterized_test_registry_;
01262 
01263   // Indicates whether RegisterParameterizedTests() has been called already.
01264   bool parameterized_tests_registered_;
01265 #endif  // GTEST_HAS_PARAM_TEST
01266 
01267   // Index of the last death test case registered.  Initially -1.
01268   int last_death_test_case_;
01269 
01270   // This points to the TestCase for the currently running test.  It
01271   // changes as Google Test goes through one test case after another.
01272   // When no test is running, this is set to NULL and Google Test
01273   // stores assertion results in ad_hoc_test_result_.  Initially NULL.
01274   TestCase* current_test_case_;
01275 
01276   // This points to the TestInfo for the currently running test.  It
01277   // changes as Google Test goes through one test after another.  When
01278   // no test is running, this is set to NULL and Google Test stores
01279   // assertion results in ad_hoc_test_result_.  Initially NULL.
01280   TestInfo* current_test_info_;
01281 
01282   // Normally, a user only writes assertions inside a TEST or TEST_F,
01283   // or inside a function called by a TEST or TEST_F.  Since Google
01284   // Test keeps track of which test is current running, it can
01285   // associate such an assertion with the test it belongs to.
01286   //
01287   // If an assertion is encountered when no TEST or TEST_F is running,
01288   // Google Test attributes the assertion result to an imaginary "ad hoc"
01289   // test, and records the result in ad_hoc_test_result_.
01290   TestResult ad_hoc_test_result_;
01291 
01292   // The list of event listeners that can be used to track events inside
01293   // Google Test.
01294   TestEventListeners listeners_;
01295 
01296   // The OS stack trace getter.  Will be deleted when the UnitTest
01297   // object is destructed.  By default, an OsStackTraceGetter is used,
01298   // but the user can set this field to use a custom getter if that is
01299   // desired.
01300   OsStackTraceGetterInterface* os_stack_trace_getter_;
01301 
01302   // True iff PostFlagParsingInit() has been called.
01303   bool post_flag_parse_init_performed_;
01304 
01305   // The random number seed used at the beginning of the test run.
01306   int random_seed_;
01307 
01308   // Our random number generator.
01309   internal::Random random_;
01310 
01311   // The time of the test program start, in ms from the start of the
01312   // UNIX epoch.
01313   TimeInMillis start_timestamp_;
01314 
01315   // How long the test took to run, in milliseconds.
01316   TimeInMillis elapsed_time_;
01317 
01318 #if GTEST_HAS_DEATH_TEST
01319   // The decomposed components of the gtest_internal_run_death_test flag,
01320   // parsed when RUN_ALL_TESTS is called.
01321   internal::scoped_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;
01322   internal::scoped_ptr<internal::DeathTestFactory> death_test_factory_;
01323 #endif  // GTEST_HAS_DEATH_TEST
01324 
01325   // A per-thread stack of traces created by the SCOPED_TRACE() macro.
01326   internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_;
01327 
01328   // The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests()
01329   // starts.
01330   bool catch_exceptions_;
01331 
01332   GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl);
01333 };  // class UnitTestImpl
01334 
01335 // Convenience function for accessing the global UnitTest
01336 // implementation object.
01337 inline UnitTestImpl* GetUnitTestImpl() {
01338   return UnitTest::GetInstance()->impl();
01339 }
01340 
01341 #if GTEST_USES_SIMPLE_RE
01342 
01343 // Internal helper functions for implementing the simple regular
01344 // expression matcher.
01345 GTEST_API_ bool IsInSet(char ch, const char* str);
01346 GTEST_API_ bool IsAsciiDigit(char ch);
01347 GTEST_API_ bool IsAsciiPunct(char ch);
01348 GTEST_API_ bool IsRepeat(char ch);
01349 GTEST_API_ bool IsAsciiWhiteSpace(char ch);
01350 GTEST_API_ bool IsAsciiWordChar(char ch);
01351 GTEST_API_ bool IsValidEscape(char ch);
01352 GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch);
01353 GTEST_API_ bool ValidateRegex(const char* regex);
01354 GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str);
01355 GTEST_API_ bool MatchRepetitionAndRegexAtHead(
01356     bool escaped, char ch, char repeat, const char* regex, const char* str);
01357 GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str);
01358 
01359 #endif  // GTEST_USES_SIMPLE_RE
01360 
01361 // Parses the command line for Google Test flags, without initializing
01362 // other parts of Google Test.
01363 GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv);
01364 GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv);
01365 
01366 #if GTEST_HAS_DEATH_TEST
01367 
01368 // Returns the message describing the last system error, regardless of the
01369 // platform.
01370 GTEST_API_ std::string GetLastErrnoDescription();
01371 
01372 # if GTEST_OS_WINDOWS
01373 // Provides leak-safe Windows kernel handle ownership.
01374 class AutoHandle {
01375  public:
01376   AutoHandle() : handle_(INVALID_HANDLE_VALUE) {}
01377   explicit AutoHandle(HANDLE handle) : handle_(handle) {}
01378 
01379   ~AutoHandle() { Reset(); }
01380 
01381   HANDLE Get() const { return handle_; }
01382   void Reset() { Reset(INVALID_HANDLE_VALUE); }
01383   void Reset(HANDLE handle) {
01384     if (handle != handle_) {
01385       if (handle_ != INVALID_HANDLE_VALUE)
01386         ::CloseHandle(handle_);
01387       handle_ = handle;
01388     }
01389   }
01390 
01391  private:
01392   HANDLE handle_;
01393 
01394   GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle);
01395 };
01396 # endif  // GTEST_OS_WINDOWS
01397 
01398 // Attempts to parse a string into a positive integer pointed to by the
01399 // number parameter.  Returns true if that is possible.
01400 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use
01401 // it here.
01402 template <typename Integer>
01403 bool ParseNaturalNumber(const ::std::string& str, Integer* number) {
01404   // Fail fast if the given string does not begin with a digit;
01405   // this bypasses strtoXXX's "optional leading whitespace and plus
01406   // or minus sign" semantics, which are undesirable here.
01407   if (str.empty() || !IsDigit(str[0])) {
01408     return false;
01409   }
01410   errno = 0;
01411 
01412   char* end;
01413   // BiggestConvertible is the largest integer type that system-provided
01414   // string-to-number conversion routines can return.
01415 
01416 # if GTEST_OS_WINDOWS && !defined(__GNUC__)
01417 
01418   // MSVC and C++ Builder define __int64 instead of the standard long long.
01419   typedef unsigned __int64 BiggestConvertible;
01420   const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10);
01421 
01422 # else
01423 
01424   typedef unsigned long long BiggestConvertible;  // NOLINT
01425   const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10);
01426 
01427 # endif  // GTEST_OS_WINDOWS && !defined(__GNUC__)
01428 
01429   const bool parse_success = *end == '\0' && errno == 0;
01430 
01431   // TODO(vladl@google.com): Convert this to compile time assertion when it is
01432   // available.
01433   GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed));
01434 
01435   const Integer result = static_cast<Integer>(parsed);
01436   if (parse_success && static_cast<BiggestConvertible>(result) == parsed) {
01437     *number = result;
01438     return true;
01439   }
01440   return false;
01441 }
01442 #endif  // GTEST_HAS_DEATH_TEST
01443 
01444 // TestResult contains some private methods that should be hidden from
01445 // Google Test user but are required for testing. This class allow our tests
01446 // to access them.
01447 //
01448 // This class is supplied only for the purpose of testing Google Test's own
01449 // constructs. Do not use it in user tests, either directly or indirectly.
01450 class TestResultAccessor {
01451  public:
01452   static void RecordProperty(TestResult* test_result,
01453                              const std::string& xml_element,
01454                              const TestProperty& property) {
01455     test_result->RecordProperty(xml_element, property);
01456   }
01457 
01458   static void ClearTestPartResults(TestResult* test_result) {
01459     test_result->ClearTestPartResults();
01460   }
01461 
01462   static const std::vector<testing::TestPartResult>& test_part_results(
01463       const TestResult& test_result) {
01464     return test_result.test_part_results();
01465   }
01466 };
01467 
01468 #if GTEST_CAN_STREAM_RESULTS_
01469 
01470 // Streams test results to the given port on the given host machine.
01471 class StreamingListener : public EmptyTestEventListener {
01472  public:
01473   // Abstract base class for writing strings to a socket.
01474   class AbstractSocketWriter {
01475    public:
01476     virtual ~AbstractSocketWriter() {}
01477 
01478     // Sends a string to the socket.
01479     virtual void Send(const string& message) = 0;
01480 
01481     // Closes the socket.
01482     virtual void CloseConnection() {}
01483 
01484     // Sends a string and a newline to the socket.
01485     void SendLn(const string& message) {
01486       Send(message + "\n");
01487     }
01488   };
01489 
01490   // Concrete class for actually writing strings to a socket.
01491   class SocketWriter : public AbstractSocketWriter {
01492    public:
01493     SocketWriter(const string& host, const string& port)
01494         : sockfd_(-1), host_name_(host), port_num_(port) {
01495       MakeConnection();
01496     }
01497 
01498     virtual ~SocketWriter() {
01499       if (sockfd_ != -1)
01500         CloseConnection();
01501     }
01502 
01503     // Sends a string to the socket.
01504     virtual void Send(const string& message) {
01505       GTEST_CHECK_(sockfd_ != -1)
01506           << "Send() can be called only when there is a connection.";
01507 
01508       const int len = static_cast<int>(message.length());
01509       if (write(sockfd_, message.c_str(), len) != len) {
01510         GTEST_LOG_(WARNING)
01511             << "stream_result_to: failed to stream to "
01512             << host_name_ << ":" << port_num_;
01513       }
01514     }
01515 
01516    private:
01517     // Creates a client socket and connects to the server.
01518     void MakeConnection();
01519 
01520     // Closes the socket.
01521     void CloseConnection() {
01522       GTEST_CHECK_(sockfd_ != -1)
01523           << "CloseConnection() can be called only when there is a connection.";
01524 
01525       close(sockfd_);
01526       sockfd_ = -1;
01527     }
01528 
01529     int sockfd_;  // socket file descriptor
01530     const string host_name_;
01531     const string port_num_;
01532 
01533     GTEST_DISALLOW_COPY_AND_ASSIGN_(SocketWriter);
01534   };  // class SocketWriter
01535 
01536   // Escapes '=', '&', '%', and '\n' characters in str as "%xx".
01537   static string UrlEncode(const char* str);
01538 
01539   StreamingListener(const string& host, const string& port)
01540       : socket_writer_(new SocketWriter(host, port)) { Start(); }
01541 
01542   explicit StreamingListener(AbstractSocketWriter* socket_writer)
01543       : socket_writer_(socket_writer) { Start(); }
01544 
01545   void OnTestProgramStart(const UnitTest& /* unit_test */) {
01546     SendLn("event=TestProgramStart");
01547   }
01548 
01549   void OnTestProgramEnd(const UnitTest& unit_test) {
01550     // Note that Google Test current only report elapsed time for each
01551     // test iteration, not for the entire test program.
01552     SendLn("event=TestProgramEnd&passed=" + FormatBool(unit_test.Passed()));
01553 
01554     // Notify the streaming server to stop.
01555     socket_writer_->CloseConnection();
01556   }
01557 
01558   void OnTestIterationStart(const UnitTest& /* unit_test */, int iteration) {
01559     SendLn("event=TestIterationStart&iteration=" +
01560            StreamableToString(iteration));
01561   }
01562 
01563   void OnTestIterationEnd(const UnitTest& unit_test, int /* iteration */) {
01564     SendLn("event=TestIterationEnd&passed=" +
01565            FormatBool(unit_test.Passed()) + "&elapsed_time=" +
01566            StreamableToString(unit_test.elapsed_time()) + "ms");
01567   }
01568 
01569   void OnTestCaseStart(const TestCase& test_case) {
01570     SendLn(std::string("event=TestCaseStart&name=") + test_case.name());
01571   }
01572 
01573   void OnTestCaseEnd(const TestCase& test_case) {
01574     SendLn("event=TestCaseEnd&passed=" + FormatBool(test_case.Passed())
01575            + "&elapsed_time=" + StreamableToString(test_case.elapsed_time())
01576            + "ms");
01577   }
01578 
01579   void OnTestStart(const TestInfo& test_info) {
01580     SendLn(std::string("event=TestStart&name=") + test_info.name());
01581   }
01582 
01583   void OnTestEnd(const TestInfo& test_info) {
01584     SendLn("event=TestEnd&passed=" +
01585            FormatBool((test_info.result())->Passed()) +
01586            "&elapsed_time=" +
01587            StreamableToString((test_info.result())->elapsed_time()) + "ms");
01588   }
01589 
01590   void OnTestPartResult(const TestPartResult& test_part_result) {
01591     const char* file_name = test_part_result.file_name();
01592     if (file_name == NULL)
01593       file_name = "";
01594     SendLn("event=TestPartResult&file=" + UrlEncode(file_name) +
01595            "&line=" + StreamableToString(test_part_result.line_number()) +
01596            "&message=" + UrlEncode(test_part_result.message()));
01597   }
01598 
01599  private:
01600   // Sends the given message and a newline to the socket.
01601   void SendLn(const string& message) { socket_writer_->SendLn(message); }
01602 
01603   // Called at the start of streaming to notify the receiver what
01604   // protocol we are using.
01605   void Start() { SendLn("gtest_streaming_protocol_version=1.0"); }
01606 
01607   string FormatBool(bool value) { return value ? "1" : "0"; }
01608 
01609   const scoped_ptr<AbstractSocketWriter> socket_writer_;
01610 
01611   GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener);
01612 };  // class StreamingListener
01613 
01614 #endif  // GTEST_CAN_STREAM_RESULTS_
01615 
01616 }  // namespace internal
01617 }  // namespace testing
01618 
01619 #endif  // GTEST_SRC_GTEST_INTERNAL_INL_H_
01620 #undef GTEST_IMPLEMENTATION_
01621 
01622 #if GTEST_OS_WINDOWS
01623 # define vsnprintf _vsnprintf
01624 #endif  // GTEST_OS_WINDOWS
01625 
01626 namespace testing {
01627 
01628 using internal::CountIf;
01629 using internal::ForEach;
01630 using internal::GetElementOr;
01631 using internal::Shuffle;
01632 
01633 // Constants.
01634 
01635 // A test whose test case name or test name matches this filter is
01636 // disabled and not run.
01637 static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
01638 
01639 // A test case whose name matches this filter is considered a death
01640 // test case and will be run before test cases whose name doesn't
01641 // match this filter.
01642 static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*";
01643 
01644 // A test filter that matches everything.
01645 static const char kUniversalFilter[] = "*";
01646 
01647 // The default output file for XML output.
01648 static const char kDefaultOutputFile[] = "test_detail.xml";
01649 
01650 // The environment variable name for the test shard index.
01651 static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
01652 // The environment variable name for the total number of test shards.
01653 static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
01654 // The environment variable name for the test shard status file.
01655 static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
01656 
01657 namespace internal {
01658 
01659 // The text used in failure messages to indicate the start of the
01660 // stack trace.
01661 const char kStackTraceMarker[] = "\nStack trace:\n";
01662 
01663 // g_help_flag is true iff the --help flag or an equivalent form is
01664 // specified on the command line.
01665 bool g_help_flag = false;
01666 
01667 }  // namespace internal
01668 
01669 static const char* GetDefaultFilter() {
01670   return kUniversalFilter;
01671 }
01672 
01673 GTEST_DEFINE_bool_(
01674     also_run_disabled_tests,
01675     internal::BoolFromGTestEnv("also_run_disabled_tests", false),
01676     "Run disabled tests too, in addition to the tests normally being run.");
01677 
01678 GTEST_DEFINE_bool_(
01679     break_on_failure,
01680     internal::BoolFromGTestEnv("break_on_failure", false),
01681     "True iff a failed assertion should be a debugger break-point.");
01682 
01683 GTEST_DEFINE_bool_(
01684     catch_exceptions,
01685     internal::BoolFromGTestEnv("catch_exceptions", true),
01686     "True iff " GTEST_NAME_
01687     " should catch exceptions and treat them as test failures.");
01688 
01689 GTEST_DEFINE_string_(
01690     color,
01691     internal::StringFromGTestEnv("color", "auto"),
01692     "Whether to use colors in the output.  Valid values: yes, no, "
01693     "and auto.  'auto' means to use colors if the output is "
01694     "being sent to a terminal and the TERM environment variable "
01695     "is set to a terminal type that supports colors.");
01696 
01697 GTEST_DEFINE_string_(
01698     filter,
01699     internal::StringFromGTestEnv("filter", GetDefaultFilter()),
01700     "A colon-separated list of glob (not regex) patterns "
01701     "for filtering the tests to run, optionally followed by a "
01702     "'-' and a : separated list of negative patterns (tests to "
01703     "exclude).  A test is run if it matches one of the positive "
01704     "patterns and does not match any of the negative patterns.");
01705 
01706 GTEST_DEFINE_bool_(list_tests, false,
01707                    "List all tests without running them.");
01708 
01709 GTEST_DEFINE_string_(
01710     output,
01711     internal::StringFromGTestEnv("output", ""),
01712     "A format (currently must be \"xml\"), optionally followed "
01713     "by a colon and an output file name or directory. A directory "
01714     "is indicated by a trailing pathname separator. "
01715     "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
01716     "If a directory is specified, output files will be created "
01717     "within that directory, with file-names based on the test "
01718     "executable's name and, if necessary, made unique by adding "
01719     "digits.");
01720 
01721 GTEST_DEFINE_bool_(
01722     print_time,
01723     internal::BoolFromGTestEnv("print_time", true),
01724     "True iff " GTEST_NAME_
01725     " should display elapsed time in text output.");
01726 
01727 GTEST_DEFINE_int32_(
01728     random_seed,
01729     internal::Int32FromGTestEnv("random_seed", 0),
01730     "Random number seed to use when shuffling test orders.  Must be in range "
01731     "[1, 99999], or 0 to use a seed based on the current time.");
01732 
01733 GTEST_DEFINE_int32_(
01734     repeat,
01735     internal::Int32FromGTestEnv("repeat", 1),
01736     "How many times to repeat each test.  Specify a negative number "
01737     "for repeating forever.  Useful for shaking out flaky tests.");
01738 
01739 GTEST_DEFINE_bool_(
01740     show_internal_stack_frames, false,
01741     "True iff " GTEST_NAME_ " should include internal stack frames when "
01742     "printing test failure stack traces.");
01743 
01744 GTEST_DEFINE_bool_(
01745     shuffle,
01746     internal::BoolFromGTestEnv("shuffle", false),
01747     "True iff " GTEST_NAME_
01748     " should randomize tests' order on every run.");
01749 
01750 GTEST_DEFINE_int32_(
01751     stack_trace_depth,
01752     internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
01753     "The maximum number of stack frames to print when an "
01754     "assertion fails.  The valid range is 0 through 100, inclusive.");
01755 
01756 GTEST_DEFINE_string_(
01757     stream_result_to,
01758     internal::StringFromGTestEnv("stream_result_to", ""),
01759     "This flag specifies the host name and the port number on which to stream "
01760     "test results. Example: \"localhost:555\". The flag is effective only on "
01761     "Linux.");
01762 
01763 GTEST_DEFINE_bool_(
01764     throw_on_failure,
01765     internal::BoolFromGTestEnv("throw_on_failure", false),
01766     "When this flag is specified, a failed assertion will throw an exception "
01767     "if exceptions are enabled or exit the program with a non-zero code "
01768     "otherwise.");
01769 
01770 namespace internal {
01771 
01772 // Generates a random number from [0, range), using a Linear
01773 // Congruential Generator (LCG).  Crashes if 'range' is 0 or greater
01774 // than kMaxRange.
01775 UInt32 Random::Generate(UInt32 range) {
01776   // These constants are the same as are used in glibc's rand(3).
01777   state_ = (1103515245U*state_ + 12345U) % kMaxRange;
01778 
01779   GTEST_CHECK_(range > 0)
01780       << "Cannot generate a number in the range [0, 0).";
01781   GTEST_CHECK_(range <= kMaxRange)
01782       << "Generation of a number in [0, " << range << ") was requested, "
01783       << "but this can only generate numbers in [0, " << kMaxRange << ").";
01784 
01785   // Converting via modulus introduces a bit of downward bias, but
01786   // it's simple, and a linear congruential generator isn't too good
01787   // to begin with.
01788   return state_ % range;
01789 }
01790 
01791 // GTestIsInitialized() returns true iff the user has initialized
01792 // Google Test.  Useful for catching the user mistake of not initializing
01793 // Google Test before calling RUN_ALL_TESTS().
01794 //
01795 // A user must call testing::InitGoogleTest() to initialize Google
01796 // Test.  g_init_gtest_count is set to the number of times
01797 // InitGoogleTest() has been called.  We don't protect this variable
01798 // under a mutex as it is only accessed in the main thread.
01799 GTEST_API_ int g_init_gtest_count = 0;
01800 static bool GTestIsInitialized() { return g_init_gtest_count != 0; }
01801 
01802 // Iterates over a vector of TestCases, keeping a running sum of the
01803 // results of calling a given int-returning method on each.
01804 // Returns the sum.
01805 static int SumOverTestCaseList(const std::vector<TestCase*>& case_list,
01806                                int (TestCase::*method)() const) {
01807   int sum = 0;
01808   for (size_t i = 0; i < case_list.size(); i++) {
01809     sum += (case_list[i]->*method)();
01810   }
01811   return sum;
01812 }
01813 
01814 // Returns true iff the test case passed.
01815 static bool TestCasePassed(const TestCase* test_case) {
01816   return test_case->should_run() && test_case->Passed();
01817 }
01818 
01819 // Returns true iff the test case failed.
01820 static bool TestCaseFailed(const TestCase* test_case) {
01821   return test_case->should_run() && test_case->Failed();
01822 }
01823 
01824 // Returns true iff test_case contains at least one test that should
01825 // run.
01826 static bool ShouldRunTestCase(const TestCase* test_case) {
01827   return test_case->should_run();
01828 }
01829 
01830 // AssertHelper constructor.
01831 AssertHelper::AssertHelper(TestPartResult::Type type,
01832                            const char* file,
01833                            int line,
01834                            const char* message)
01835     : data_(new AssertHelperData(type, file, line, message)) {
01836 }
01837 
01838 AssertHelper::~AssertHelper() {
01839   delete data_;
01840 }
01841 
01842 // Message assignment, for assertion streaming support.
01843 void AssertHelper::operator=(const Message& message) const {
01844   UnitTest::GetInstance()->
01845     AddTestPartResult(data_->type, data_->file, data_->line,
01846                       AppendUserMessage(data_->message, message),
01847                       UnitTest::GetInstance()->impl()
01848                       ->CurrentOsStackTraceExceptTop(1)
01849                       // Skips the stack frame for this function itself.
01850                       );  // NOLINT
01851 }
01852 
01853 // Mutex for linked pointers.
01854 GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex);
01855 
01856 // Application pathname gotten in InitGoogleTest.
01857 std::string g_executable_path;
01858 
01859 // Returns the current application's name, removing directory path if that
01860 // is present.
01861 FilePath GetCurrentExecutableName() {
01862   FilePath result;
01863 
01864 #if GTEST_OS_WINDOWS
01865   result.Set(FilePath(g_executable_path).RemoveExtension("exe"));
01866 #else
01867   result.Set(FilePath(g_executable_path));
01868 #endif  // GTEST_OS_WINDOWS
01869 
01870   return result.RemoveDirectoryName();
01871 }
01872 
01873 // Functions for processing the gtest_output flag.
01874 
01875 // Returns the output format, or "" for normal printed output.
01876 std::string UnitTestOptions::GetOutputFormat() {
01877   const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
01878   if (gtest_output_flag == NULL) return std::string("");
01879 
01880   const char* const colon = strchr(gtest_output_flag, ':');
01881   return (colon == NULL) ?
01882       std::string(gtest_output_flag) :
01883       std::string(gtest_output_flag, colon - gtest_output_flag);
01884 }
01885 
01886 // Returns the name of the requested output file, or the default if none
01887 // was explicitly specified.
01888 std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
01889   const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
01890   if (gtest_output_flag == NULL)
01891     return "";
01892 
01893   const char* const colon = strchr(gtest_output_flag, ':');
01894   if (colon == NULL)
01895     return internal::FilePath::ConcatPaths(
01896         internal::FilePath(
01897             UnitTest::GetInstance()->original_working_dir()),
01898         internal::FilePath(kDefaultOutputFile)).string();
01899 
01900   internal::FilePath output_name(colon + 1);
01901   if (!output_name.IsAbsolutePath())
01902     // TODO(wan@google.com): on Windows \some\path is not an absolute
01903     // path (as its meaning depends on the current drive), yet the
01904     // following logic for turning it into an absolute path is wrong.
01905     // Fix it.
01906     output_name = internal::FilePath::ConcatPaths(
01907         internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
01908         internal::FilePath(colon + 1));
01909 
01910   if (!output_name.IsDirectory())
01911     return output_name.string();
01912 
01913   internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
01914       output_name, internal::GetCurrentExecutableName(),
01915       GetOutputFormat().c_str()));
01916   return result.string();
01917 }
01918 
01919 // Returns true iff the wildcard pattern matches the string.  The
01920 // first ':' or '\0' character in pattern marks the end of it.
01921 //
01922 // This recursive algorithm isn't very efficient, but is clear and
01923 // works well enough for matching test names, which are short.
01924 bool UnitTestOptions::PatternMatchesString(const char *pattern,
01925                                            const char *str) {
01926   switch (*pattern) {
01927     case '\0':
01928     case ':':  // Either ':' or '\0' marks the end of the pattern.
01929       return *str == '\0';
01930     case '?':  // Matches any single character.
01931       return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);
01932     case '*':  // Matches any string (possibly empty) of characters.
01933       return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||
01934           PatternMatchesString(pattern + 1, str);
01935     default:  // Non-special character.  Matches itself.
01936       return *pattern == *str &&
01937           PatternMatchesString(pattern + 1, str + 1);
01938   }
01939 }
01940 
01941 bool UnitTestOptions::MatchesFilter(
01942     const std::string& name, const char* filter) {
01943   const char *cur_pattern = filter;
01944   for (;;) {
01945     if (PatternMatchesString(cur_pattern, name.c_str())) {
01946       return true;
01947     }
01948 
01949     // Finds the next pattern in the filter.
01950     cur_pattern = strchr(cur_pattern, ':');
01951 
01952     // Returns if no more pattern can be found.
01953     if (cur_pattern == NULL) {
01954       return false;
01955     }
01956 
01957     // Skips the pattern separater (the ':' character).
01958     cur_pattern++;
01959   }
01960 }
01961 
01962 // Returns true iff the user-specified filter matches the test case
01963 // name and the test name.
01964 bool UnitTestOptions::FilterMatchesTest(const std::string &test_case_name,
01965                                         const std::string &test_name) {
01966   const std::string& full_name = test_case_name + "." + test_name.c_str();
01967 
01968   // Split --gtest_filter at '-', if there is one, to separate into
01969   // positive filter and negative filter portions
01970   const char* const p = GTEST_FLAG(filter).c_str();
01971   const char* const dash = strchr(p, '-');
01972   std::string positive;
01973   std::string negative;
01974   if (dash == NULL) {
01975     positive = GTEST_FLAG(filter).c_str();  // Whole string is a positive filter
01976     negative = "";
01977   } else {
01978     positive = std::string(p, dash);   // Everything up to the dash
01979     negative = std::string(dash + 1);  // Everything after the dash
01980     if (positive.empty()) {
01981       // Treat '-test1' as the same as '*-test1'
01982       positive = kUniversalFilter;
01983     }
01984   }
01985 
01986   // A filter is a colon-separated list of patterns.  It matches a
01987   // test if any pattern in it matches the test.
01988   return (MatchesFilter(full_name, positive.c_str()) &&
01989           !MatchesFilter(full_name, negative.c_str()));
01990 }
01991 
01992 #if GTEST_HAS_SEH
01993 // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
01994 // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
01995 // This function is useful as an __except condition.
01996 int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
01997   // Google Test should handle a SEH exception if:
01998   //   1. the user wants it to, AND
01999   //   2. this is not a breakpoint exception, AND
02000   //   3. this is not a C++ exception (VC++ implements them via SEH,
02001   //      apparently).
02002   //
02003   // SEH exception code for C++ exceptions.
02004   // (see http://support.microsoft.com/kb/185294 for more information).
02005   const DWORD kCxxExceptionCode = 0xe06d7363;
02006 
02007   bool should_handle = true;
02008 
02009   if (!GTEST_FLAG(catch_exceptions))
02010     should_handle = false;
02011   else if (exception_code == EXCEPTION_BREAKPOINT)
02012     should_handle = false;
02013   else if (exception_code == kCxxExceptionCode)
02014     should_handle = false;
02015 
02016   return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
02017 }
02018 #endif  // GTEST_HAS_SEH
02019 
02020 }  // namespace internal
02021 
02022 // The c'tor sets this object as the test part result reporter used by
02023 // Google Test.  The 'result' parameter specifies where to report the
02024 // results. Intercepts only failures from the current thread.
02025 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
02026     TestPartResultArray* result)
02027     : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
02028       result_(result) {
02029   Init();
02030 }
02031 
02032 // The c'tor sets this object as the test part result reporter used by
02033 // Google Test.  The 'result' parameter specifies where to report the
02034 // results.
02035 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
02036     InterceptMode intercept_mode, TestPartResultArray* result)
02037     : intercept_mode_(intercept_mode),
02038       result_(result) {
02039   Init();
02040 }
02041 
02042 void ScopedFakeTestPartResultReporter::Init() {
02043   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
02044   if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
02045     old_reporter_ = impl->GetGlobalTestPartResultReporter();
02046     impl->SetGlobalTestPartResultReporter(this);
02047   } else {
02048     old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
02049     impl->SetTestPartResultReporterForCurrentThread(this);
02050   }
02051 }
02052 
02053 // The d'tor restores the test part result reporter used by Google Test
02054 // before.
02055 ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
02056   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
02057   if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
02058     impl->SetGlobalTestPartResultReporter(old_reporter_);
02059   } else {
02060     impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
02061   }
02062 }
02063 
02064 // Increments the test part result count and remembers the result.
02065 // This method is from the TestPartResultReporterInterface interface.
02066 void ScopedFakeTestPartResultReporter::ReportTestPartResult(
02067     const TestPartResult& result) {
02068   result_->Append(result);
02069 }
02070 
02071 namespace internal {
02072 
02073 // Returns the type ID of ::testing::Test.  We should always call this
02074 // instead of GetTypeId< ::testing::Test>() to get the type ID of
02075 // testing::Test.  This is to work around a suspected linker bug when
02076 // using Google Test as a framework on Mac OS X.  The bug causes
02077 // GetTypeId< ::testing::Test>() to return different values depending
02078 // on whether the call is from the Google Test framework itself or
02079 // from user test code.  GetTestTypeId() is guaranteed to always
02080 // return the same value, as it always calls GetTypeId<>() from the
02081 // gtest.cc, which is within the Google Test framework.
02082 TypeId GetTestTypeId() {
02083   return GetTypeId<Test>();
02084 }
02085 
02086 // The value of GetTestTypeId() as seen from within the Google Test
02087 // library.  This is solely for testing GetTestTypeId().
02088 extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
02089 
02090 // This predicate-formatter checks that 'results' contains a test part
02091 // failure of the given type and that the failure message contains the
02092 // given substring.
02093 AssertionResult HasOneFailure(const char* /* results_expr */,
02094                               const char* /* type_expr */,
02095                               const char* /* substr_expr */,
02096                               const TestPartResultArray& results,
02097                               TestPartResult::Type type,
02098                               const string& substr) {
02099   const std::string expected(type == TestPartResult::kFatalFailure ?
02100                         "1 fatal failure" :
02101                         "1 non-fatal failure");
02102   Message msg;
02103   if (results.size() != 1) {
02104     msg << "Expected: " << expected << "\n"
02105         << "  Actual: " << results.size() << " failures";
02106     for (int i = 0; i < results.size(); i++) {
02107       msg << "\n" << results.GetTestPartResult(i);
02108     }
02109     return AssertionFailure() << msg;
02110   }
02111 
02112   const TestPartResult& r = results.GetTestPartResult(0);
02113   if (r.type() != type) {
02114     return AssertionFailure() << "Expected: " << expected << "\n"
02115                               << "  Actual:\n"
02116                               << r;
02117   }
02118 
02119   if (strstr(r.message(), substr.c_str()) == NULL) {
02120     return AssertionFailure() << "Expected: " << expected << " containing \""
02121                               << substr << "\"\n"
02122                               << "  Actual:\n"
02123                               << r;
02124   }
02125 
02126   return AssertionSuccess();
02127 }
02128 
02129 // The constructor of SingleFailureChecker remembers where to look up
02130 // test part results, what type of failure we expect, and what
02131 // substring the failure message should contain.
02132 SingleFailureChecker:: SingleFailureChecker(
02133     const TestPartResultArray* results,
02134     TestPartResult::Type type,
02135     const string& substr)
02136     : results_(results),
02137       type_(type),
02138       substr_(substr) {}
02139 
02140 // The destructor of SingleFailureChecker verifies that the given
02141 // TestPartResultArray contains exactly one failure that has the given
02142 // type and contains the given substring.  If that's not the case, a
02143 // non-fatal failure will be generated.
02144 SingleFailureChecker::~SingleFailureChecker() {
02145   EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_);
02146 }
02147 
02148 DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
02149     UnitTestImpl* unit_test) : unit_test_(unit_test) {}
02150 
02151 void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
02152     const TestPartResult& result) {
02153   unit_test_->current_test_result()->AddTestPartResult(result);
02154   unit_test_->listeners()->repeater()->OnTestPartResult(result);
02155 }
02156 
02157 DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
02158     UnitTestImpl* unit_test) : unit_test_(unit_test) {}
02159 
02160 void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
02161     const TestPartResult& result) {
02162   unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
02163 }
02164 
02165 // Returns the global test part result reporter.
02166 TestPartResultReporterInterface*
02167 UnitTestImpl::GetGlobalTestPartResultReporter() {
02168   internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
02169   return global_test_part_result_repoter_;
02170 }
02171 
02172 // Sets the global test part result reporter.
02173 void UnitTestImpl::SetGlobalTestPartResultReporter(
02174     TestPartResultReporterInterface* reporter) {
02175   internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
02176   global_test_part_result_repoter_ = reporter;
02177 }
02178 
02179 // Returns the test part result reporter for the current thread.
02180 TestPartResultReporterInterface*
02181 UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
02182   return per_thread_test_part_result_reporter_.get();
02183 }
02184 
02185 // Sets the test part result reporter for the current thread.
02186 void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
02187     TestPartResultReporterInterface* reporter) {
02188   per_thread_test_part_result_reporter_.set(reporter);
02189 }
02190 
02191 // Gets the number of successful test cases.
02192 int UnitTestImpl::successful_test_case_count() const {
02193   return CountIf(test_cases_, TestCasePassed);
02194 }
02195 
02196 // Gets the number of failed test cases.
02197 int UnitTestImpl::failed_test_case_count() const {
02198   return CountIf(test_cases_, TestCaseFailed);
02199 }
02200 
02201 // Gets the number of all test cases.
02202 int UnitTestImpl::total_test_case_count() const {
02203   return static_cast<int>(test_cases_.size());
02204 }
02205 
02206 // Gets the number of all test cases that contain at least one test
02207 // that should run.
02208 int UnitTestImpl::test_case_to_run_count() const {
02209   return CountIf(test_cases_, ShouldRunTestCase);
02210 }
02211 
02212 // Gets the number of successful tests.
02213 int UnitTestImpl::successful_test_count() const {
02214   return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count);
02215 }
02216 
02217 // Gets the number of failed tests.
02218 int UnitTestImpl::failed_test_count() const {
02219   return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count);
02220 }
02221 
02222 // Gets the number of disabled tests that will be reported in the XML report.
02223 int UnitTestImpl::reportable_disabled_test_count() const {
02224   return SumOverTestCaseList(test_cases_,
02225                              &TestCase::reportable_disabled_test_count);
02226 }
02227 
02228 // Gets the number of disabled tests.
02229 int UnitTestImpl::disabled_test_count() const {
02230   return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count);
02231 }
02232 
02233 // Gets the number of tests to be printed in the XML report.
02234 int UnitTestImpl::reportable_test_count() const {
02235   return SumOverTestCaseList(test_cases_, &TestCase::reportable_test_count);
02236 }
02237 
02238 // Gets the number of all tests.
02239 int UnitTestImpl::total_test_count() const {
02240   return SumOverTestCaseList(test_cases_, &TestCase::total_test_count);
02241 }
02242 
02243 // Gets the number of tests that should run.
02244 int UnitTestImpl::test_to_run_count() const {
02245   return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count);
02246 }
02247 
02248 // Returns the current OS stack trace as an std::string.
02249 //
02250 // The maximum number of stack frames to be included is specified by
02251 // the gtest_stack_trace_depth flag.  The skip_count parameter
02252 // specifies the number of top frames to be skipped, which doesn't
02253 // count against the number of frames to be included.
02254 //
02255 // For example, if Foo() calls Bar(), which in turn calls
02256 // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
02257 // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
02258 std::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
02259   (void)skip_count;
02260   return "";
02261 }
02262 
02263 // Returns the current time in milliseconds.
02264 TimeInMillis GetTimeInMillis() {
02265 #if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__)
02266   // Difference between 1970-01-01 and 1601-01-01 in milliseconds.
02267   // http://analogous.blogspot.com/2005/04/epoch.html
02268   const TimeInMillis kJavaEpochToWinFileTimeDelta =
02269     static_cast<TimeInMillis>(116444736UL) * 100000UL;
02270   const DWORD kTenthMicrosInMilliSecond = 10000;
02271 
02272   SYSTEMTIME now_systime;
02273   FILETIME now_filetime;
02274   ULARGE_INTEGER now_int64;
02275   // TODO(kenton@google.com): Shouldn't this just use
02276   //   GetSystemTimeAsFileTime()?
02277   GetSystemTime(&now_systime);
02278   if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
02279     now_int64.LowPart = now_filetime.dwLowDateTime;
02280     now_int64.HighPart = now_filetime.dwHighDateTime;
02281     now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
02282       kJavaEpochToWinFileTimeDelta;
02283     return now_int64.QuadPart;
02284   }
02285   return 0;
02286 #elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_
02287   __timeb64 now;
02288 
02289 # ifdef _MSC_VER
02290 
02291   // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996
02292   // (deprecated function) there.
02293   // TODO(kenton@google.com): Use GetTickCount()?  Or use
02294   //   SystemTimeToFileTime()
02295 #  pragma warning(push)          // Saves the current warning state.
02296 #  pragma warning(disable:4996)  // Temporarily disables warning 4996.
02297   _ftime64(&now);
02298 #  pragma warning(pop)           // Restores the warning state.
02299 # else
02300 
02301   _ftime64(&now);
02302 
02303 # endif  // _MSC_VER
02304 
02305   return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
02306 #elif GTEST_HAS_GETTIMEOFDAY_
02307   struct timeval now;
02308   gettimeofday(&now, NULL);
02309   return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
02310 #else
02311 # error "Don't know how to get the current time on your system."
02312 #endif
02313 }
02314 
02315 // Utilities
02316 
02317 // class String.
02318 
02319 #if GTEST_OS_WINDOWS_MOBILE
02320 // Creates a UTF-16 wide string from the given ANSI string, allocating
02321 // memory using new. The caller is responsible for deleting the return
02322 // value using delete[]. Returns the wide string, or NULL if the
02323 // input is NULL.
02324 LPCWSTR String::AnsiToUtf16(const char* ansi) {
02325   if (!ansi) return NULL;
02326   const int length = strlen(ansi);
02327   const int unicode_length =
02328       MultiByteToWideChar(CP_ACP, 0, ansi, length,
02329                           NULL, 0);
02330   WCHAR* unicode = new WCHAR[unicode_length + 1];
02331   MultiByteToWideChar(CP_ACP, 0, ansi, length,
02332                       unicode, unicode_length);
02333   unicode[unicode_length] = 0;
02334   return unicode;
02335 }
02336 
02337 // Creates an ANSI string from the given wide string, allocating
02338 // memory using new. The caller is responsible for deleting the return
02339 // value using delete[]. Returns the ANSI string, or NULL if the
02340 // input is NULL.
02341 const char* String::Utf16ToAnsi(LPCWSTR utf16_str)  {
02342   if (!utf16_str) return NULL;
02343   const int ansi_length =
02344       WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
02345                           NULL, 0, NULL, NULL);
02346   char* ansi = new char[ansi_length + 1];
02347   WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
02348                       ansi, ansi_length, NULL, NULL);
02349   ansi[ansi_length] = 0;
02350   return ansi;
02351 }
02352 
02353 #endif  // GTEST_OS_WINDOWS_MOBILE
02354 
02355 // Compares two C strings.  Returns true iff they have the same content.
02356 //
02357 // Unlike strcmp(), this function can handle NULL argument(s).  A NULL
02358 // C string is considered different to any non-NULL C string,
02359 // including the empty string.
02360 bool String::CStringEquals(const char * lhs, const char * rhs) {
02361   if ( lhs == NULL ) return rhs == NULL;
02362 
02363   if ( rhs == NULL ) return false;
02364 
02365   return strcmp(lhs, rhs) == 0;
02366 }
02367 
02368 #if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
02369 
02370 // Converts an array of wide chars to a narrow string using the UTF-8
02371 // encoding, and streams the result to the given Message object.
02372 static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
02373                                      Message* msg) {
02374   for (size_t i = 0; i != length; ) {  // NOLINT
02375     if (wstr[i] != L'\0') {
02376       *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
02377       while (i != length && wstr[i] != L'\0')
02378         i++;
02379     } else {
02380       *msg << '\0';
02381       i++;
02382     }
02383   }
02384 }
02385 
02386 #endif  // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
02387 
02388 }  // namespace internal
02389 
02390 // Constructs an empty Message.
02391 // We allocate the stringstream separately because otherwise each use of
02392 // ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's
02393 // stack frame leading to huge stack frames in some cases; gcc does not reuse
02394 // the stack space.
02395 Message::Message() : ss_(new ::std::stringstream) {
02396   // By default, we want there to be enough precision when printing
02397   // a double to a Message.
02398   *ss_ << std::setprecision(std::numeric_limits<double>::digits10 + 2);
02399 }
02400 
02401 // These two overloads allow streaming a wide C string to a Message
02402 // using the UTF-8 encoding.
02403 Message& Message::operator <<(const wchar_t* wide_c_str) {
02404   return *this << internal::String::ShowWideCString(wide_c_str);
02405 }
02406 Message& Message::operator <<(wchar_t* wide_c_str) {
02407   return *this << internal::String::ShowWideCString(wide_c_str);
02408 }
02409 
02410 #if GTEST_HAS_STD_WSTRING
02411 // Converts the given wide string to a narrow string using the UTF-8
02412 // encoding, and streams the result to this Message object.
02413 Message& Message::operator <<(const ::std::wstring& wstr) {
02414   internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
02415   return *this;
02416 }
02417 #endif  // GTEST_HAS_STD_WSTRING
02418 
02419 #if GTEST_HAS_GLOBAL_WSTRING
02420 // Converts the given wide string to a narrow string using the UTF-8
02421 // encoding, and streams the result to this Message object.
02422 Message& Message::operator <<(const ::wstring& wstr) {
02423   internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
02424   return *this;
02425 }
02426 #endif  // GTEST_HAS_GLOBAL_WSTRING
02427 
02428 // Gets the text streamed to this object so far as an std::string.
02429 // Each '\0' character in the buffer is replaced with "\\0".
02430 std::string Message::GetString() const {
02431   return internal::StringStreamToString(ss_.get());
02432 }
02433 
02434 // AssertionResult constructors.
02435 // Used in EXPECT_TRUE/FALSE(assertion_result).
02436 AssertionResult::AssertionResult(const AssertionResult& other)
02437     : success_(other.success_),
02438       message_(other.message_.get() != NULL ?
02439                new ::std::string(*other.message_) :
02440                static_cast< ::std::string*>(NULL)) {
02441 }
02442 
02443 // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
02444 AssertionResult AssertionResult::operator!() const {
02445   AssertionResult negation(!success_);
02446   if (message_.get() != NULL)
02447     negation << *message_;
02448   return negation;
02449 }
02450 
02451 // Makes a successful assertion result.
02452 AssertionResult AssertionSuccess() {
02453   return AssertionResult(true);
02454 }
02455 
02456 // Makes a failed assertion result.
02457 AssertionResult AssertionFailure() {
02458   return AssertionResult(false);
02459 }
02460 
02461 // Makes a failed assertion result with the given failure message.
02462 // Deprecated; use AssertionFailure() << message.
02463 AssertionResult AssertionFailure(const Message& message) {
02464   return AssertionFailure() << message;
02465 }
02466 
02467 namespace internal {
02468 
02469 // Constructs and returns the message for an equality assertion
02470 // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
02471 //
02472 // The first four parameters are the expressions used in the assertion
02473 // and their values, as strings.  For example, for ASSERT_EQ(foo, bar)
02474 // where foo is 5 and bar is 6, we have:
02475 //
02476 //   expected_expression: "foo"
02477 //   actual_expression:   "bar"
02478 //   expected_value:      "5"
02479 //   actual_value:        "6"
02480 //
02481 // The ignoring_case parameter is true iff the assertion is a
02482 // *_STRCASEEQ*.  When it's true, the string " (ignoring case)" will
02483 // be inserted into the message.
02484 AssertionResult EqFailure(const char* expected_expression,
02485                           const char* actual_expression,
02486                           const std::string& expected_value,
02487                           const std::string& actual_value,
02488                           bool ignoring_case) {
02489   Message msg;
02490   msg << "Value of: " << actual_expression;
02491   if (actual_value != actual_expression) {
02492     msg << "\n  Actual: " << actual_value;
02493   }
02494 
02495   msg << "\nExpected: " << expected_expression;
02496   if (ignoring_case) {
02497     msg << " (ignoring case)";
02498   }
02499   if (expected_value != expected_expression) {
02500     msg << "\nWhich is: " << expected_value;
02501   }
02502 
02503   return AssertionFailure() << msg;
02504 }
02505 
02506 // Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
02507 std::string GetBoolAssertionFailureMessage(
02508     const AssertionResult& assertion_result,
02509     const char* expression_text,
02510     const char* actual_predicate_value,
02511     const char* expected_predicate_value) {
02512   const char* actual_message = assertion_result.message();
02513   Message msg;
02514   msg << "Value of: " << expression_text
02515       << "\n  Actual: " << actual_predicate_value;
02516   if (actual_message[0] != '\0')
02517     msg << " (" << actual_message << ")";
02518   msg << "\nExpected: " << expected_predicate_value;
02519   return msg.GetString();
02520 }
02521 
02522 // Helper function for implementing ASSERT_NEAR.
02523 AssertionResult DoubleNearPredFormat(const char* expr1,
02524                                      const char* expr2,
02525                                      const char* abs_error_expr,
02526                                      double val1,
02527                                      double val2,
02528                                      double abs_error) {
02529   const double diff = fabs(val1 - val2);
02530   if (diff <= abs_error) return AssertionSuccess();
02531 
02532   // TODO(wan): do not print the value of an expression if it's
02533   // already a literal.
02534   return AssertionFailure()
02535       << "The difference between " << expr1 << " and " << expr2
02536       << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"
02537       << expr1 << " evaluates to " << val1 << ",\n"
02538       << expr2 << " evaluates to " << val2 << ", and\n"
02539       << abs_error_expr << " evaluates to " << abs_error << ".";
02540 }
02541 
02542 
02543 // Helper template for implementing FloatLE() and DoubleLE().
02544 template <typename RawType>
02545 AssertionResult FloatingPointLE(const char* expr1,
02546                                 const char* expr2,
02547                                 RawType val1,
02548                                 RawType val2) {
02549   // Returns success if val1 is less than val2,
02550   if (val1 < val2) {
02551     return AssertionSuccess();
02552   }
02553 
02554   // or if val1 is almost equal to val2.
02555   const FloatingPoint<RawType> lhs(val1), rhs(val2);
02556   if (lhs.AlmostEquals(rhs)) {
02557     return AssertionSuccess();
02558   }
02559 
02560   // Note that the above two checks will both fail if either val1 or
02561   // val2 is NaN, as the IEEE floating-point standard requires that
02562   // any predicate involving a NaN must return false.
02563 
02564   ::std::stringstream val1_ss;
02565   val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
02566           << val1;
02567 
02568   ::std::stringstream val2_ss;
02569   val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
02570           << val2;
02571 
02572   return AssertionFailure()
02573       << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
02574       << "  Actual: " << StringStreamToString(&val1_ss) << " vs "
02575       << StringStreamToString(&val2_ss);
02576 }
02577 
02578 }  // namespace internal
02579 
02580 // Asserts that val1 is less than, or almost equal to, val2.  Fails
02581 // otherwise.  In particular, it fails if either val1 or val2 is NaN.
02582 AssertionResult FloatLE(const char* expr1, const char* expr2,
02583                         float val1, float val2) {
02584   return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
02585 }
02586 
02587 // Asserts that val1 is less than, or almost equal to, val2.  Fails
02588 // otherwise.  In particular, it fails if either val1 or val2 is NaN.
02589 AssertionResult DoubleLE(const char* expr1, const char* expr2,
02590                          double val1, double val2) {
02591   return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
02592 }
02593 
02594 namespace internal {
02595 
02596 // The helper function for {ASSERT|EXPECT}_EQ with int or enum
02597 // arguments.
02598 AssertionResult CmpHelperEQ(const char* expected_expression,
02599                             const char* actual_expression,
02600                             BiggestInt expected,
02601                             BiggestInt actual) {
02602   if (expected == actual) {
02603     return AssertionSuccess();
02604   }
02605 
02606   return EqFailure(expected_expression,
02607                    actual_expression,
02608                    FormatForComparisonFailureMessage(expected, actual),
02609                    FormatForComparisonFailureMessage(actual, expected),
02610                    false);
02611 }
02612 
02613 // A macro for implementing the helper functions needed to implement
02614 // ASSERT_?? and EXPECT_?? with integer or enum arguments.  It is here
02615 // just to avoid copy-and-paste of similar code.
02616 #define GTEST_IMPL_CMP_HELPER_(op_name, op)\
02617 AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
02618                                    BiggestInt val1, BiggestInt val2) {\
02619   if (val1 op val2) {\
02620     return AssertionSuccess();\
02621   } else {\
02622     return AssertionFailure() \
02623         << "Expected: (" << expr1 << ") " #op " (" << expr2\
02624         << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
02625         << " vs " << FormatForComparisonFailureMessage(val2, val1);\
02626   }\
02627 }
02628 
02629 // Implements the helper function for {ASSERT|EXPECT}_NE with int or
02630 // enum arguments.
02631 GTEST_IMPL_CMP_HELPER_(NE, !=)
02632 // Implements the helper function for {ASSERT|EXPECT}_LE with int or
02633 // enum arguments.
02634 GTEST_IMPL_CMP_HELPER_(LE, <=)
02635 // Implements the helper function for {ASSERT|EXPECT}_LT with int or
02636 // enum arguments.
02637 GTEST_IMPL_CMP_HELPER_(LT, < )
02638 // Implements the helper function for {ASSERT|EXPECT}_GE with int or
02639 // enum arguments.
02640 GTEST_IMPL_CMP_HELPER_(GE, >=)
02641 // Implements the helper function for {ASSERT|EXPECT}_GT with int or
02642 // enum arguments.
02643 GTEST_IMPL_CMP_HELPER_(GT, > )
02644 
02645 #undef GTEST_IMPL_CMP_HELPER_
02646 
02647 // The helper function for {ASSERT|EXPECT}_STREQ.
02648 AssertionResult CmpHelperSTREQ(const char* expected_expression,
02649                                const char* actual_expression,
02650                                const char* expected,
02651                                const char* actual) {
02652   if (String::CStringEquals(expected, actual)) {
02653     return AssertionSuccess();
02654   }
02655 
02656   return EqFailure(expected_expression,
02657                    actual_expression,
02658                    PrintToString(expected),
02659                    PrintToString(actual),
02660                    false);
02661 }
02662 
02663 // The helper function for {ASSERT|EXPECT}_STRCASEEQ.
02664 AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression,
02665                                    const char* actual_expression,
02666                                    const char* expected,
02667                                    const char* actual) {
02668   if (String::CaseInsensitiveCStringEquals(expected, actual)) {
02669     return AssertionSuccess();
02670   }
02671 
02672   return EqFailure(expected_expression,
02673                    actual_expression,
02674                    PrintToString(expected),
02675                    PrintToString(actual),
02676                    true);
02677 }
02678 
02679 // The helper function for {ASSERT|EXPECT}_STRNE.
02680 AssertionResult CmpHelperSTRNE(const char* s1_expression,
02681                                const char* s2_expression,
02682                                const char* s1,
02683                                const char* s2) {
02684   if (!String::CStringEquals(s1, s2)) {
02685     return AssertionSuccess();
02686   } else {
02687     return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
02688                               << s2_expression << "), actual: \""
02689                               << s1 << "\" vs \"" << s2 << "\"";
02690   }
02691 }
02692 
02693 // The helper function for {ASSERT|EXPECT}_STRCASENE.
02694 AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
02695                                    const char* s2_expression,
02696                                    const char* s1,
02697                                    const char* s2) {
02698   if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
02699     return AssertionSuccess();
02700   } else {
02701     return AssertionFailure()
02702         << "Expected: (" << s1_expression << ") != ("
02703         << s2_expression << ") (ignoring case), actual: \""
02704         << s1 << "\" vs \"" << s2 << "\"";
02705   }
02706 }
02707 
02708 }  // namespace internal
02709 
02710 namespace {
02711 
02712 // Helper functions for implementing IsSubString() and IsNotSubstring().
02713 
02714 // This group of overloaded functions return true iff needle is a
02715 // substring of haystack.  NULL is considered a substring of itself
02716 // only.
02717 
02718 bool IsSubstringPred(const char* needle, const char* haystack) {
02719   if (needle == NULL || haystack == NULL)
02720     return needle == haystack;
02721 
02722   return strstr(haystack, needle) != NULL;
02723 }
02724 
02725 bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
02726   if (needle == NULL || haystack == NULL)
02727     return needle == haystack;
02728 
02729   return wcsstr(haystack, needle) != NULL;
02730 }
02731 
02732 // StringType here can be either ::std::string or ::std::wstring.
02733 template <typename StringType>
02734 bool IsSubstringPred(const StringType& needle,
02735                      const StringType& haystack) {
02736   return haystack.find(needle) != StringType::npos;
02737 }
02738 
02739 // This function implements either IsSubstring() or IsNotSubstring(),
02740 // depending on the value of the expected_to_be_substring parameter.
02741 // StringType here can be const char*, const wchar_t*, ::std::string,
02742 // or ::std::wstring.
02743 template <typename StringType>
02744 AssertionResult IsSubstringImpl(
02745     bool expected_to_be_substring,
02746     const char* needle_expr, const char* haystack_expr,
02747     const StringType& needle, const StringType& haystack) {
02748   if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
02749     return AssertionSuccess();
02750 
02751   const bool is_wide_string = sizeof(needle[0]) > 1;
02752   const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
02753   return AssertionFailure()
02754       << "Value of: " << needle_expr << "\n"
02755       << "  Actual: " << begin_string_quote << needle << "\"\n"
02756       << "Expected: " << (expected_to_be_substring ? "" : "not ")
02757       << "a substring of " << haystack_expr << "\n"
02758       << "Which is: " << begin_string_quote << haystack << "\"";
02759 }
02760 
02761 }  // namespace
02762 
02763 // IsSubstring() and IsNotSubstring() check whether needle is a
02764 // substring of haystack (NULL is considered a substring of itself
02765 // only), and return an appropriate error message when they fail.
02766 
02767 AssertionResult IsSubstring(
02768     const char* needle_expr, const char* haystack_expr,
02769     const char* needle, const char* haystack) {
02770   return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
02771 }
02772 
02773 AssertionResult IsSubstring(
02774     const char* needle_expr, const char* haystack_expr,
02775     const wchar_t* needle, const wchar_t* haystack) {
02776   return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
02777 }
02778 
02779 AssertionResult IsNotSubstring(
02780     const char* needle_expr, const char* haystack_expr,
02781     const char* needle, const char* haystack) {
02782   return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
02783 }
02784 
02785 AssertionResult IsNotSubstring(
02786     const char* needle_expr, const char* haystack_expr,
02787     const wchar_t* needle, const wchar_t* haystack) {
02788   return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
02789 }
02790 
02791 AssertionResult IsSubstring(
02792     const char* needle_expr, const char* haystack_expr,
02793     const ::std::string& needle, const ::std::string& haystack) {
02794   return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
02795 }
02796 
02797 AssertionResult IsNotSubstring(
02798     const char* needle_expr, const char* haystack_expr,
02799     const ::std::string& needle, const ::std::string& haystack) {
02800   return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
02801 }
02802 
02803 #if GTEST_HAS_STD_WSTRING
02804 AssertionResult IsSubstring(
02805     const char* needle_expr, const char* haystack_expr,
02806     const ::std::wstring& needle, const ::std::wstring& haystack) {
02807   return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
02808 }
02809 
02810 AssertionResult IsNotSubstring(
02811     const char* needle_expr, const char* haystack_expr,
02812     const ::std::wstring& needle, const ::std::wstring& haystack) {
02813   return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
02814 }
02815 #endif  // GTEST_HAS_STD_WSTRING
02816 
02817 namespace internal {
02818 
02819 #if GTEST_OS_WINDOWS
02820 
02821 namespace {
02822 
02823 // Helper function for IsHRESULT{SuccessFailure} predicates
02824 AssertionResult HRESULTFailureHelper(const char* expr,
02825                                      const char* expected,
02826                                      long hr) {  // NOLINT
02827 # if GTEST_OS_WINDOWS_MOBILE
02828 
02829   // Windows CE doesn't support FormatMessage.
02830   const char error_text[] = "";
02831 
02832 # else
02833 
02834   // Looks up the human-readable system message for the HRESULT code
02835   // and since we're not passing any params to FormatMessage, we don't
02836   // want inserts expanded.
02837   const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
02838                        FORMAT_MESSAGE_IGNORE_INSERTS;
02839   const DWORD kBufSize = 4096;
02840   // Gets the system's human readable message string for this HRESULT.
02841   char error_text[kBufSize] = { '\0' };
02842   DWORD message_length = ::FormatMessageA(kFlags,
02843                                           0,  // no source, we're asking system
02844                                           hr,  // the error
02845                                           0,  // no line width restrictions
02846                                           error_text,  // output buffer
02847                                           kBufSize,  // buf size
02848                                           NULL);  // no arguments for inserts
02849   // Trims tailing white space (FormatMessage leaves a trailing CR-LF)
02850   for (; message_length && IsSpace(error_text[message_length - 1]);
02851           --message_length) {
02852     error_text[message_length - 1] = '\0';
02853   }
02854 
02855 # endif  // GTEST_OS_WINDOWS_MOBILE
02856 
02857   const std::string error_hex("0x" + String::FormatHexInt(hr));
02858   return ::testing::AssertionFailure()
02859       << "Expected: " << expr << " " << expected << ".\n"
02860       << "  Actual: " << error_hex << " " << error_text << "\n";
02861 }
02862 
02863 }  // namespace
02864 
02865 AssertionResult IsHRESULTSuccess(const char* expr, long hr) {  // NOLINT
02866   if (SUCCEEDED(hr)) {
02867     return AssertionSuccess();
02868   }
02869   return HRESULTFailureHelper(expr, "succeeds", hr);
02870 }
02871 
02872 AssertionResult IsHRESULTFailure(const char* expr, long hr) {  // NOLINT
02873   if (FAILED(hr)) {
02874     return AssertionSuccess();
02875   }
02876   return HRESULTFailureHelper(expr, "fails", hr);
02877 }
02878 
02879 #endif  // GTEST_OS_WINDOWS
02880 
02881 // Utility functions for encoding Unicode text (wide strings) in
02882 // UTF-8.
02883 
02884 // A Unicode code-point can have upto 21 bits, and is encoded in UTF-8
02885 // like this:
02886 //
02887 // Code-point length   Encoding
02888 //   0 -  7 bits       0xxxxxxx
02889 //   8 - 11 bits       110xxxxx 10xxxxxx
02890 //  12 - 16 bits       1110xxxx 10xxxxxx 10xxxxxx
02891 //  17 - 21 bits       11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
02892 
02893 // The maximum code-point a one-byte UTF-8 sequence can represent.
02894 const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) <<  7) - 1;
02895 
02896 // The maximum code-point a two-byte UTF-8 sequence can represent.
02897 const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1;
02898 
02899 // The maximum code-point a three-byte UTF-8 sequence can represent.
02900 const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2*6)) - 1;
02901 
02902 // The maximum code-point a four-byte UTF-8 sequence can represent.
02903 const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3*6)) - 1;
02904 
02905 // Chops off the n lowest bits from a bit pattern.  Returns the n
02906 // lowest bits.  As a side effect, the original bit pattern will be
02907 // shifted to the right by n bits.
02908 inline UInt32 ChopLowBits(UInt32* bits, int n) {
02909   const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1);
02910   *bits >>= n;
02911   return low_bits;
02912 }
02913 
02914 // Converts a Unicode code point to a narrow string in UTF-8 encoding.
02915 // code_point parameter is of type UInt32 because wchar_t may not be
02916 // wide enough to contain a code point.
02917 // If the code_point is not a valid Unicode code point
02918 // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
02919 // to "(Invalid Unicode 0xXXXXXXXX)".
02920 std::string CodePointToUtf8(UInt32 code_point) {
02921   if (code_point > kMaxCodePoint4) {
02922     return "(Invalid Unicode 0x" + String::FormatHexInt(code_point) + ")";
02923   }
02924 
02925   char str[5];  // Big enough for the largest valid code point.
02926   if (code_point <= kMaxCodePoint1) {
02927     str[1] = '\0';
02928     str[0] = static_cast<char>(code_point);                          // 0xxxxxxx
02929   } else if (code_point <= kMaxCodePoint2) {
02930     str[2] = '\0';
02931     str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
02932     str[0] = static_cast<char>(0xC0 | code_point);                   // 110xxxxx
02933   } else if (code_point <= kMaxCodePoint3) {
02934     str[3] = '\0';
02935     str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
02936     str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
02937     str[0] = static_cast<char>(0xE0 | code_point);                   // 1110xxxx
02938   } else {  // code_point <= kMaxCodePoint4
02939     str[4] = '\0';
02940     str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
02941     str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
02942     str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
02943     str[0] = static_cast<char>(0xF0 | code_point);                   // 11110xxx
02944   }
02945   return str;
02946 }
02947 
02948 // The following two functions only make sense if the the system
02949 // uses UTF-16 for wide string encoding. All supported systems
02950 // with 16 bit wchar_t (Windows, Cygwin, Symbian OS) do use UTF-16.
02951 
02952 // Determines if the arguments constitute UTF-16 surrogate pair
02953 // and thus should be combined into a single Unicode code point
02954 // using CreateCodePointFromUtf16SurrogatePair.
02955 inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
02956   return sizeof(wchar_t) == 2 &&
02957       (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;
02958 }
02959 
02960 // Creates a Unicode code point from UTF16 surrogate pair.
02961 inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first,
02962                                                     wchar_t second) {
02963   const UInt32 mask = (1 << 10) - 1;
02964   return (sizeof(wchar_t) == 2) ?
02965       (((first & mask) << 10) | (second & mask)) + 0x10000 :
02966       // This function should not be called when the condition is
02967       // false, but we provide a sensible default in case it is.
02968       static_cast<UInt32>(first);
02969 }
02970 
02971 // Converts a wide string to a narrow string in UTF-8 encoding.
02972 // The wide string is assumed to have the following encoding:
02973 //   UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
02974 //   UTF-32 if sizeof(wchar_t) == 4 (on Linux)
02975 // Parameter str points to a null-terminated wide string.
02976 // Parameter num_chars may additionally limit the number
02977 // of wchar_t characters processed. -1 is used when the entire string
02978 // should be processed.
02979 // If the string contains code points that are not valid Unicode code points
02980 // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
02981 // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
02982 // and contains invalid UTF-16 surrogate pairs, values in those pairs
02983 // will be encoded as individual Unicode characters from Basic Normal Plane.
02984 std::string WideStringToUtf8(const wchar_t* str, int num_chars) {
02985   if (num_chars == -1)
02986     num_chars = static_cast<int>(wcslen(str));
02987 
02988   ::std::stringstream stream;
02989   for (int i = 0; i < num_chars; ++i) {
02990     UInt32 unicode_code_point;
02991 
02992     if (str[i] == L'\0') {
02993       break;
02994     } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
02995       unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i],
02996                                                                  str[i + 1]);
02997       i++;
02998     } else {
02999       unicode_code_point = static_cast<UInt32>(str[i]);
03000     }
03001 
03002     stream << CodePointToUtf8(unicode_code_point);
03003   }
03004   return StringStreamToString(&stream);
03005 }
03006 
03007 // Converts a wide C string to an std::string using the UTF-8 encoding.
03008 // NULL will be converted to "(null)".
03009 std::string String::ShowWideCString(const wchar_t * wide_c_str) {
03010   if (wide_c_str == NULL)  return "(null)";
03011 
03012   return internal::WideStringToUtf8(wide_c_str, -1);
03013 }
03014 
03015 // Compares two wide C strings.  Returns true iff they have the same
03016 // content.
03017 //
03018 // Unlike wcscmp(), this function can handle NULL argument(s).  A NULL
03019 // C string is considered different to any non-NULL C string,
03020 // including the empty string.
03021 bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {
03022   if (lhs == NULL) return rhs == NULL;
03023 
03024   if (rhs == NULL) return false;
03025 
03026   return wcscmp(lhs, rhs) == 0;
03027 }
03028 
03029 // Helper function for *_STREQ on wide strings.
03030 AssertionResult CmpHelperSTREQ(const char* expected_expression,
03031                                const char* actual_expression,
03032                                const wchar_t* expected,
03033                                const wchar_t* actual) {
03034   if (String::WideCStringEquals(expected, actual)) {
03035     return AssertionSuccess();
03036   }
03037 
03038   return EqFailure(expected_expression,
03039                    actual_expression,
03040                    PrintToString(expected),
03041                    PrintToString(actual),
03042                    false);
03043 }
03044 
03045 // Helper function for *_STRNE on wide strings.
03046 AssertionResult CmpHelperSTRNE(const char* s1_expression,
03047                                const char* s2_expression,
03048                                const wchar_t* s1,
03049                                const wchar_t* s2) {
03050   if (!String::WideCStringEquals(s1, s2)) {
03051     return AssertionSuccess();
03052   }
03053 
03054   return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
03055                             << s2_expression << "), actual: "
03056                             << PrintToString(s1)
03057                             << " vs " << PrintToString(s2);
03058 }
03059 
03060 // Compares two C strings, ignoring case.  Returns true iff they have
03061 // the same content.
03062 //
03063 // Unlike strcasecmp(), this function can handle NULL argument(s).  A
03064 // NULL C string is considered different to any non-NULL C string,
03065 // including the empty string.
03066 bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) {
03067   if (lhs == NULL)
03068     return rhs == NULL;
03069   if (rhs == NULL)
03070     return false;
03071   return posix::StrCaseCmp(lhs, rhs) == 0;
03072 }
03073 
03074   // Compares two wide C strings, ignoring case.  Returns true iff they
03075   // have the same content.
03076   //
03077   // Unlike wcscasecmp(), this function can handle NULL argument(s).
03078   // A NULL C string is considered different to any non-NULL wide C string,
03079   // including the empty string.
03080   // NB: The implementations on different platforms slightly differ.
03081   // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
03082   // environment variable. On GNU platform this method uses wcscasecmp
03083   // which compares according to LC_CTYPE category of the current locale.
03084   // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
03085   // current locale.
03086 bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
03087                                               const wchar_t* rhs) {
03088   if (lhs == NULL) return rhs == NULL;
03089 
03090   if (rhs == NULL) return false;
03091 
03092 #if GTEST_OS_WINDOWS
03093   return _wcsicmp(lhs, rhs) == 0;
03094 #elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID
03095   return wcscasecmp(lhs, rhs) == 0;
03096 #else
03097   // Android, Mac OS X and Cygwin don't define wcscasecmp.
03098   // Other unknown OSes may not define it either.
03099   wint_t left, right;
03100   do {
03101     left = towlower(*lhs++);
03102     right = towlower(*rhs++);
03103   } while (left && left == right);
03104   return left == right;
03105 #endif  // OS selector
03106 }
03107 
03108 // Returns true iff str ends with the given suffix, ignoring case.
03109 // Any string is considered to end with an empty suffix.
03110 bool String::EndsWithCaseInsensitive(
03111     const std::string& str, const std::string& suffix) {
03112   const size_t str_len = str.length();
03113   const size_t suffix_len = suffix.length();
03114   return (str_len >= suffix_len) &&
03115          CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len,
03116                                       suffix.c_str());
03117 }
03118 
03119 // Formats an int value as "%02d".
03120 std::string String::FormatIntWidth2(int value) {
03121   std::stringstream ss;
03122   ss << std::setfill('0') << std::setw(2) << value;
03123   return ss.str();
03124 }
03125 
03126 // Formats an int value as "%X".
03127 std::string String::FormatHexInt(int value) {
03128   std::stringstream ss;
03129   ss << std::hex << std::uppercase << value;
03130   return ss.str();
03131 }
03132 
03133 // Formats a byte as "%02X".
03134 std::string String::FormatByte(unsigned char value) {
03135   std::stringstream ss;
03136   ss << std::setfill('0') << std::setw(2) << std::hex << std::uppercase
03137      << static_cast<unsigned int>(value);
03138   return ss.str();
03139 }
03140 
03141 // Converts the buffer in a stringstream to an std::string, converting NUL
03142 // bytes to "\\0" along the way.
03143 std::string StringStreamToString(::std::stringstream* ss) {
03144   const ::std::string& str = ss->str();
03145   const char* const start = str.c_str();
03146   const char* const end = start + str.length();
03147 
03148   std::string result;
03149   result.reserve(2 * (end - start));
03150   for (const char* ch = start; ch != end; ++ch) {
03151     if (*ch == '\0') {
03152       result += "\\0";  // Replaces NUL with "\\0";
03153     } else {
03154       result += *ch;
03155     }
03156   }
03157 
03158   return result;
03159 }
03160 
03161 // Appends the user-supplied message to the Google-Test-generated message.
03162 std::string AppendUserMessage(const std::string& gtest_msg,
03163                               const Message& user_msg) {
03164   // Appends the user message if it's non-empty.
03165   const std::string user_msg_string = user_msg.GetString();
03166   if (user_msg_string.empty()) {
03167     return gtest_msg;
03168   }
03169 
03170   return gtest_msg + "\n" + user_msg_string;
03171 }
03172 
03173 }  // namespace internal
03174 
03175 // class TestResult
03176 
03177 // Creates an empty TestResult.
03178 TestResult::TestResult()
03179     : death_test_count_(0),
03180       elapsed_time_(0) {
03181 }
03182 
03183 // D'tor.
03184 TestResult::~TestResult() {
03185 }
03186 
03187 // Returns the i-th test part result among all the results. i can
03188 // range from 0 to total_part_count() - 1. If i is not in that range,
03189 // aborts the program.
03190 const TestPartResult& TestResult::GetTestPartResult(int i) const {
03191   if (i < 0 || i >= total_part_count())
03192     internal::posix::Abort();
03193   return test_part_results_.at(i);
03194 }
03195 
03196 // Returns the i-th test property. i can range from 0 to
03197 // test_property_count() - 1. If i is not in that range, aborts the
03198 // program.
03199 const TestProperty& TestResult::GetTestProperty(int i) const {
03200   if (i < 0 || i >= test_property_count())
03201     internal::posix::Abort();
03202   return test_properties_.at(i);
03203 }
03204 
03205 // Clears the test part results.
03206 void TestResult::ClearTestPartResults() {
03207   test_part_results_.clear();
03208 }
03209 
03210 // Adds a test part result to the list.
03211 void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
03212   test_part_results_.push_back(test_part_result);
03213 }
03214 
03215 // Adds a test property to the list. If a property with the same key as the
03216 // supplied property is already represented, the value of this test_property
03217 // replaces the old value for that key.
03218 void TestResult::RecordProperty(const std::string& xml_element,
03219                                 const TestProperty& test_property) {
03220   if (!ValidateTestProperty(xml_element, test_property)) {
03221     return;
03222   }
03223   internal::MutexLock lock(&test_properites_mutex_);
03224   const std::vector<TestProperty>::iterator property_with_matching_key =
03225       std::find_if(test_properties_.begin(), test_properties_.end(),
03226                    internal::TestPropertyKeyIs(test_property.key()));
03227   if (property_with_matching_key == test_properties_.end()) {
03228     test_properties_.push_back(test_property);
03229     return;
03230   }
03231   property_with_matching_key->SetValue(test_property.value());
03232 }
03233 
03234 // The list of reserved attributes used in the <testsuites> element of XML
03235 // output.
03236 static const char* const kReservedTestSuitesAttributes[] = {
03237   "disabled",
03238   "errors",
03239   "failures",
03240   "name",
03241   "random_seed",
03242   "tests",
03243   "time",
03244   "timestamp"
03245 };
03246 
03247 // The list of reserved attributes used in the <testsuite> element of XML
03248 // output.
03249 static const char* const kReservedTestSuiteAttributes[] = {
03250   "disabled",
03251   "errors",
03252   "failures",
03253   "name",
03254   "tests",
03255   "time"
03256 };
03257 
03258 // The list of reserved attributes used in the <testcase> element of XML output.
03259 static const char* const kReservedTestCaseAttributes[] = {
03260   "classname",
03261   "name",
03262   "status",
03263   "time",
03264   "type_param",
03265   "value_param"
03266 };
03267 
03268 template <int kSize>
03269 std::vector<std::string> ArrayAsVector(const char* const (&array)[kSize]) {
03270   return std::vector<std::string>(array, array + kSize);
03271 }
03272 
03273 static std::vector<std::string> GetReservedAttributesForElement(
03274     const std::string& xml_element) {
03275   if (xml_element == "testsuites") {
03276     return ArrayAsVector(kReservedTestSuitesAttributes);
03277   } else if (xml_element == "testsuite") {
03278     return ArrayAsVector(kReservedTestSuiteAttributes);
03279   } else if (xml_element == "testcase") {
03280     return ArrayAsVector(kReservedTestCaseAttributes);
03281   } else {
03282     GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element;
03283   }
03284   // This code is unreachable but some compilers may not realizes that.
03285   return std::vector<std::string>();
03286 }
03287 
03288 static std::string FormatWordList(const std::vector<std::string>& words) {
03289   Message word_list;
03290   for (size_t i = 0; i < words.size(); ++i) {
03291     if (i > 0 && words.size() > 2) {
03292       word_list << ", ";
03293     }
03294     if (i == words.size() - 1) {
03295       word_list << "and ";
03296     }
03297     word_list << "'" << words[i] << "'";
03298   }
03299   return word_list.GetString();
03300 }
03301 
03302 bool ValidateTestPropertyName(const std::string& property_name,
03303                               const std::vector<std::string>& reserved_names) {
03304   if (std::find(reserved_names.begin(), reserved_names.end(), property_name) !=
03305           reserved_names.end()) {
03306     ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name
03307                   << " (" << FormatWordList(reserved_names)
03308                   << " are reserved by " << GTEST_NAME_ << ")";
03309     return false;
03310   }
03311   return true;
03312 }
03313 
03314 // Adds a failure if the key is a reserved attribute of the element named
03315 // xml_element.  Returns true if the property is valid.
03316 bool TestResult::ValidateTestProperty(const std::string& xml_element,
03317                                       const TestProperty& test_property) {
03318   return ValidateTestPropertyName(test_property.key(),
03319                                   GetReservedAttributesForElement(xml_element));
03320 }
03321 
03322 // Clears the object.
03323 void TestResult::Clear() {
03324   test_part_results_.clear();
03325   test_properties_.clear();
03326   death_test_count_ = 0;
03327   elapsed_time_ = 0;
03328 }
03329 
03330 // Returns true iff the test failed.
03331 bool TestResult::Failed() const {
03332   for (int i = 0; i < total_part_count(); ++i) {
03333     if (GetTestPartResult(i).failed())
03334       return true;
03335   }
03336   return false;
03337 }
03338 
03339 // Returns true iff the test part fatally failed.
03340 static bool TestPartFatallyFailed(const TestPartResult& result) {
03341   return result.fatally_failed();
03342 }
03343 
03344 // Returns true iff the test fatally failed.
03345 bool TestResult::HasFatalFailure() const {
03346   return CountIf(test_part_results_, TestPartFatallyFailed) > 0;
03347 }
03348 
03349 // Returns true iff the test part non-fatally failed.
03350 static bool TestPartNonfatallyFailed(const TestPartResult& result) {
03351   return result.nonfatally_failed();
03352 }
03353 
03354 // Returns true iff the test has a non-fatal failure.
03355 bool TestResult::HasNonfatalFailure() const {
03356   return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0;
03357 }
03358 
03359 // Gets the number of all test parts.  This is the sum of the number
03360 // of successful test parts and the number of failed test parts.
03361 int TestResult::total_part_count() const {
03362   return static_cast<int>(test_part_results_.size());
03363 }
03364 
03365 // Returns the number of the test properties.
03366 int TestResult::test_property_count() const {
03367   return static_cast<int>(test_properties_.size());
03368 }
03369 
03370 // class Test
03371 
03372 // Creates a Test object.
03373 
03374 // The c'tor saves the values of all Google Test flags.
03375 Test::Test()
03376     : gtest_flag_saver_(new internal::GTestFlagSaver) {
03377 }
03378 
03379 // The d'tor restores the values of all Google Test flags.
03380 Test::~Test() {
03381   delete gtest_flag_saver_;
03382 }
03383 
03384 // Sets up the test fixture.
03385 //
03386 // A sub-class may override this.
03387 void Test::SetUp() {
03388 }
03389 
03390 // Tears down the test fixture.
03391 //
03392 // A sub-class may override this.
03393 void Test::TearDown() {
03394 }
03395 
03396 // Allows user supplied key value pairs to be recorded for later output.
03397 void Test::RecordProperty(const std::string& key, const std::string& value) {
03398   UnitTest::GetInstance()->RecordProperty(key, value);
03399 }
03400 
03401 // Allows user supplied key value pairs to be recorded for later output.
03402 void Test::RecordProperty(const std::string& key, int value) {
03403   Message value_message;
03404   value_message << value;
03405   RecordProperty(key, value_message.GetString().c_str());
03406 }
03407 
03408 namespace internal {
03409 
03410 void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
03411                                     const std::string& message) {
03412   // This function is a friend of UnitTest and as such has access to
03413   // AddTestPartResult.
03414   UnitTest::GetInstance()->AddTestPartResult(
03415       result_type,
03416       NULL,  // No info about the source file where the exception occurred.
03417       -1,    // We have no info on which line caused the exception.
03418       message,
03419       "");   // No stack trace, either.
03420 }
03421 
03422 }  // namespace internal
03423 
03424 // Google Test requires all tests in the same test case to use the same test
03425 // fixture class.  This function checks if the current test has the
03426 // same fixture class as the first test in the current test case.  If
03427 // yes, it returns true; otherwise it generates a Google Test failure and
03428 // returns false.
03429 bool Test::HasSameFixtureClass() {
03430   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
03431   const TestCase* const test_case = impl->current_test_case();
03432 
03433   // Info about the first test in the current test case.
03434   const TestInfo* const first_test_info = test_case->test_info_list()[0];
03435   const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_;
03436   const char* const first_test_name = first_test_info->name();
03437 
03438   // Info about the current test.
03439   const TestInfo* const this_test_info = impl->current_test_info();
03440   const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_;
03441   const char* const this_test_name = this_test_info->name();
03442 
03443   if (this_fixture_id != first_fixture_id) {
03444     // Is the first test defined using TEST?
03445     const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();
03446     // Is this test defined using TEST?
03447     const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();
03448 
03449     if (first_is_TEST || this_is_TEST) {
03450       // The user mixed TEST and TEST_F in this test case - we'll tell
03451       // him/her how to fix it.
03452 
03453       // Gets the name of the TEST and the name of the TEST_F.  Note
03454       // that first_is_TEST and this_is_TEST cannot both be true, as
03455       // the fixture IDs are different for the two tests.
03456       const char* const TEST_name =
03457           first_is_TEST ? first_test_name : this_test_name;
03458       const char* const TEST_F_name =
03459           first_is_TEST ? this_test_name : first_test_name;
03460 
03461       ADD_FAILURE()
03462           << "All tests in the same test case must use the same test fixture\n"
03463           << "class, so mixing TEST_F and TEST in the same test case is\n"
03464           << "illegal.  In test case " << this_test_info->test_case_name()
03465           << ",\n"
03466           << "test " << TEST_F_name << " is defined using TEST_F but\n"
03467           << "test " << TEST_name << " is defined using TEST.  You probably\n"
03468           << "want to change the TEST to TEST_F or move it to another test\n"
03469           << "case.";
03470     } else {
03471       // The user defined two fixture classes with the same name in
03472       // two namespaces - we'll tell him/her how to fix it.
03473       ADD_FAILURE()
03474           << "All tests in the same test case must use the same test fixture\n"
03475           << "class.  However, in test case "
03476           << this_test_info->test_case_name() << ",\n"
03477           << "you defined test " << first_test_name
03478           << " and test " << this_test_name << "\n"
03479           << "using two different test fixture classes.  This can happen if\n"
03480           << "the two classes are from different namespaces or translation\n"
03481           << "units and have the same name.  You should probably rename one\n"
03482           << "of the classes to put the tests into different test cases.";
03483     }
03484     return false;
03485   }
03486 
03487   return true;
03488 }
03489 
03490 #if GTEST_HAS_SEH
03491 
03492 // Adds an "exception thrown" fatal failure to the current test.  This
03493 // function returns its result via an output parameter pointer because VC++
03494 // prohibits creation of objects with destructors on stack in functions
03495 // using __try (see error C2712).
03496 static std::string* FormatSehExceptionMessage(DWORD exception_code,
03497                                               const char* location) {
03498   Message message;
03499   message << "SEH exception with code 0x" << std::setbase(16) <<
03500     exception_code << std::setbase(10) << " thrown in " << location << ".";
03501 
03502   return new std::string(message.GetString());
03503 }
03504 
03505 #endif  // GTEST_HAS_SEH
03506 
03507 namespace internal {
03508 
03509 #if GTEST_HAS_EXCEPTIONS
03510 
03511 // Adds an "exception thrown" fatal failure to the current test.
03512 static std::string FormatCxxExceptionMessage(const char* description,
03513                                              const char* location) {
03514   Message message;
03515   if (description != NULL) {
03516     message << "C++ exception with description \"" << description << "\"";
03517   } else {
03518     message << "Unknown C++ exception";
03519   }
03520   message << " thrown in " << location << ".";
03521 
03522   return message.GetString();
03523 }
03524 
03525 static std::string PrintTestPartResultToString(
03526     const TestPartResult& test_part_result);
03527 
03528 GoogleTestFailureException::GoogleTestFailureException(
03529     const TestPartResult& failure)
03530     : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
03531 
03532 #endif  // GTEST_HAS_EXCEPTIONS
03533 
03534 // We put these helper functions in the internal namespace as IBM's xlC
03535 // compiler rejects the code if they were declared static.
03536 
03537 // Runs the given method and handles SEH exceptions it throws, when
03538 // SEH is supported; returns the 0-value for type Result in case of an
03539 // SEH exception.  (Microsoft compilers cannot handle SEH and C++
03540 // exceptions in the same function.  Therefore, we provide a separate
03541 // wrapper function for handling SEH exceptions.)
03542 template <class T, typename Result>
03543 Result HandleSehExceptionsInMethodIfSupported(
03544     T* object, Result (T::*method)(), const char* location) {
03545 #if GTEST_HAS_SEH
03546   __try {
03547     return (object->*method)();
03548   } __except (internal::UnitTestOptions::GTestShouldProcessSEH(  // NOLINT
03549       GetExceptionCode())) {
03550     // We create the exception message on the heap because VC++ prohibits
03551     // creation of objects with destructors on stack in functions using __try
03552     // (see error C2712).
03553     std::string* exception_message = FormatSehExceptionMessage(
03554         GetExceptionCode(), location);
03555     internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
03556                                              *exception_message);
03557     delete exception_message;
03558     return static_cast<Result>(0);
03559   }
03560 #else
03561   (void)location;
03562   return (object->*method)();
03563 #endif  // GTEST_HAS_SEH
03564 }
03565 
03566 // Runs the given method and catches and reports C++ and/or SEH-style
03567 // exceptions, if they are supported; returns the 0-value for type
03568 // Result in case of an SEH exception.
03569 template <class T, typename Result>
03570 Result HandleExceptionsInMethodIfSupported(
03571     T* object, Result (T::*method)(), const char* location) {
03572   // NOTE: The user code can affect the way in which Google Test handles
03573   // exceptions by setting GTEST_FLAG(catch_exceptions), but only before
03574   // RUN_ALL_TESTS() starts. It is technically possible to check the flag
03575   // after the exception is caught and either report or re-throw the
03576   // exception based on the flag's value:
03577   //
03578   // try {
03579   //   // Perform the test method.
03580   // } catch (...) {
03581   //   if (GTEST_FLAG(catch_exceptions))
03582   //     // Report the exception as failure.
03583   //   else
03584   //     throw;  // Re-throws the original exception.
03585   // }
03586   //
03587   // However, the purpose of this flag is to allow the program to drop into
03588   // the debugger when the exception is thrown. On most platforms, once the
03589   // control enters the catch block, the exception origin information is
03590   // lost and the debugger will stop the program at the point of the
03591   // re-throw in this function -- instead of at the point of the original
03592   // throw statement in the code under test.  For this reason, we perform
03593   // the check early, sacrificing the ability to affect Google Test's
03594   // exception handling in the method where the exception is thrown.
03595   if (internal::GetUnitTestImpl()->catch_exceptions()) {
03596 #if GTEST_HAS_EXCEPTIONS
03597     try {
03598       return HandleSehExceptionsInMethodIfSupported(object, method, location);
03599     } catch (const internal::GoogleTestFailureException&) {  // NOLINT
03600       // This exception type can only be thrown by a failed Google
03601       // Test assertion with the intention of letting another testing
03602       // framework catch it.  Therefore we just re-throw it.
03603       throw;
03604     } catch (const std::exception& e) {  // NOLINT
03605       internal::ReportFailureInUnknownLocation(
03606           TestPartResult::kFatalFailure,
03607           FormatCxxExceptionMessage(e.what(), location));
03608     } catch (...) {  // NOLINT
03609       internal::ReportFailureInUnknownLocation(
03610           TestPartResult::kFatalFailure,
03611           FormatCxxExceptionMessage(NULL, location));
03612     }
03613     return static_cast<Result>(0);
03614 #else
03615     return HandleSehExceptionsInMethodIfSupported(object, method, location);
03616 #endif  // GTEST_HAS_EXCEPTIONS
03617   } else {
03618     return (object->*method)();
03619   }
03620 }
03621 
03622 }  // namespace internal
03623 
03624 // Runs the test and updates the test result.
03625 void Test::Run() {
03626   if (!HasSameFixtureClass()) return;
03627 
03628   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
03629   impl->os_stack_trace_getter()->UponLeavingGTest();
03630   internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()");
03631   // We will run the test only if SetUp() was successful.
03632   if (!HasFatalFailure()) {
03633     impl->os_stack_trace_getter()->UponLeavingGTest();
03634     internal::HandleExceptionsInMethodIfSupported(
03635         this, &Test::TestBody, "the test body");
03636   }
03637 
03638   // However, we want to clean up as much as possible.  Hence we will
03639   // always call TearDown(), even if SetUp() or the test body has
03640   // failed.
03641   impl->os_stack_trace_getter()->UponLeavingGTest();
03642   internal::HandleExceptionsInMethodIfSupported(
03643       this, &Test::TearDown, "TearDown()");
03644 }
03645 
03646 // Returns true iff the current test has a fatal failure.
03647 bool Test::HasFatalFailure() {
03648   return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
03649 }
03650 
03651 // Returns true iff the current test has a non-fatal failure.
03652 bool Test::HasNonfatalFailure() {
03653   return internal::GetUnitTestImpl()->current_test_result()->
03654       HasNonfatalFailure();
03655 }
03656 
03657 // class TestInfo
03658 
03659 // Constructs a TestInfo object. It assumes ownership of the test factory
03660 // object.
03661 TestInfo::TestInfo(const std::string& a_test_case_name,
03662                    const std::string& a_name,
03663                    const char* a_type_param,
03664                    const char* a_value_param,
03665                    internal::TypeId fixture_class_id,
03666                    internal::TestFactoryBase* factory)
03667     : test_case_name_(a_test_case_name),
03668       name_(a_name),
03669       type_param_(a_type_param ? new std::string(a_type_param) : NULL),
03670       value_param_(a_value_param ? new std::string(a_value_param) : NULL),
03671       fixture_class_id_(fixture_class_id),
03672       should_run_(false),
03673       is_disabled_(false),
03674       matches_filter_(false),
03675       factory_(factory),
03676       result_() {}
03677 
03678 // Destructs a TestInfo object.
03679 TestInfo::~TestInfo() { delete factory_; }
03680 
03681 namespace internal {
03682 
03683 // Creates a new TestInfo object and registers it with Google Test;
03684 // returns the created object.
03685 //
03686 // Arguments:
03687 //
03688 //   test_case_name:   name of the test case
03689 //   name:             name of the test
03690 //   type_param:       the name of the test's type parameter, or NULL if
03691 //                     this is not a typed or a type-parameterized test.
03692 //   value_param:      text representation of the test's value parameter,
03693 //                     or NULL if this is not a value-parameterized test.
03694 //   fixture_class_id: ID of the test fixture class
03695 //   set_up_tc:        pointer to the function that sets up the test case
03696 //   tear_down_tc:     pointer to the function that tears down the test case
03697 //   factory:          pointer to the factory that creates a test object.
03698 //                     The newly created TestInfo instance will assume
03699 //                     ownership of the factory object.
03700 TestInfo* MakeAndRegisterTestInfo(
03701     const char* test_case_name,
03702     const char* name,
03703     const char* type_param,
03704     const char* value_param,
03705     TypeId fixture_class_id,
03706     SetUpTestCaseFunc set_up_tc,
03707     TearDownTestCaseFunc tear_down_tc,
03708     TestFactoryBase* factory) {
03709   TestInfo* const test_info =
03710       new TestInfo(test_case_name, name, type_param, value_param,
03711                    fixture_class_id, factory);
03712   GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
03713   return test_info;
03714 }
03715 
03716 #if GTEST_HAS_PARAM_TEST
03717 void ReportInvalidTestCaseType(const char* test_case_name,
03718                                const char* file, int line) {
03719   Message errors;
03720   errors
03721       << "Attempted redefinition of test case " << test_case_name << ".\n"
03722       << "All tests in the same test case must use the same test fixture\n"
03723       << "class.  However, in test case " << test_case_name << ", you tried\n"
03724       << "to define a test using a fixture class different from the one\n"
03725       << "used earlier. This can happen if the two fixture classes are\n"
03726       << "from different namespaces and have the same name. You should\n"
03727       << "probably rename one of the classes to put the tests into different\n"
03728       << "test cases.";
03729 
03730   fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
03731           errors.GetString().c_str());
03732 }
03733 #endif  // GTEST_HAS_PARAM_TEST
03734 
03735 }  // namespace internal
03736 
03737 namespace {
03738 
03739 // A predicate that checks the test name of a TestInfo against a known
03740 // value.
03741 //
03742 // This is used for implementation of the TestCase class only.  We put
03743 // it in the anonymous namespace to prevent polluting the outer
03744 // namespace.
03745 //
03746 // TestNameIs is copyable.
03747 class TestNameIs {
03748  public:
03749   // Constructor.
03750   //
03751   // TestNameIs has NO default constructor.
03752   explicit TestNameIs(const char* name)
03753       : name_(name) {}
03754 
03755   // Returns true iff the test name of test_info matches name_.
03756   bool operator()(const TestInfo * test_info) const {
03757     return test_info && test_info->name() == name_;
03758   }
03759 
03760  private:
03761   std::string name_;
03762 };
03763 
03764 }  // namespace
03765 
03766 namespace internal {
03767 
03768 // This method expands all parameterized tests registered with macros TEST_P
03769 // and INSTANTIATE_TEST_CASE_P into regular tests and registers those.
03770 // This will be done just once during the program runtime.
03771 void UnitTestImpl::RegisterParameterizedTests() {
03772 #if GTEST_HAS_PARAM_TEST
03773   if (!parameterized_tests_registered_) {
03774     parameterized_test_registry_.RegisterTests();
03775     parameterized_tests_registered_ = true;
03776   }
03777 #endif
03778 }
03779 
03780 }  // namespace internal
03781 
03782 // Creates the test object, runs it, records its result, and then
03783 // deletes it.
03784 void TestInfo::Run() {
03785   if (!should_run_) return;
03786 
03787   // Tells UnitTest where to store test result.
03788   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
03789   impl->set_current_test_info(this);
03790 
03791   TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
03792 
03793   // Notifies the unit test event listeners that a test is about to start.
03794   repeater->OnTestStart(*this);
03795 
03796   const TimeInMillis start = internal::GetTimeInMillis();
03797 
03798   impl->os_stack_trace_getter()->UponLeavingGTest();
03799 
03800   // Creates the test object.
03801   Test* const test = internal::HandleExceptionsInMethodIfSupported(
03802       factory_, &internal::TestFactoryBase::CreateTest,
03803       "the test fixture's constructor");
03804 
03805   // Runs the test only if the test object was created and its
03806   // constructor didn't generate a fatal failure.
03807   if ((test != NULL) && !Test::HasFatalFailure()) {
03808     // This doesn't throw as all user code that can throw are wrapped into
03809     // exception handling code.
03810     test->Run();
03811   }
03812 
03813   // Deletes the test object.
03814   impl->os_stack_trace_getter()->UponLeavingGTest();
03815   internal::HandleExceptionsInMethodIfSupported(
03816       test, &Test::DeleteSelf_, "the test fixture's destructor");
03817 
03818   result_.set_elapsed_time(internal::GetTimeInMillis() - start);
03819 
03820   // Notifies the unit test event listener that a test has just finished.
03821   repeater->OnTestEnd(*this);
03822 
03823   // Tells UnitTest to stop associating assertion results to this
03824   // test.
03825   impl->set_current_test_info(NULL);
03826 }
03827 
03828 // class TestCase
03829 
03830 // Gets the number of successful tests in this test case.
03831 int TestCase::successful_test_count() const {
03832   return CountIf(test_info_list_, TestPassed);
03833 }
03834 
03835 // Gets the number of failed tests in this test case.
03836 int TestCase::failed_test_count() const {
03837   return CountIf(test_info_list_, TestFailed);
03838 }
03839 
03840 // Gets the number of disabled tests that will be reported in the XML report.
03841 int TestCase::reportable_disabled_test_count() const {
03842   return CountIf(test_info_list_, TestReportableDisabled);
03843 }
03844 
03845 // Gets the number of disabled tests in this test case.
03846 int TestCase::disabled_test_count() const {
03847   return CountIf(test_info_list_, TestDisabled);
03848 }
03849 
03850 // Gets the number of tests to be printed in the XML report.
03851 int TestCase::reportable_test_count() const {
03852   return CountIf(test_info_list_, TestReportable);
03853 }
03854 
03855 // Get the number of tests in this test case that should run.
03856 int TestCase::test_to_run_count() const {
03857   return CountIf(test_info_list_, ShouldRunTest);
03858 }
03859 
03860 // Gets the number of all tests.
03861 int TestCase::total_test_count() const {
03862   return static_cast<int>(test_info_list_.size());
03863 }
03864 
03865 // Creates a TestCase with the given name.
03866 //
03867 // Arguments:
03868 //
03869 //   name:         name of the test case
03870 //   a_type_param: the name of the test case's type parameter, or NULL if
03871 //                 this is not a typed or a type-parameterized test case.
03872 //   set_up_tc:    pointer to the function that sets up the test case
03873 //   tear_down_tc: pointer to the function that tears down the test case
03874 TestCase::TestCase(const char* a_name, const char* a_type_param,
03875                    Test::SetUpTestCaseFunc set_up_tc,
03876                    Test::TearDownTestCaseFunc tear_down_tc)
03877     : name_(a_name),
03878       type_param_(a_type_param ? new std::string(a_type_param) : NULL),
03879       set_up_tc_(set_up_tc),
03880       tear_down_tc_(tear_down_tc),
03881       should_run_(false),
03882       elapsed_time_(0) {
03883 }
03884 
03885 // Destructor of TestCase.
03886 TestCase::~TestCase() {
03887   // Deletes every Test in the collection.
03888   ForEach(test_info_list_, internal::Delete<TestInfo>);
03889 }
03890 
03891 // Returns the i-th test among all the tests. i can range from 0 to
03892 // total_test_count() - 1. If i is not in that range, returns NULL.
03893 const TestInfo* TestCase::GetTestInfo(int i) const {
03894   const int index = GetElementOr(test_indices_, i, -1);
03895   return index < 0 ? NULL : test_info_list_[index];
03896 }
03897 
03898 // Returns the i-th test among all the tests. i can range from 0 to
03899 // total_test_count() - 1. If i is not in that range, returns NULL.
03900 TestInfo* TestCase::GetMutableTestInfo(int i) {
03901   const int index = GetElementOr(test_indices_, i, -1);
03902   return index < 0 ? NULL : test_info_list_[index];
03903 }
03904 
03905 // Adds a test to this test case.  Will delete the test upon
03906 // destruction of the TestCase object.
03907 void TestCase::AddTestInfo(TestInfo * test_info) {
03908   test_info_list_.push_back(test_info);
03909   test_indices_.push_back(static_cast<int>(test_indices_.size()));
03910 }
03911 
03912 // Runs every test in this TestCase.
03913 void TestCase::Run() {
03914   if (!should_run_) return;
03915 
03916   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
03917   impl->set_current_test_case(this);
03918 
03919   TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
03920 
03921   repeater->OnTestCaseStart(*this);
03922   impl->os_stack_trace_getter()->UponLeavingGTest();
03923   internal::HandleExceptionsInMethodIfSupported(
03924       this, &TestCase::RunSetUpTestCase, "SetUpTestCase()");
03925 
03926   const internal::TimeInMillis start = internal::GetTimeInMillis();
03927   for (int i = 0; i < total_test_count(); i++) {
03928     GetMutableTestInfo(i)->Run();
03929   }
03930   elapsed_time_ = internal::GetTimeInMillis() - start;
03931 
03932   impl->os_stack_trace_getter()->UponLeavingGTest();
03933   internal::HandleExceptionsInMethodIfSupported(
03934       this, &TestCase::RunTearDownTestCase, "TearDownTestCase()");
03935 
03936   repeater->OnTestCaseEnd(*this);
03937   impl->set_current_test_case(NULL);
03938 }
03939 
03940 // Clears the results of all tests in this test case.
03941 void TestCase::ClearResult() {
03942   ad_hoc_test_result_.Clear();
03943   ForEach(test_info_list_, TestInfo::ClearTestResult);
03944 }
03945 
03946 // Shuffles the tests in this test case.
03947 void TestCase::ShuffleTests(internal::Random* random) {
03948   Shuffle(random, &test_indices_);
03949 }
03950 
03951 // Restores the test order to before the first shuffle.
03952 void TestCase::UnshuffleTests() {
03953   for (size_t i = 0; i < test_indices_.size(); i++) {
03954     test_indices_[i] = static_cast<int>(i);
03955   }
03956 }
03957 
03958 // Formats a countable noun.  Depending on its quantity, either the
03959 // singular form or the plural form is used. e.g.
03960 //
03961 // FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
03962 // FormatCountableNoun(5, "book", "books") returns "5 books".
03963 static std::string FormatCountableNoun(int count,
03964                                        const char * singular_form,
03965                                        const char * plural_form) {
03966   return internal::StreamableToString(count) + " " +
03967       (count == 1 ? singular_form : plural_form);
03968 }
03969 
03970 // Formats the count of tests.
03971 static std::string FormatTestCount(int test_count) {
03972   return FormatCountableNoun(test_count, "test", "tests");
03973 }
03974 
03975 // Formats the count of test cases.
03976 static std::string FormatTestCaseCount(int test_case_count) {
03977   return FormatCountableNoun(test_case_count, "test case", "test cases");
03978 }
03979 
03980 // Converts a TestPartResult::Type enum to human-friendly string
03981 // representation.  Both kNonFatalFailure and kFatalFailure are translated
03982 // to "Failure", as the user usually doesn't care about the difference
03983 // between the two when viewing the test result.
03984 static const char * TestPartResultTypeToString(TestPartResult::Type type) {
03985   switch (type) {
03986     case TestPartResult::kSuccess:
03987       return "Success";
03988 
03989     case TestPartResult::kNonFatalFailure:
03990     case TestPartResult::kFatalFailure:
03991 #ifdef _MSC_VER
03992       return "error: ";
03993 #else
03994       return "Failure\n";
03995 #endif
03996     default:
03997       return "Unknown result type";
03998   }
03999 }
04000 
04001 namespace internal {
04002 
04003 // Prints a TestPartResult to an std::string.
04004 static std::string PrintTestPartResultToString(
04005     const TestPartResult& test_part_result) {
04006   return (Message()
04007           << internal::FormatFileLocation(test_part_result.file_name(),
04008                                           test_part_result.line_number())
04009           << " " << TestPartResultTypeToString(test_part_result.type())
04010           << test_part_result.message()).GetString();
04011 }
04012 
04013 // Prints a TestPartResult.
04014 static void PrintTestPartResult(const TestPartResult& test_part_result) {
04015   const std::string& result =
04016       PrintTestPartResultToString(test_part_result);
04017   printf("%s\n", result.c_str());
04018   fflush(stdout);
04019   // If the test program runs in Visual Studio or a debugger, the
04020   // following statements add the test part result message to the Output
04021   // window such that the user can double-click on it to jump to the
04022   // corresponding source code location; otherwise they do nothing.
04023 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
04024   // We don't call OutputDebugString*() on Windows Mobile, as printing
04025   // to stdout is done by OutputDebugString() there already - we don't
04026   // want the same message printed twice.
04027   ::OutputDebugStringA(result.c_str());
04028   ::OutputDebugStringA("\n");
04029 #endif
04030 }
04031 
04032 // class PrettyUnitTestResultPrinter
04033 
04034 enum GTestColor {
04035   COLOR_DEFAULT,
04036   COLOR_RED,
04037   COLOR_GREEN,
04038   COLOR_YELLOW
04039 };
04040 
04041 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
04042 
04043 // Returns the character attribute for the given color.
04044 WORD GetColorAttribute(GTestColor color) {
04045   switch (color) {
04046     case COLOR_RED:    return FOREGROUND_RED;
04047     case COLOR_GREEN:  return FOREGROUND_GREEN;
04048     case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
04049     default:           return 0;
04050   }
04051 }
04052 
04053 #else
04054 
04055 // Returns the ANSI color code for the given color.  COLOR_DEFAULT is
04056 // an invalid input.
04057 const char* GetAnsiColorCode(GTestColor color) {
04058   switch (color) {
04059     case COLOR_RED:     return "1";
04060     case COLOR_GREEN:   return "2";
04061     case COLOR_YELLOW:  return "3";
04062     default:            return NULL;
04063   };
04064 }
04065 
04066 #endif  // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
04067 
04068 // Returns true iff Google Test should use colors in the output.
04069 bool ShouldUseColor(bool stdout_is_tty) {
04070   const char* const gtest_color = GTEST_FLAG(color).c_str();
04071 
04072   if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
04073 #if GTEST_OS_WINDOWS
04074     // On Windows the TERM variable is usually not set, but the
04075     // console there does support colors.
04076     return stdout_is_tty;
04077 #else
04078     // On non-Windows platforms, we rely on the TERM variable.
04079     const char* const term = posix::GetEnv("TERM");
04080     const bool term_supports_color =
04081         String::CStringEquals(term, "xterm") ||
04082         String::CStringEquals(term, "xterm-color") ||
04083         String::CStringEquals(term, "xterm-256color") ||
04084         String::CStringEquals(term, "screen") ||
04085         String::CStringEquals(term, "screen-256color") ||
04086         String::CStringEquals(term, "linux") ||
04087         String::CStringEquals(term, "cygwin");
04088     return stdout_is_tty && term_supports_color;
04089 #endif  // GTEST_OS_WINDOWS
04090   }
04091 
04092   return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
04093       String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
04094       String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
04095       String::CStringEquals(gtest_color, "1");
04096   // We take "yes", "true", "t", and "1" as meaning "yes".  If the
04097   // value is neither one of these nor "auto", we treat it as "no" to
04098   // be conservative.
04099 }
04100 
04101 // Helpers for printing colored strings to stdout. Note that on Windows, we
04102 // cannot simply emit special characters and have the terminal change colors.
04103 // This routine must actually emit the characters rather than return a string
04104 // that would be colored when printed, as can be done on Linux.
04105 void ColoredPrintf(GTestColor color, const char* fmt, ...) {
04106   va_list args;
04107   va_start(args, fmt);
04108 
04109 #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS || GTEST_OS_IOS
04110   const bool use_color = false;
04111 #else
04112   static const bool in_color_mode =
04113       ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
04114   const bool use_color = in_color_mode && (color != COLOR_DEFAULT);
04115 #endif  // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
04116   // The '!= 0' comparison is necessary to satisfy MSVC 7.1.
04117 
04118   if (!use_color) {
04119     vprintf(fmt, args);
04120     va_end(args);
04121     return;
04122   }
04123 
04124 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
04125   const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
04126 
04127   // Gets the current text color.
04128   CONSOLE_SCREEN_BUFFER_INFO buffer_info;
04129   GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
04130   const WORD old_color_attrs = buffer_info.wAttributes;
04131 
04132   // We need to flush the stream buffers into the console before each
04133   // SetConsoleTextAttribute call lest it affect the text that is already
04134   // printed but has not yet reached the console.
04135   fflush(stdout);
04136   SetConsoleTextAttribute(stdout_handle,
04137                           GetColorAttribute(color) | FOREGROUND_INTENSITY);
04138   vprintf(fmt, args);
04139 
04140   fflush(stdout);
04141   // Restores the text color.
04142   SetConsoleTextAttribute(stdout_handle, old_color_attrs);
04143 #else
04144   printf("\033[0;3%sm", GetAnsiColorCode(color));
04145   vprintf(fmt, args);
04146   printf("\033[m");  // Resets the terminal to default.
04147 #endif  // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
04148   va_end(args);
04149 }
04150 
04151 // Text printed in Google Test's text output and --gunit_list_tests
04152 // output to label the type parameter and value parameter for a test.
04153 static const char kTypeParamLabel[] = "TypeParam";
04154 static const char kValueParamLabel[] = "GetParam()";
04155 
04156 void PrintFullTestCommentIfPresent(const TestInfo& test_info) {
04157   const char* const type_param = test_info.type_param();
04158   const char* const value_param = test_info.value_param();
04159 
04160   if (type_param != NULL || value_param != NULL) {
04161     printf(", where ");
04162     if (type_param != NULL) {
04163       printf("%s = %s", kTypeParamLabel, type_param);
04164       if (value_param != NULL)
04165         printf(" and ");
04166     }
04167     if (value_param != NULL) {
04168       printf("%s = %s", kValueParamLabel, value_param);
04169     }
04170   }
04171 }
04172 
04173 // This class implements the TestEventListener interface.
04174 //
04175 // Class PrettyUnitTestResultPrinter is copyable.
04176 class PrettyUnitTestResultPrinter : public TestEventListener {
04177  public:
04178   PrettyUnitTestResultPrinter() {}
04179   static void PrintTestName(const char * test_case, const char * test) {
04180     printf("%s.%s", test_case, test);
04181   }
04182 
04183   // The following methods override what's in the TestEventListener class.
04184   virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {}
04185   virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
04186   virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
04187   virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {}
04188   virtual void OnTestCaseStart(const TestCase& test_case);
04189   virtual void OnTestStart(const TestInfo& test_info);
04190   virtual void OnTestPartResult(const TestPartResult& result);
04191   virtual void OnTestEnd(const TestInfo& test_info);
04192   virtual void OnTestCaseEnd(const TestCase& test_case);
04193   virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
04194   virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {}
04195   virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
04196   virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {}
04197 
04198  private:
04199   static void PrintFailedTests(const UnitTest& unit_test);
04200 };
04201 
04202   // Fired before each iteration of tests starts.
04203 void PrettyUnitTestResultPrinter::OnTestIterationStart(
04204     const UnitTest& unit_test, int iteration) {
04205   if (GTEST_FLAG(repeat) != 1)
04206     printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
04207 
04208   const char* const filter = GTEST_FLAG(filter).c_str();
04209 
04210   // Prints the filter if it's not *.  This reminds the user that some
04211   // tests may be skipped.
04212   if (!String::CStringEquals(filter, kUniversalFilter)) {
04213     ColoredPrintf(COLOR_YELLOW,
04214                   "Note: %s filter = %s\n", GTEST_NAME_, filter);
04215   }
04216 
04217   if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
04218     const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
04219     ColoredPrintf(COLOR_YELLOW,
04220                   "Note: This is test shard %d of %s.\n",
04221                   static_cast<int>(shard_index) + 1,
04222                   internal::posix::GetEnv(kTestTotalShards));
04223   }
04224 
04225   if (GTEST_FLAG(shuffle)) {
04226     ColoredPrintf(COLOR_YELLOW,
04227                   "Note: Randomizing tests' orders with a seed of %d .\n",
04228                   unit_test.random_seed());
04229   }
04230 
04231   ColoredPrintf(COLOR_GREEN,  "[==========] ");
04232   printf("Running %s from %s.\n",
04233          FormatTestCount(unit_test.test_to_run_count()).c_str(),
04234          FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
04235   fflush(stdout);
04236 }
04237 
04238 void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
04239     const UnitTest& /*unit_test*/) {
04240   ColoredPrintf(COLOR_GREEN,  "[----------] ");
04241   printf("Global test environment set-up.\n");
04242   fflush(stdout);
04243 }
04244 
04245 void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {
04246   const std::string counts =
04247       FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
04248   ColoredPrintf(COLOR_GREEN, "[----------] ");
04249   printf("%s from %s", counts.c_str(), test_case.name());
04250   if (test_case.type_param() == NULL) {
04251     printf("\n");
04252   } else {
04253     printf(", where %s = %s\n", kTypeParamLabel, test_case.type_param());
04254   }
04255   fflush(stdout);
04256 }
04257 
04258 void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
04259   ColoredPrintf(COLOR_GREEN,  "[ RUN      ] ");
04260   PrintTestName(test_info.test_case_name(), test_info.name());
04261   printf("\n");
04262   fflush(stdout);
04263 }
04264 
04265 // Called after an assertion failure.
04266 void PrettyUnitTestResultPrinter::OnTestPartResult(
04267     const TestPartResult& result) {
04268   // If the test part succeeded, we don't need to do anything.
04269   if (result.type() == TestPartResult::kSuccess)
04270     return;
04271 
04272   // Print failure message from the assertion (e.g. expected this and got that).
04273   PrintTestPartResult(result);
04274   fflush(stdout);
04275 }
04276 
04277 void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
04278   if (test_info.result()->Passed()) {
04279     ColoredPrintf(COLOR_GREEN, "[       OK ] ");
04280   } else {
04281     ColoredPrintf(COLOR_RED, "[  FAILED  ] ");
04282   }
04283   PrintTestName(test_info.test_case_name(), test_info.name());
04284   if (test_info.result()->Failed())
04285     PrintFullTestCommentIfPresent(test_info);
04286 
04287   if (GTEST_FLAG(print_time)) {
04288     printf(" (%s ms)\n", internal::StreamableToString(
04289            test_info.result()->elapsed_time()).c_str());
04290   } else {
04291     printf("\n");
04292   }
04293   fflush(stdout);
04294 }
04295 
04296 void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {
04297   if (!GTEST_FLAG(print_time)) return;
04298 
04299   const std::string counts =
04300       FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
04301   ColoredPrintf(COLOR_GREEN, "[----------] ");
04302   printf("%s from %s (%s ms total)\n\n",
04303          counts.c_str(), test_case.name(),
04304          internal::StreamableToString(test_case.elapsed_time()).c_str());
04305   fflush(stdout);
04306 }
04307 
04308 void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
04309     const UnitTest& /*unit_test*/) {
04310   ColoredPrintf(COLOR_GREEN,  "[----------] ");
04311   printf("Global test environment tear-down\n");
04312   fflush(stdout);
04313 }
04314 
04315 // Internal helper for printing the list of failed tests.
04316 void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
04317   const int failed_test_count = unit_test.failed_test_count();
04318   if (failed_test_count == 0) {
04319     return;
04320   }
04321 
04322   for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
04323     const TestCase& test_case = *unit_test.GetTestCase(i);
04324     if (!test_case.should_run() || (test_case.failed_test_count() == 0)) {
04325       continue;
04326     }
04327     for (int j = 0; j < test_case.total_test_count(); ++j) {
04328       const TestInfo& test_info = *test_case.GetTestInfo(j);
04329       if (!test_info.should_run() || test_info.result()->Passed()) {
04330         continue;
04331       }
04332       ColoredPrintf(COLOR_RED, "[  FAILED  ] ");
04333       printf("%s.%s", test_case.name(), test_info.name());
04334       PrintFullTestCommentIfPresent(test_info);
04335       printf("\n");
04336     }
04337   }
04338 }
04339 
04340 void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
04341                                                      int /*iteration*/) {
04342   ColoredPrintf(COLOR_GREEN,  "[==========] ");
04343   printf("%s from %s ran.",
04344          FormatTestCount(unit_test.test_to_run_count()).c_str(),
04345          FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
04346   if (GTEST_FLAG(print_time)) {
04347     printf(" (%s ms total)",
04348            internal::StreamableToString(unit_test.elapsed_time()).c_str());
04349   }
04350   printf("\n");
04351   ColoredPrintf(COLOR_GREEN,  "[  PASSED  ] ");
04352   printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
04353 
04354   int num_failures = unit_test.failed_test_count();
04355   if (!unit_test.Passed()) {
04356     const int failed_test_count = unit_test.failed_test_count();
04357     ColoredPrintf(COLOR_RED,  "[  FAILED  ] ");
04358     printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
04359     PrintFailedTests(unit_test);
04360     printf("\n%2d FAILED %s\n", num_failures,
04361                         num_failures == 1 ? "TEST" : "TESTS");
04362   }
04363 
04364   int num_disabled = unit_test.reportable_disabled_test_count();
04365   if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
04366     if (!num_failures) {
04367       printf("\n");  // Add a spacer if no FAILURE banner is displayed.
04368     }
04369     ColoredPrintf(COLOR_YELLOW,
04370                   "  YOU HAVE %d DISABLED %s\n\n",
04371                   num_disabled,
04372                   num_disabled == 1 ? "TEST" : "TESTS");
04373   }
04374   // Ensure that Google Test output is printed before, e.g., heapchecker output.
04375   fflush(stdout);
04376 }
04377 
04378 // End PrettyUnitTestResultPrinter
04379 
04380 // class TestEventRepeater
04381 //
04382 // This class forwards events to other event listeners.
04383 class TestEventRepeater : public TestEventListener {
04384  public:
04385   TestEventRepeater() : forwarding_enabled_(true) {}
04386   virtual ~TestEventRepeater();
04387   void Append(TestEventListener *listener);
04388   TestEventListener* Release(TestEventListener* listener);
04389 
04390   // Controls whether events will be forwarded to listeners_. Set to false
04391   // in death test child processes.
04392   bool forwarding_enabled() const { return forwarding_enabled_; }
04393   void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }
04394 
04395   virtual void OnTestProgramStart(const UnitTest& unit_test);
04396   virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
04397   virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
04398   virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test);
04399   virtual void OnTestCaseStart(const TestCase& test_case);
04400   virtual void OnTestStart(const TestInfo& test_info);
04401   virtual void OnTestPartResult(const TestPartResult& result);
04402   virtual void OnTestEnd(const TestInfo& test_info);
04403   virtual void OnTestCaseEnd(const TestCase& test_case);
04404   virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
04405   virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test);
04406   virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
04407   virtual void OnTestProgramEnd(const UnitTest& unit_test);
04408 
04409  private:
04410   // Controls whether events will be forwarded to listeners_. Set to false
04411   // in death test child processes.
04412   bool forwarding_enabled_;
04413   // The list of listeners that receive events.
04414   std::vector<TestEventListener*> listeners_;
04415 
04416   GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater);
04417 };
04418 
04419 TestEventRepeater::~TestEventRepeater() {
04420   ForEach(listeners_, Delete<TestEventListener>);
04421 }
04422 
04423 void TestEventRepeater::Append(TestEventListener *listener) {
04424   listeners_.push_back(listener);
04425 }
04426 
04427 // TODO(vladl@google.com): Factor the search functionality into Vector::Find.
04428 TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {
04429   for (size_t i = 0; i < listeners_.size(); ++i) {
04430     if (listeners_[i] == listener) {
04431       listeners_.erase(listeners_.begin() + i);
04432       return listener;
04433     }
04434   }
04435 
04436   return NULL;
04437 }
04438 
04439 // Since most methods are very similar, use macros to reduce boilerplate.
04440 // This defines a member that forwards the call to all listeners.
04441 #define GTEST_REPEATER_METHOD_(Name, Type) \
04442 void TestEventRepeater::Name(const Type& parameter) { \
04443   if (forwarding_enabled_) { \
04444     for (size_t i = 0; i < listeners_.size(); i++) { \
04445       listeners_[i]->Name(parameter); \
04446     } \
04447   } \
04448 }
04449 // This defines a member that forwards the call to all listeners in reverse
04450 // order.
04451 #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
04452 void TestEventRepeater::Name(const Type& parameter) { \
04453   if (forwarding_enabled_) { \
04454     for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \
04455       listeners_[i]->Name(parameter); \
04456     } \
04457   } \
04458 }
04459 
04460 GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)
04461 GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)
04462 GTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase)
04463 GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
04464 GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)
04465 GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)
04466 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)
04467 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)
04468 GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)
04469 GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestCase)
04470 GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)
04471 
04472 #undef GTEST_REPEATER_METHOD_
04473 #undef GTEST_REVERSE_REPEATER_METHOD_
04474 
04475 void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,
04476                                              int iteration) {
04477   if (forwarding_enabled_) {
04478     for (size_t i = 0; i < listeners_.size(); i++) {
04479       listeners_[i]->OnTestIterationStart(unit_test, iteration);
04480     }
04481   }
04482 }
04483 
04484 void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,
04485                                            int iteration) {
04486   if (forwarding_enabled_) {
04487     for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) {
04488       listeners_[i]->OnTestIterationEnd(unit_test, iteration);
04489     }
04490   }
04491 }
04492 
04493 // End TestEventRepeater
04494 
04495 // This class generates an XML output file.
04496 class XmlUnitTestResultPrinter : public EmptyTestEventListener {
04497  public:
04498   explicit XmlUnitTestResultPrinter(const char* output_file);
04499 
04500   virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
04501 
04502  private:
04503   // Is c a whitespace character that is normalized to a space character
04504   // when it appears in an XML attribute value?
04505   static bool IsNormalizableWhitespace(char c) {
04506     return c == 0x9 || c == 0xA || c == 0xD;
04507   }
04508 
04509   // May c appear in a well-formed XML document?
04510   static bool IsValidXmlCharacter(char c) {
04511     return IsNormalizableWhitespace(c) || c >= 0x20;
04512   }
04513 
04514   // Returns an XML-escaped copy of the input string str.  If
04515   // is_attribute is true, the text is meant to appear as an attribute
04516   // value, and normalizable whitespace is preserved by replacing it
04517   // with character references.
04518   static std::string EscapeXml(const std::string& str, bool is_attribute);
04519 
04520   // Returns the given string with all characters invalid in XML removed.
04521   static std::string RemoveInvalidXmlCharacters(const std::string& str);
04522 
04523   // Convenience wrapper around EscapeXml when str is an attribute value.
04524   static std::string EscapeXmlAttribute(const std::string& str) {
04525     return EscapeXml(str, true);
04526   }
04527 
04528   // Convenience wrapper around EscapeXml when str is not an attribute value.
04529   static std::string EscapeXmlText(const char* str) {
04530     return EscapeXml(str, false);
04531   }
04532 
04533   // Verifies that the given attribute belongs to the given element and
04534   // streams the attribute as XML.
04535   static void OutputXmlAttribute(std::ostream* stream,
04536                                  const std::string& element_name,
04537                                  const std::string& name,
04538                                  const std::string& value);
04539 
04540   // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
04541   static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
04542 
04543   // Streams an XML representation of a TestInfo object.
04544   static void OutputXmlTestInfo(::std::ostream* stream,
04545                                 const char* test_case_name,
04546                                 const TestInfo& test_info);
04547 
04548   // Prints an XML representation of a TestCase object
04549   static void PrintXmlTestCase(::std::ostream* stream,
04550                                const TestCase& test_case);
04551 
04552   // Prints an XML summary of unit_test to output stream out.
04553   static void PrintXmlUnitTest(::std::ostream* stream,
04554                                const UnitTest& unit_test);
04555 
04556   // Produces a string representing the test properties in a result as space
04557   // delimited XML attributes based on the property key="value" pairs.
04558   // When the std::string is not empty, it includes a space at the beginning,
04559   // to delimit this attribute from prior attributes.
04560   static std::string TestPropertiesAsXmlAttributes(const TestResult& result);
04561 
04562   // The output file.
04563   const std::string output_file_;
04564 
04565   GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);
04566 };
04567 
04568 // Creates a new XmlUnitTestResultPrinter.
04569 XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
04570     : output_file_(output_file) {
04571   if (output_file_.c_str() == NULL || output_file_.empty()) {
04572     fprintf(stderr, "XML output file may not be null\n");
04573     fflush(stderr);
04574     exit(EXIT_FAILURE);
04575   }
04576 }
04577 
04578 // Called after the unit test ends.
04579 void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
04580                                                   int /*iteration*/) {
04581   FILE* xmlout = NULL;
04582   FilePath output_file(output_file_);
04583   FilePath output_dir(output_file.RemoveFileName());
04584 
04585   if (output_dir.CreateDirectoriesRecursively()) {
04586     xmlout = posix::FOpen(output_file_.c_str(), "w");
04587   }
04588   if (xmlout == NULL) {
04589     // TODO(wan): report the reason of the failure.
04590     //
04591     // We don't do it for now as:
04592     //
04593     //   1. There is no urgent need for it.
04594     //   2. It's a bit involved to make the errno variable thread-safe on
04595     //      all three operating systems (Linux, Windows, and Mac OS).
04596     //   3. To interpret the meaning of errno in a thread-safe way,
04597     //      we need the strerror_r() function, which is not available on
04598     //      Windows.
04599     fprintf(stderr,
04600             "Unable to open file \"%s\"\n",
04601             output_file_.c_str());
04602     fflush(stderr);
04603     exit(EXIT_FAILURE);
04604   }
04605   std::stringstream stream;
04606   PrintXmlUnitTest(&stream, unit_test);
04607   fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
04608   fclose(xmlout);
04609 }
04610 
04611 // Returns an XML-escaped copy of the input string str.  If is_attribute
04612 // is true, the text is meant to appear as an attribute value, and
04613 // normalizable whitespace is preserved by replacing it with character
04614 // references.
04615 //
04616 // Invalid XML characters in str, if any, are stripped from the output.
04617 // It is expected that most, if not all, of the text processed by this
04618 // module will consist of ordinary English text.
04619 // If this module is ever modified to produce version 1.1 XML output,
04620 // most invalid characters can be retained using character references.
04621 // TODO(wan): It might be nice to have a minimally invasive, human-readable
04622 // escaping scheme for invalid characters, rather than dropping them.
04623 std::string XmlUnitTestResultPrinter::EscapeXml(
04624     const std::string& str, bool is_attribute) {
04625   Message m;
04626 
04627   for (size_t i = 0; i < str.size(); ++i) {
04628     const char ch = str[i];
04629     switch (ch) {
04630       case '<':
04631         m << "&lt;";
04632         break;
04633       case '>':
04634         m << "&gt;";
04635         break;
04636       case '&':
04637         m << "&amp;";
04638         break;
04639       case '\'':
04640         if (is_attribute)
04641           m << "&apos;";
04642         else
04643           m << '\'';
04644         break;
04645       case '"':
04646         if (is_attribute)
04647           m << "&quot;";
04648         else
04649           m << '"';
04650         break;
04651       default:
04652         if (IsValidXmlCharacter(ch)) {
04653           if (is_attribute && IsNormalizableWhitespace(ch))
04654             m << "&#x" << String::FormatByte(static_cast<unsigned char>(ch))
04655               << ";";
04656           else
04657             m << ch;
04658         }
04659         break;
04660     }
04661   }
04662 
04663   return m.GetString();
04664 }
04665 
04666 // Returns the given string with all characters invalid in XML removed.
04667 // Currently invalid characters are dropped from the string. An
04668 // alternative is to replace them with certain characters such as . or ?.
04669 std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(
04670     const std::string& str) {
04671   std::string output;
04672   output.reserve(str.size());
04673   for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
04674     if (IsValidXmlCharacter(*it))
04675       output.push_back(*it);
04676 
04677   return output;
04678 }
04679 
04680 // The following routines generate an XML representation of a UnitTest
04681 // object.
04682 //
04683 // This is how Google Test concepts map to the DTD:
04684 //
04685 // <testsuites name="AllTests">        <-- corresponds to a UnitTest object
04686 //   <testsuite name="testcase-name">  <-- corresponds to a TestCase object
04687 //     <testcase name="test-name">     <-- corresponds to a TestInfo object
04688 //       <failure message="...">...</failure>
04689 //       <failure message="...">...</failure>
04690 //       <failure message="...">...</failure>
04691 //                                     <-- individual assertion failures
04692 //     </testcase>
04693 //   </testsuite>
04694 // </testsuites>
04695 
04696 // Formats the given time in milliseconds as seconds.
04697 std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {
04698   ::std::stringstream ss;
04699   ss << ms/1000.0;
04700   return ss.str();
04701 }
04702 
04703 // Converts the given epoch time in milliseconds to a date string in the ISO
04704 // 8601 format, without the timezone information.
04705 std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) {
04706   // Using non-reentrant version as localtime_r is not portable.
04707   time_t seconds = static_cast<time_t>(ms / 1000);
04708 #ifdef _MSC_VER
04709 # pragma warning(push)          // Saves the current warning state.
04710 # pragma warning(disable:4996)  // Temporarily disables warning 4996
04711                                 // (function or variable may be unsafe).
04712   const struct tm* const time_struct = localtime(&seconds);  // NOLINT
04713 # pragma warning(pop)           // Restores the warning state again.
04714 #else
04715   const struct tm* const time_struct = localtime(&seconds);  // NOLINT
04716 #endif
04717   if (time_struct == NULL)
04718     return "";  // Invalid ms value
04719 
04720   // YYYY-MM-DDThh:mm:ss
04721   return StreamableToString(time_struct->tm_year + 1900) + "-" +
04722       String::FormatIntWidth2(time_struct->tm_mon + 1) + "-" +
04723       String::FormatIntWidth2(time_struct->tm_mday) + "T" +
04724       String::FormatIntWidth2(time_struct->tm_hour) + ":" +
04725       String::FormatIntWidth2(time_struct->tm_min) + ":" +
04726       String::FormatIntWidth2(time_struct->tm_sec);
04727 }
04728 
04729 // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
04730 void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
04731                                                      const char* data) {
04732   const char* segment = data;
04733   *stream << "<![CDATA[";
04734   for (;;) {
04735     const char* const next_segment = strstr(segment, "]]>");
04736     if (next_segment != NULL) {
04737       stream->write(
04738           segment, static_cast<std::streamsize>(next_segment - segment));
04739       *stream << "]]>]]&gt;<![CDATA[";
04740       segment = next_segment + strlen("]]>");
04741     } else {
04742       *stream << segment;
04743       break;
04744     }
04745   }
04746   *stream << "]]>";
04747 }
04748 
04749 void XmlUnitTestResultPrinter::OutputXmlAttribute(
04750     std::ostream* stream,
04751     const std::string& element_name,
04752     const std::string& name,
04753     const std::string& value) {
04754   const std::vector<std::string>& allowed_names =
04755       GetReservedAttributesForElement(element_name);
04756 
04757   GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
04758                    allowed_names.end())
04759       << "Attribute " << name << " is not allowed for element <" << element_name
04760       << ">.";
04761 
04762   *stream << " " << name << "=\"" << EscapeXmlAttribute(value) << "\"";
04763 }
04764 
04765 // Prints an XML representation of a TestInfo object.
04766 // TODO(wan): There is also value in printing properties with the plain printer.
04767 void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
04768                                                  const char* test_case_name,
04769                                                  const TestInfo& test_info) {
04770   const TestResult& result = *test_info.result();
04771   const std::string kTestcase = "testcase";
04772 
04773   *stream << "    <testcase";
04774   OutputXmlAttribute(stream, kTestcase, "name", test_info.name());
04775 
04776   if (test_info.value_param() != NULL) {
04777     OutputXmlAttribute(stream, kTestcase, "value_param",
04778                        test_info.value_param());
04779   }
04780   if (test_info.type_param() != NULL) {
04781     OutputXmlAttribute(stream, kTestcase, "type_param", test_info.type_param());
04782   }
04783 
04784   OutputXmlAttribute(stream, kTestcase, "status",
04785                      test_info.should_run() ? "run" : "notrun");
04786   OutputXmlAttribute(stream, kTestcase, "time",
04787                      FormatTimeInMillisAsSeconds(result.elapsed_time()));
04788   OutputXmlAttribute(stream, kTestcase, "classname", test_case_name);
04789   *stream << TestPropertiesAsXmlAttributes(result);
04790 
04791   int failures = 0;
04792   for (int i = 0; i < result.total_part_count(); ++i) {
04793     const TestPartResult& part = result.GetTestPartResult(i);
04794     if (part.failed()) {
04795       if (++failures == 1) {
04796         *stream << ">\n";
04797       }
04798       const string location = internal::FormatCompilerIndependentFileLocation(
04799           part.file_name(), part.line_number());
04800       const string summary = location + "\n" + part.summary();
04801       *stream << "      <failure message=\""
04802               << EscapeXmlAttribute(summary.c_str())
04803               << "\" type=\"\">";
04804       const string detail = location + "\n" + part.message();
04805       OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
04806       *stream << "</failure>\n";
04807     }
04808   }
04809 
04810   if (failures == 0)
04811     *stream << " />\n";
04812   else
04813     *stream << "    </testcase>\n";
04814 }
04815 
04816 // Prints an XML representation of a TestCase object
04817 void XmlUnitTestResultPrinter::PrintXmlTestCase(std::ostream* stream,
04818                                                 const TestCase& test_case) {
04819   const std::string kTestsuite = "testsuite";
04820   *stream << "  <" << kTestsuite;
04821   OutputXmlAttribute(stream, kTestsuite, "name", test_case.name());
04822   OutputXmlAttribute(stream, kTestsuite, "tests",
04823                      StreamableToString(test_case.reportable_test_count()));
04824   OutputXmlAttribute(stream, kTestsuite, "failures",
04825                      StreamableToString(test_case.failed_test_count()));
04826   OutputXmlAttribute(
04827       stream, kTestsuite, "disabled",
04828       StreamableToString(test_case.reportable_disabled_test_count()));
04829   OutputXmlAttribute(stream, kTestsuite, "errors", "0");
04830   OutputXmlAttribute(stream, kTestsuite, "time",
04831                      FormatTimeInMillisAsSeconds(test_case.elapsed_time()));
04832   *stream << TestPropertiesAsXmlAttributes(test_case.ad_hoc_test_result())
04833           << ">\n";
04834 
04835   for (int i = 0; i < test_case.total_test_count(); ++i) {
04836     if (test_case.GetTestInfo(i)->is_reportable())
04837       OutputXmlTestInfo(stream, test_case.name(), *test_case.GetTestInfo(i));
04838   }
04839   *stream << "  </" << kTestsuite << ">\n";
04840 }
04841 
04842 // Prints an XML summary of unit_test to output stream out.
04843 void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream,
04844                                                 const UnitTest& unit_test) {
04845   const std::string kTestsuites = "testsuites";
04846 
04847   *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
04848   *stream << "<" << kTestsuites;
04849 
04850   OutputXmlAttribute(stream, kTestsuites, "tests",
04851                      StreamableToString(unit_test.reportable_test_count()));
04852   OutputXmlAttribute(stream, kTestsuites, "failures",
04853                      StreamableToString(unit_test.failed_test_count()));
04854   OutputXmlAttribute(
04855       stream, kTestsuites, "disabled",
04856       StreamableToString(unit_test.reportable_disabled_test_count()));
04857   OutputXmlAttribute(stream, kTestsuites, "errors", "0");
04858   OutputXmlAttribute(
04859       stream, kTestsuites, "timestamp",
04860       FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp()));
04861   OutputXmlAttribute(stream, kTestsuites, "time",
04862                      FormatTimeInMillisAsSeconds(unit_test.elapsed_time()));
04863 
04864   if (GTEST_FLAG(shuffle)) {
04865     OutputXmlAttribute(stream, kTestsuites, "random_seed",
04866                        StreamableToString(unit_test.random_seed()));
04867   }
04868 
04869   *stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result());
04870 
04871   OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
04872   *stream << ">\n";
04873 
04874   for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
04875     if (unit_test.GetTestCase(i)->reportable_test_count() > 0)
04876       PrintXmlTestCase(stream, *unit_test.GetTestCase(i));
04877   }
04878   *stream << "</" << kTestsuites << ">\n";
04879 }
04880 
04881 // Produces a string representing the test properties in a result as space
04882 // delimited XML attributes based on the property key="value" pairs.
04883 std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
04884     const TestResult& result) {
04885   Message attributes;
04886   for (int i = 0; i < result.test_property_count(); ++i) {
04887     const TestProperty& property = result.GetTestProperty(i);
04888     attributes << " " << property.key() << "="
04889         << "\"" << EscapeXmlAttribute(property.value()) << "\"";
04890   }
04891   return attributes.GetString();
04892 }
04893 
04894 // End XmlUnitTestResultPrinter
04895 
04896 #if GTEST_CAN_STREAM_RESULTS_
04897 
04898 // Checks if str contains '=', '&', '%' or '\n' characters. If yes,
04899 // replaces them by "%xx" where xx is their hexadecimal value. For
04900 // example, replaces "=" with "%3D".  This algorithm is O(strlen(str))
04901 // in both time and space -- important as the input str may contain an
04902 // arbitrarily long test failure message and stack trace.
04903 string StreamingListener::UrlEncode(const char* str) {
04904   string result;
04905   result.reserve(strlen(str) + 1);
04906   for (char ch = *str; ch != '\0'; ch = *++str) {
04907     switch (ch) {
04908       case '%':
04909       case '=':
04910       case '&':
04911       case '\n':
04912         result.append("%" + String::FormatByte(static_cast<unsigned char>(ch)));
04913         break;
04914       default:
04915         result.push_back(ch);
04916         break;
04917     }
04918   }
04919   return result;
04920 }
04921 
04922 void StreamingListener::SocketWriter::MakeConnection() {
04923   GTEST_CHECK_(sockfd_ == -1)
04924       << "MakeConnection() can't be called when there is already a connection.";
04925 
04926   addrinfo hints;
04927   memset(&hints, 0, sizeof(hints));
04928   hints.ai_family = AF_UNSPEC;    // To allow both IPv4 and IPv6 addresses.
04929   hints.ai_socktype = SOCK_STREAM;
04930   addrinfo* servinfo = NULL;
04931 
04932   // Use the getaddrinfo() to get a linked list of IP addresses for
04933   // the given host name.
04934   const int error_num = getaddrinfo(
04935       host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
04936   if (error_num != 0) {
04937     GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: "
04938                         << gai_strerror(error_num);
04939   }
04940 
04941   // Loop through all the results and connect to the first we can.
04942   for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != NULL;
04943        cur_addr = cur_addr->ai_next) {
04944     sockfd_ = socket(
04945         cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol);
04946     if (sockfd_ != -1) {
04947       // Connect the client socket to the server socket.
04948       if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
04949         close(sockfd_);
04950         sockfd_ = -1;
04951       }
04952     }
04953   }
04954 
04955   freeaddrinfo(servinfo);  // all done with this structure
04956 
04957   if (sockfd_ == -1) {
04958     GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to "
04959                         << host_name_ << ":" << port_num_;
04960   }
04961 }
04962 
04963 // End of class Streaming Listener
04964 #endif  // GTEST_CAN_STREAM_RESULTS__
04965 
04966 // Class ScopedTrace
04967 
04968 // Pushes the given source file location and message onto a per-thread
04969 // trace stack maintained by Google Test.
04970 ScopedTrace::ScopedTrace(const char* file, int line, const Message& message)
04971     GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
04972   TraceInfo trace;
04973   trace.file = file;
04974   trace.line = line;
04975   trace.message = message.GetString();
04976 
04977   UnitTest::GetInstance()->PushGTestTrace(trace);
04978 }
04979 
04980 // Pops the info pushed by the c'tor.
04981 ScopedTrace::~ScopedTrace()
04982     GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
04983   UnitTest::GetInstance()->PopGTestTrace();
04984 }
04985 
04986 
04987 // class OsStackTraceGetter
04988 
04989 // Returns the current OS stack trace as an std::string.  Parameters:
04990 //
04991 //   max_depth  - the maximum number of stack frames to be included
04992 //                in the trace.
04993 //   skip_count - the number of top frames to be skipped; doesn't count
04994 //                against max_depth.
04995 //
04996 string OsStackTraceGetter::CurrentStackTrace(int /* max_depth */,
04997                                              int /* skip_count */)
04998     GTEST_LOCK_EXCLUDED_(mutex_) {
04999   return "";
05000 }
05001 
05002 void OsStackTraceGetter::UponLeavingGTest()
05003     GTEST_LOCK_EXCLUDED_(mutex_) {
05004 }
05005 
05006 const char* const
05007 OsStackTraceGetter::kElidedFramesMarker =
05008     "... " GTEST_NAME_ " internal frames ...";
05009 
05010 // A helper class that creates the premature-exit file in its
05011 // constructor and deletes the file in its destructor.
05012 class ScopedPrematureExitFile {
05013  public:
05014   explicit ScopedPrematureExitFile(const char* premature_exit_filepath)
05015       : premature_exit_filepath_(premature_exit_filepath) {
05016     // If a path to the premature-exit file is specified...
05017     if (premature_exit_filepath != NULL && *premature_exit_filepath != '\0') {
05018       // create the file with a single "0" character in it.  I/O
05019       // errors are ignored as there's nothing better we can do and we
05020       // don't want to fail the test because of this.
05021       FILE* pfile = posix::FOpen(premature_exit_filepath, "w");
05022       fwrite("0", 1, 1, pfile);
05023       fclose(pfile);
05024     }
05025   }
05026 
05027   ~ScopedPrematureExitFile() {
05028     if (premature_exit_filepath_ != NULL && *premature_exit_filepath_ != '\0') {
05029       remove(premature_exit_filepath_);
05030     }
05031   }
05032 
05033  private:
05034   const char* const premature_exit_filepath_;
05035 
05036   GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedPrematureExitFile);
05037 };
05038 
05039 }  // namespace internal
05040 
05041 // class TestEventListeners
05042 
05043 TestEventListeners::TestEventListeners()
05044     : repeater_(new internal::TestEventRepeater()),
05045       default_result_printer_(NULL),
05046       default_xml_generator_(NULL) {
05047 }
05048 
05049 TestEventListeners::~TestEventListeners() { delete repeater_; }
05050 
05051 // Returns the standard listener responsible for the default console
05052 // output.  Can be removed from the listeners list to shut down default
05053 // console output.  Note that removing this object from the listener list
05054 // with Release transfers its ownership to the user.
05055 void TestEventListeners::Append(TestEventListener* listener) {
05056   repeater_->Append(listener);
05057 }
05058 
05059 // Removes the given event listener from the list and returns it.  It then
05060 // becomes the caller's responsibility to delete the listener. Returns
05061 // NULL if the listener is not found in the list.
05062 TestEventListener* TestEventListeners::Release(TestEventListener* listener) {
05063   if (listener == default_result_printer_)
05064     default_result_printer_ = NULL;
05065   else if (listener == default_xml_generator_)
05066     default_xml_generator_ = NULL;
05067   return repeater_->Release(listener);
05068 }
05069 
05070 // Returns repeater that broadcasts the TestEventListener events to all
05071 // subscribers.
05072 TestEventListener* TestEventListeners::repeater() { return repeater_; }
05073 
05074 // Sets the default_result_printer attribute to the provided listener.
05075 // The listener is also added to the listener list and previous
05076 // default_result_printer is removed from it and deleted. The listener can
05077 // also be NULL in which case it will not be added to the list. Does
05078 // nothing if the previous and the current listener objects are the same.
05079 void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
05080   if (default_result_printer_ != listener) {
05081     // It is an error to pass this method a listener that is already in the
05082     // list.
05083     delete Release(default_result_printer_);
05084     default_result_printer_ = listener;
05085     if (listener != NULL)
05086       Append(listener);
05087   }
05088 }
05089 
05090 // Sets the default_xml_generator attribute to the provided listener.  The
05091 // listener is also added to the listener list and previous
05092 // default_xml_generator is removed from it and deleted. The listener can
05093 // also be NULL in which case it will not be added to the list. Does
05094 // nothing if the previous and the current listener objects are the same.
05095 void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
05096   if (default_xml_generator_ != listener) {
05097     // It is an error to pass this method a listener that is already in the
05098     // list.
05099     delete Release(default_xml_generator_);
05100     default_xml_generator_ = listener;
05101     if (listener != NULL)
05102       Append(listener);
05103   }
05104 }
05105 
05106 // Controls whether events will be forwarded by the repeater to the
05107 // listeners in the list.
05108 bool TestEventListeners::EventForwardingEnabled() const {
05109   return repeater_->forwarding_enabled();
05110 }
05111 
05112 void TestEventListeners::SuppressEventForwarding() {
05113   repeater_->set_forwarding_enabled(false);
05114 }
05115 
05116 // class UnitTest
05117 
05118 // Gets the singleton UnitTest object.  The first time this method is
05119 // called, a UnitTest object is constructed and returned.  Consecutive
05120 // calls will return the same object.
05121 //
05122 // We don't protect this under mutex_ as a user is not supposed to
05123 // call this before main() starts, from which point on the return
05124 // value will never change.
05125 UnitTest* UnitTest::GetInstance() {
05126   // When compiled with MSVC 7.1 in optimized mode, destroying the
05127   // UnitTest object upon exiting the program messes up the exit code,
05128   // causing successful tests to appear failed.  We have to use a
05129   // different implementation in this case to bypass the compiler bug.
05130   // This implementation makes the compiler happy, at the cost of
05131   // leaking the UnitTest object.
05132 
05133   // CodeGear C++Builder insists on a public destructor for the
05134   // default implementation.  Use this implementation to keep good OO
05135   // design with private destructor.
05136 
05137 #if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
05138   static UnitTest* const instance = new UnitTest;
05139   return instance;
05140 #else
05141   static UnitTest instance;
05142   return &instance;
05143 #endif  // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
05144 }
05145 
05146 // Gets the number of successful test cases.
05147 int UnitTest::successful_test_case_count() const {
05148   return impl()->successful_test_case_count();
05149 }
05150 
05151 // Gets the number of failed test cases.
05152 int UnitTest::failed_test_case_count() const {
05153   return impl()->failed_test_case_count();
05154 }
05155 
05156 // Gets the number of all test cases.
05157 int UnitTest::total_test_case_count() const {
05158   return impl()->total_test_case_count();
05159 }
05160 
05161 // Gets the number of all test cases that contain at least one test
05162 // that should run.
05163 int UnitTest::test_case_to_run_count() const {
05164   return impl()->test_case_to_run_count();
05165 }
05166 
05167 // Gets the number of successful tests.
05168 int UnitTest::successful_test_count() const {
05169   return impl()->successful_test_count();
05170 }
05171 
05172 // Gets the number of failed tests.
05173 int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
05174 
05175 // Gets the number of disabled tests that will be reported in the XML report.
05176 int UnitTest::reportable_disabled_test_count() const {
05177   return impl()->reportable_disabled_test_count();
05178 }
05179 
05180 // Gets the number of disabled tests.
05181 int UnitTest::disabled_test_count() const {
05182   return impl()->disabled_test_count();
05183 }
05184 
05185 // Gets the number of tests to be printed in the XML report.
05186 int UnitTest::reportable_test_count() const {
05187   return impl()->reportable_test_count();
05188 }
05189 
05190 // Gets the number of all tests.
05191 int UnitTest::total_test_count() const { return impl()->total_test_count(); }
05192 
05193 // Gets the number of tests that should run.
05194 int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
05195 
05196 // Gets the time of the test program start, in ms from the start of the
05197 // UNIX epoch.
05198 internal::TimeInMillis UnitTest::start_timestamp() const {
05199     return impl()->start_timestamp();
05200 }
05201 
05202 // Gets the elapsed time, in milliseconds.
05203 internal::TimeInMillis UnitTest::elapsed_time() const {
05204   return impl()->elapsed_time();
05205 }
05206 
05207 // Returns true iff the unit test passed (i.e. all test cases passed).
05208 bool UnitTest::Passed() const { return impl()->Passed(); }
05209 
05210 // Returns true iff the unit test failed (i.e. some test case failed
05211 // or something outside of all tests failed).
05212 bool UnitTest::Failed() const { return impl()->Failed(); }
05213 
05214 // Gets the i-th test case among all the test cases. i can range from 0 to
05215 // total_test_case_count() - 1. If i is not in that range, returns NULL.
05216 const TestCase* UnitTest::GetTestCase(int i) const {
05217   return impl()->GetTestCase(i);
05218 }
05219 
05220 // Returns the TestResult containing information on test failures and
05221 // properties logged outside of individual test cases.
05222 const TestResult& UnitTest::ad_hoc_test_result() const {
05223   return *impl()->ad_hoc_test_result();
05224 }
05225 
05226 // Gets the i-th test case among all the test cases. i can range from 0 to
05227 // total_test_case_count() - 1. If i is not in that range, returns NULL.
05228 TestCase* UnitTest::GetMutableTestCase(int i) {
05229   return impl()->GetMutableTestCase(i);
05230 }
05231 
05232 // Returns the list of event listeners that can be used to track events
05233 // inside Google Test.
05234 TestEventListeners& UnitTest::listeners() {
05235   return *impl()->listeners();
05236 }
05237 
05238 // Registers and returns a global test environment.  When a test
05239 // program is run, all global test environments will be set-up in the
05240 // order they were registered.  After all tests in the program have
05241 // finished, all global test environments will be torn-down in the
05242 // *reverse* order they were registered.
05243 //
05244 // The UnitTest object takes ownership of the given environment.
05245 //
05246 // We don't protect this under mutex_, as we only support calling it
05247 // from the main thread.
05248 Environment* UnitTest::AddEnvironment(Environment* env) {
05249   if (env == NULL) {
05250     return NULL;
05251   }
05252 
05253   impl_->environments().push_back(env);
05254   return env;
05255 }
05256 
05257 // Adds a TestPartResult to the current TestResult object.  All Google Test
05258 // assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
05259 // this to report their results.  The user code should use the
05260 // assertion macros instead of calling this directly.
05261 void UnitTest::AddTestPartResult(
05262     TestPartResult::Type result_type,
05263     const char* file_name,
05264     int line_number,
05265     const std::string& message,
05266     const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_) {
05267   Message msg;
05268   msg << message;
05269 
05270   internal::MutexLock lock(&mutex_);
05271   if (impl_->gtest_trace_stack().size() > 0) {
05272     msg << "\n" << GTEST_NAME_ << " trace:";
05273 
05274     for (int i = static_cast<int>(impl_->gtest_trace_stack().size());
05275          i > 0; --i) {
05276       const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
05277       msg << "\n" << internal::FormatFileLocation(trace.file, trace.line)
05278           << " " << trace.message;
05279     }
05280   }
05281 
05282   if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) {
05283     msg << internal::kStackTraceMarker << os_stack_trace;
05284   }
05285 
05286   const TestPartResult result =
05287     TestPartResult(result_type, file_name, line_number,
05288                    msg.GetString().c_str());
05289   impl_->GetTestPartResultReporterForCurrentThread()->
05290       ReportTestPartResult(result);
05291 
05292   if (result_type != TestPartResult::kSuccess) {
05293     // gtest_break_on_failure takes precedence over
05294     // gtest_throw_on_failure.  This allows a user to set the latter
05295     // in the code (perhaps in order to use Google Test assertions
05296     // with another testing framework) and specify the former on the
05297     // command line for debugging.
05298     if (GTEST_FLAG(break_on_failure)) {
05299 #if GTEST_OS_WINDOWS
05300       // Using DebugBreak on Windows allows gtest to still break into a debugger
05301       // when a failure happens and both the --gtest_break_on_failure and
05302       // the --gtest_catch_exceptions flags are specified.
05303       DebugBreak();
05304 #else
05305       // Dereference NULL through a volatile pointer to prevent the compiler
05306       // from removing. We use this rather than abort() or __builtin_trap() for
05307       // portability: Symbian doesn't implement abort() well, and some debuggers
05308       // don't correctly trap abort().
05309       *static_cast<volatile int*>(NULL) = 1;
05310 #endif  // GTEST_OS_WINDOWS
05311     } else if (GTEST_FLAG(throw_on_failure)) {
05312 #if GTEST_HAS_EXCEPTIONS
05313       throw internal::GoogleTestFailureException(result);
05314 #else
05315       // We cannot call abort() as it generates a pop-up in debug mode
05316       // that cannot be suppressed in VC 7.1 or below.
05317       exit(1);
05318 #endif
05319     }
05320   }
05321 }
05322 
05323 // Adds a TestProperty to the current TestResult object when invoked from
05324 // inside a test, to current TestCase's ad_hoc_test_result_ when invoked
05325 // from SetUpTestCase or TearDownTestCase, or to the global property set
05326 // when invoked elsewhere.  If the result already contains a property with
05327 // the same key, the value will be updated.
05328 void UnitTest::RecordProperty(const std::string& key,
05329                               const std::string& value) {
05330   impl_->RecordProperty(TestProperty(key, value));
05331 }
05332 
05333 // Runs all tests in this UnitTest object and prints the result.
05334 // Returns 0 if successful, or 1 otherwise.
05335 //
05336 // We don't protect this under mutex_, as we only support calling it
05337 // from the main thread.
05338 int UnitTest::Run() {
05339   const bool in_death_test_child_process =
05340       internal::GTEST_FLAG(internal_run_death_test).length() > 0;
05341 
05342   // Google Test implements this protocol for catching that a test
05343   // program exits before returning control to Google Test:
05344   //
05345   //   1. Upon start, Google Test creates a file whose absolute path
05346   //      is specified by the environment variable
05347   //      TEST_PREMATURE_EXIT_FILE.
05348   //   2. When Google Test has finished its work, it deletes the file.
05349   //
05350   // This allows a test runner to set TEST_PREMATURE_EXIT_FILE before
05351   // running a Google-Test-based test program and check the existence
05352   // of the file at the end of the test execution to see if it has
05353   // exited prematurely.
05354 
05355   // If we are in the child process of a death test, don't
05356   // create/delete the premature exit file, as doing so is unnecessary
05357   // and will confuse the parent process.  Otherwise, create/delete
05358   // the file upon entering/leaving this function.  If the program
05359   // somehow exits before this function has a chance to return, the
05360   // premature-exit file will be left undeleted, causing a test runner
05361   // that understands the premature-exit-file protocol to report the
05362   // test as having failed.
05363   const internal::ScopedPrematureExitFile premature_exit_file(
05364       in_death_test_child_process ?
05365       NULL : internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE"));
05366 
05367   // Captures the value of GTEST_FLAG(catch_exceptions).  This value will be
05368   // used for the duration of the program.
05369   impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions));
05370 
05371 #if GTEST_HAS_SEH
05372   // Either the user wants Google Test to catch exceptions thrown by the
05373   // tests or this is executing in the context of death test child
05374   // process. In either case the user does not want to see pop-up dialogs
05375   // about crashes - they are expected.
05376   if (impl()->catch_exceptions() || in_death_test_child_process) {
05377 # if !GTEST_OS_WINDOWS_MOBILE
05378     // SetErrorMode doesn't exist on CE.
05379     SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
05380                  SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
05381 # endif  // !GTEST_OS_WINDOWS_MOBILE
05382 
05383 # if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
05384     // Death test children can be terminated with _abort().  On Windows,
05385     // _abort() can show a dialog with a warning message.  This forces the
05386     // abort message to go to stderr instead.
05387     _set_error_mode(_OUT_TO_STDERR);
05388 # endif
05389 
05390 # if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
05391     // In the debug version, Visual Studio pops up a separate dialog
05392     // offering a choice to debug the aborted program. We need to suppress
05393     // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
05394     // executed. Google Test will notify the user of any unexpected
05395     // failure via stderr.
05396     //
05397     // VC++ doesn't define _set_abort_behavior() prior to the version 8.0.
05398     // Users of prior VC versions shall suffer the agony and pain of
05399     // clicking through the countless debug dialogs.
05400     // TODO(vladl@google.com): find a way to suppress the abort dialog() in the
05401     // debug mode when compiled with VC 7.1 or lower.
05402     if (!GTEST_FLAG(break_on_failure))
05403       _set_abort_behavior(
05404           0x0,                                    // Clear the following flags:
05405           _WRITE_ABORT_MSG | _CALL_REPORTFAULT);  // pop-up window, core dump.
05406 # endif
05407   }
05408 #endif  // GTEST_HAS_SEH
05409 
05410   return internal::HandleExceptionsInMethodIfSupported(
05411       impl(),
05412       &internal::UnitTestImpl::RunAllTests,
05413       "auxiliary test code (environments or event listeners)") ? 0 : 1;
05414 }
05415 
05416 // Returns the working directory when the first TEST() or TEST_F() was
05417 // executed.
05418 const char* UnitTest::original_working_dir() const {
05419   return impl_->original_working_dir_.c_str();
05420 }
05421 
05422 // Returns the TestCase object for the test that's currently running,
05423 // or NULL if no test is running.
05424 const TestCase* UnitTest::current_test_case() const
05425     GTEST_LOCK_EXCLUDED_(mutex_) {
05426   internal::MutexLock lock(&mutex_);
05427   return impl_->current_test_case();
05428 }
05429 
05430 // Returns the TestInfo object for the test that's currently running,
05431 // or NULL if no test is running.
05432 const TestInfo* UnitTest::current_test_info() const
05433     GTEST_LOCK_EXCLUDED_(mutex_) {
05434   internal::MutexLock lock(&mutex_);
05435   return impl_->current_test_info();
05436 }
05437 
05438 // Returns the random seed used at the start of the current test run.
05439 int UnitTest::random_seed() const { return impl_->random_seed(); }
05440 
05441 #if GTEST_HAS_PARAM_TEST
05442 // Returns ParameterizedTestCaseRegistry object used to keep track of
05443 // value-parameterized tests and instantiate and register them.
05444 internal::ParameterizedTestCaseRegistry&
05445     UnitTest::parameterized_test_registry()
05446         GTEST_LOCK_EXCLUDED_(mutex_) {
05447   return impl_->parameterized_test_registry();
05448 }
05449 #endif  // GTEST_HAS_PARAM_TEST
05450 
05451 // Creates an empty UnitTest.
05452 UnitTest::UnitTest() {
05453   impl_ = new internal::UnitTestImpl(this);
05454 }
05455 
05456 // Destructor of UnitTest.
05457 UnitTest::~UnitTest() {
05458   delete impl_;
05459 }
05460 
05461 // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
05462 // Google Test trace stack.
05463 void UnitTest::PushGTestTrace(const internal::TraceInfo& trace)
05464     GTEST_LOCK_EXCLUDED_(mutex_) {
05465   internal::MutexLock lock(&mutex_);
05466   impl_->gtest_trace_stack().push_back(trace);
05467 }
05468 
05469 // Pops a trace from the per-thread Google Test trace stack.
05470 void UnitTest::PopGTestTrace()
05471     GTEST_LOCK_EXCLUDED_(mutex_) {
05472   internal::MutexLock lock(&mutex_);
05473   impl_->gtest_trace_stack().pop_back();
05474 }
05475 
05476 namespace internal {
05477 
05478 UnitTestImpl::UnitTestImpl(UnitTest* parent)
05479     : parent_(parent),
05480 #ifdef _MSC_VER
05481 # pragma warning(push)                    // Saves the current warning state.
05482 # pragma warning(disable:4355)            // Temporarily disables warning 4355
05483                                          // (using this in initializer).
05484       default_global_test_part_result_reporter_(this),
05485       default_per_thread_test_part_result_reporter_(this),
05486 # pragma warning(pop)                     // Restores the warning state again.
05487 #else
05488       default_global_test_part_result_reporter_(this),
05489       default_per_thread_test_part_result_reporter_(this),
05490 #endif  // _MSC_VER
05491       global_test_part_result_repoter_(
05492           &default_global_test_part_result_reporter_),
05493       per_thread_test_part_result_reporter_(
05494           &default_per_thread_test_part_result_reporter_),
05495 #if GTEST_HAS_PARAM_TEST
05496       parameterized_test_registry_(),
05497       parameterized_tests_registered_(false),
05498 #endif  // GTEST_HAS_PARAM_TEST
05499       last_death_test_case_(-1),
05500       current_test_case_(NULL),
05501       current_test_info_(NULL),
05502       ad_hoc_test_result_(),
05503       os_stack_trace_getter_(NULL),
05504       post_flag_parse_init_performed_(false),
05505       random_seed_(0),  // Will be overridden by the flag before first use.
05506       random_(0),  // Will be reseeded before first use.
05507       start_timestamp_(0),
05508       elapsed_time_(0),
05509 #if GTEST_HAS_DEATH_TEST
05510       death_test_factory_(new DefaultDeathTestFactory),
05511 #endif
05512       // Will be overridden by the flag before first use.
05513       catch_exceptions_(false) {
05514   listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);
05515 }
05516 
05517 UnitTestImpl::~UnitTestImpl() {
05518   // Deletes every TestCase.
05519   ForEach(test_cases_, internal::Delete<TestCase>);
05520 
05521   // Deletes every Environment.
05522   ForEach(environments_, internal::Delete<Environment>);
05523 
05524   delete os_stack_trace_getter_;
05525 }
05526 
05527 // Adds a TestProperty to the current TestResult object when invoked in a
05528 // context of a test, to current test case's ad_hoc_test_result when invoke
05529 // from SetUpTestCase/TearDownTestCase, or to the global property set
05530 // otherwise.  If the result already contains a property with the same key,
05531 // the value will be updated.
05532 void UnitTestImpl::RecordProperty(const TestProperty& test_property) {
05533   std::string xml_element;
05534   TestResult* test_result;  // TestResult appropriate for property recording.
05535 
05536   if (current_test_info_ != NULL) {
05537     xml_element = "testcase";
05538     test_result = &(current_test_info_->result_);
05539   } else if (current_test_case_ != NULL) {
05540     xml_element = "testsuite";
05541     test_result = &(current_test_case_->ad_hoc_test_result_);
05542   } else {
05543     xml_element = "testsuites";
05544     test_result = &ad_hoc_test_result_;
05545   }
05546   test_result->RecordProperty(xml_element, test_property);
05547 }
05548 
05549 #if GTEST_HAS_DEATH_TEST
05550 // Disables event forwarding if the control is currently in a death test
05551 // subprocess. Must not be called before InitGoogleTest.
05552 void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
05553   if (internal_run_death_test_flag_.get() != NULL)
05554     listeners()->SuppressEventForwarding();
05555 }
05556 #endif  // GTEST_HAS_DEATH_TEST
05557 
05558 // Initializes event listeners performing XML output as specified by
05559 // UnitTestOptions. Must not be called before InitGoogleTest.
05560 void UnitTestImpl::ConfigureXmlOutput() {
05561   const std::string& output_format = UnitTestOptions::GetOutputFormat();
05562   if (output_format == "xml") {
05563     listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
05564         UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
05565   } else if (output_format != "") {
05566     printf("WARNING: unrecognized output format \"%s\" ignored.\n",
05567            output_format.c_str());
05568     fflush(stdout);
05569   }
05570 }
05571 
05572 #if GTEST_CAN_STREAM_RESULTS_
05573 // Initializes event listeners for streaming test results in string form.
05574 // Must not be called before InitGoogleTest.
05575 void UnitTestImpl::ConfigureStreamingOutput() {
05576   const std::string& target = GTEST_FLAG(stream_result_to);
05577   if (!target.empty()) {
05578     const size_t pos = target.find(':');
05579     if (pos != std::string::npos) {
05580       listeners()->Append(new StreamingListener(target.substr(0, pos),
05581                                                 target.substr(pos+1)));
05582     } else {
05583       printf("WARNING: unrecognized streaming target \"%s\" ignored.\n",
05584              target.c_str());
05585       fflush(stdout);
05586     }
05587   }
05588 }
05589 #endif  // GTEST_CAN_STREAM_RESULTS_
05590 
05591 // Performs initialization dependent upon flag values obtained in
05592 // ParseGoogleTestFlagsOnly.  Is called from InitGoogleTest after the call to
05593 // ParseGoogleTestFlagsOnly.  In case a user neglects to call InitGoogleTest
05594 // this function is also called from RunAllTests.  Since this function can be
05595 // called more than once, it has to be idempotent.
05596 void UnitTestImpl::PostFlagParsingInit() {
05597   // Ensures that this function does not execute more than once.
05598   if (!post_flag_parse_init_performed_) {
05599     post_flag_parse_init_performed_ = true;
05600 
05601 #if GTEST_HAS_DEATH_TEST
05602     InitDeathTestSubprocessControlInfo();
05603     SuppressTestEventsIfInSubprocess();
05604 #endif  // GTEST_HAS_DEATH_TEST
05605 
05606     // Registers parameterized tests. This makes parameterized tests
05607     // available to the UnitTest reflection API without running
05608     // RUN_ALL_TESTS.
05609     RegisterParameterizedTests();
05610 
05611     // Configures listeners for XML output. This makes it possible for users
05612     // to shut down the default XML output before invoking RUN_ALL_TESTS.
05613     ConfigureXmlOutput();
05614 
05615 #if GTEST_CAN_STREAM_RESULTS_
05616     // Configures listeners for streaming test results to the specified server.
05617     ConfigureStreamingOutput();
05618 #endif  // GTEST_CAN_STREAM_RESULTS_
05619   }
05620 }
05621 
05622 // A predicate that checks the name of a TestCase against a known
05623 // value.
05624 //
05625 // This is used for implementation of the UnitTest class only.  We put
05626 // it in the anonymous namespace to prevent polluting the outer
05627 // namespace.
05628 //
05629 // TestCaseNameIs is copyable.
05630 class TestCaseNameIs {
05631  public:
05632   // Constructor.
05633   explicit TestCaseNameIs(const std::string& name)
05634       : name_(name) {}
05635 
05636   // Returns true iff the name of test_case matches name_.
05637   bool operator()(const TestCase* test_case) const {
05638     return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0;
05639   }
05640 
05641  private:
05642   std::string name_;
05643 };
05644 
05645 // Finds and returns a TestCase with the given name.  If one doesn't
05646 // exist, creates one and returns it.  It's the CALLER'S
05647 // RESPONSIBILITY to ensure that this function is only called WHEN THE
05648 // TESTS ARE NOT SHUFFLED.
05649 //
05650 // Arguments:
05651 //
05652 //   test_case_name: name of the test case
05653 //   type_param:     the name of the test case's type parameter, or NULL if
05654 //                   this is not a typed or a type-parameterized test case.
05655 //   set_up_tc:      pointer to the function that sets up the test case
05656 //   tear_down_tc:   pointer to the function that tears down the test case
05657 TestCase* UnitTestImpl::GetTestCase(const char* test_case_name,
05658                                     const char* type_param,
05659                                     Test::SetUpTestCaseFunc set_up_tc,
05660                                     Test::TearDownTestCaseFunc tear_down_tc) {
05661   // Can we find a TestCase with the given name?
05662   const std::vector<TestCase*>::const_iterator test_case =
05663       std::find_if(test_cases_.begin(), test_cases_.end(),
05664                    TestCaseNameIs(test_case_name));
05665 
05666   if (test_case != test_cases_.end())
05667     return *test_case;
05668 
05669   // No.  Let's create one.
05670   TestCase* const new_test_case =
05671       new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc);
05672 
05673   // Is this a death test case?
05674   if (internal::UnitTestOptions::MatchesFilter(test_case_name,
05675                                                kDeathTestCaseFilter)) {
05676     // Yes.  Inserts the test case after the last death test case
05677     // defined so far.  This only works when the test cases haven't
05678     // been shuffled.  Otherwise we may end up running a death test
05679     // after a non-death test.
05680     ++last_death_test_case_;
05681     test_cases_.insert(test_cases_.begin() + last_death_test_case_,
05682                        new_test_case);
05683   } else {
05684     // No.  Appends to the end of the list.
05685     test_cases_.push_back(new_test_case);
05686   }
05687 
05688   test_case_indices_.push_back(static_cast<int>(test_case_indices_.size()));
05689   return new_test_case;
05690 }
05691 
05692 // Helpers for setting up / tearing down the given environment.  They
05693 // are for use in the ForEach() function.
05694 static void SetUpEnvironment(Environment* env) { env->SetUp(); }
05695 static void TearDownEnvironment(Environment* env) { env->TearDown(); }
05696 
05697 // Runs all tests in this UnitTest object, prints the result, and
05698 // returns true if all tests are successful.  If any exception is
05699 // thrown during a test, the test is considered to be failed, but the
05700 // rest of the tests will still be run.
05701 //
05702 // When parameterized tests are enabled, it expands and registers
05703 // parameterized tests first in RegisterParameterizedTests().
05704 // All other functions called from RunAllTests() may safely assume that
05705 // parameterized tests are ready to be counted and run.
05706 bool UnitTestImpl::RunAllTests() {
05707   // Makes sure InitGoogleTest() was called.
05708   if (!GTestIsInitialized()) {
05709     printf("%s",
05710            "\nThis test program did NOT call ::testing::InitGoogleTest "
05711            "before calling RUN_ALL_TESTS().  Please fix it.\n");
05712     return false;
05713   }
05714 
05715   // Do not run any test if the --help flag was specified.
05716   if (g_help_flag)
05717     return true;
05718 
05719   // Repeats the call to the post-flag parsing initialization in case the
05720   // user didn't call InitGoogleTest.
05721   PostFlagParsingInit();
05722 
05723   // Even if sharding is not on, test runners may want to use the
05724   // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
05725   // protocol.
05726   internal::WriteToShardStatusFileIfNeeded();
05727 
05728   // True iff we are in a subprocess for running a thread-safe-style
05729   // death test.
05730   bool in_subprocess_for_death_test = false;
05731 
05732 #if GTEST_HAS_DEATH_TEST
05733   in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL);
05734 #endif  // GTEST_HAS_DEATH_TEST
05735 
05736   const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
05737                                         in_subprocess_for_death_test);
05738 
05739   // Compares the full test names with the filter to decide which
05740   // tests to run.
05741   const bool has_tests_to_run = FilterTests(should_shard
05742                                               ? HONOR_SHARDING_PROTOCOL
05743                                               : IGNORE_SHARDING_PROTOCOL) > 0;
05744 
05745   // Lists the tests and exits if the --gtest_list_tests flag was specified.
05746   if (GTEST_FLAG(list_tests)) {
05747     // This must be called *after* FilterTests() has been called.
05748     ListTestsMatchingFilter();
05749     return true;
05750   }
05751 
05752   random_seed_ = GTEST_FLAG(shuffle) ?
05753       GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;
05754 
05755   // True iff at least one test has failed.
05756   bool failed = false;
05757 
05758   TestEventListener* repeater = listeners()->repeater();
05759 
05760   start_timestamp_ = GetTimeInMillis();
05761   repeater->OnTestProgramStart(*parent_);
05762 
05763   // How many times to repeat the tests?  We don't want to repeat them
05764   // when we are inside the subprocess of a death test.
05765   const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);
05766   // Repeats forever if the repeat count is negative.
05767   const bool forever = repeat < 0;
05768   for (int i = 0; forever || i != repeat; i++) {
05769     // We want to preserve failures generated by ad-hoc test
05770     // assertions executed before RUN_ALL_TESTS().
05771     ClearNonAdHocTestResult();
05772 
05773     const TimeInMillis start = GetTimeInMillis();
05774 
05775     // Shuffles test cases and tests if requested.
05776     if (has_tests_to_run && GTEST_FLAG(shuffle)) {
05777       random()->Reseed(random_seed_);
05778       // This should be done before calling OnTestIterationStart(),
05779       // such that a test event listener can see the actual test order
05780       // in the event.
05781       ShuffleTests();
05782     }
05783 
05784     // Tells the unit test event listeners that the tests are about to start.
05785     repeater->OnTestIterationStart(*parent_, i);
05786 
05787     // Runs each test case if there is at least one test to run.
05788     if (has_tests_to_run) {
05789       // Sets up all environments beforehand.
05790       repeater->OnEnvironmentsSetUpStart(*parent_);
05791       ForEach(environments_, SetUpEnvironment);
05792       repeater->OnEnvironmentsSetUpEnd(*parent_);
05793 
05794       // Runs the tests only if there was no fatal failure during global
05795       // set-up.
05796       if (!Test::HasFatalFailure()) {
05797         for (int test_index = 0; test_index < total_test_case_count();
05798              test_index++) {
05799           GetMutableTestCase(test_index)->Run();
05800         }
05801       }
05802 
05803       // Tears down all environments in reverse order afterwards.
05804       repeater->OnEnvironmentsTearDownStart(*parent_);
05805       std::for_each(environments_.rbegin(), environments_.rend(),
05806                     TearDownEnvironment);
05807       repeater->OnEnvironmentsTearDownEnd(*parent_);
05808     }
05809 
05810     elapsed_time_ = GetTimeInMillis() - start;
05811 
05812     // Tells the unit test event listener that the tests have just finished.
05813     repeater->OnTestIterationEnd(*parent_, i);
05814 
05815     // Gets the result and clears it.
05816     if (!Passed()) {
05817       failed = true;
05818     }
05819 
05820     // Restores the original test order after the iteration.  This
05821     // allows the user to quickly repro a failure that happens in the
05822     // N-th iteration without repeating the first (N - 1) iterations.
05823     // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in
05824     // case the user somehow changes the value of the flag somewhere
05825     // (it's always safe to unshuffle the tests).
05826     UnshuffleTests();
05827 
05828     if (GTEST_FLAG(shuffle)) {
05829       // Picks a new random seed for each iteration.
05830       random_seed_ = GetNextRandomSeed(random_seed_);
05831     }
05832   }
05833 
05834   repeater->OnTestProgramEnd(*parent_);
05835 
05836   return !failed;
05837 }
05838 
05839 // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
05840 // if the variable is present. If a file already exists at this location, this
05841 // function will write over it. If the variable is present, but the file cannot
05842 // be created, prints an error and exits.
05843 void WriteToShardStatusFileIfNeeded() {
05844   const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);
05845   if (test_shard_file != NULL) {
05846     FILE* const file = posix::FOpen(test_shard_file, "w");
05847     if (file == NULL) {
05848       ColoredPrintf(COLOR_RED,
05849                     "Could not write to the test shard status file \"%s\" "
05850                     "specified by the %s environment variable.\n",
05851                     test_shard_file, kTestShardStatusFile);
05852       fflush(stdout);
05853       exit(EXIT_FAILURE);
05854     }
05855     fclose(file);
05856   }
05857 }
05858 
05859 // Checks whether sharding is enabled by examining the relevant
05860 // environment variable values. If the variables are present,
05861 // but inconsistent (i.e., shard_index >= total_shards), prints
05862 // an error and exits. If in_subprocess_for_death_test, sharding is
05863 // disabled because it must only be applied to the original test
05864 // process. Otherwise, we could filter out death tests we intended to execute.
05865 bool ShouldShard(const char* total_shards_env,
05866                  const char* shard_index_env,
05867                  bool in_subprocess_for_death_test) {
05868   if (in_subprocess_for_death_test) {
05869     return false;
05870   }
05871 
05872   const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1);
05873   const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1);
05874 
05875   if (total_shards == -1 && shard_index == -1) {
05876     return false;
05877   } else if (total_shards == -1 && shard_index != -1) {
05878     const Message msg = Message()
05879       << "Invalid environment variables: you have "
05880       << kTestShardIndex << " = " << shard_index
05881       << ", but have left " << kTestTotalShards << " unset.\n";
05882     ColoredPrintf(COLOR_RED, msg.GetString().c_str());
05883     fflush(stdout);
05884     exit(EXIT_FAILURE);
05885   } else if (total_shards != -1 && shard_index == -1) {
05886     const Message msg = Message()
05887       << "Invalid environment variables: you have "
05888       << kTestTotalShards << " = " << total_shards
05889       << ", but have left " << kTestShardIndex << " unset.\n";
05890     ColoredPrintf(COLOR_RED, msg.GetString().c_str());
05891     fflush(stdout);
05892     exit(EXIT_FAILURE);
05893   } else if (shard_index < 0 || shard_index >= total_shards) {
05894     const Message msg = Message()
05895       << "Invalid environment variables: we require 0 <= "
05896       << kTestShardIndex << " < " << kTestTotalShards
05897       << ", but you have " << kTestShardIndex << "=" << shard_index
05898       << ", " << kTestTotalShards << "=" << total_shards << ".\n";
05899     ColoredPrintf(COLOR_RED, msg.GetString().c_str());
05900     fflush(stdout);
05901     exit(EXIT_FAILURE);
05902   }
05903 
05904   return total_shards > 1;
05905 }
05906 
05907 // Parses the environment variable var as an Int32. If it is unset,
05908 // returns default_val. If it is not an Int32, prints an error
05909 // and aborts.
05910 Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) {
05911   const char* str_val = posix::GetEnv(var);
05912   if (str_val == NULL) {
05913     return default_val;
05914   }
05915 
05916   Int32 result;
05917   if (!ParseInt32(Message() << "The value of environment variable " << var,
05918                   str_val, &result)) {
05919     exit(EXIT_FAILURE);
05920   }
05921   return result;
05922 }
05923 
05924 // Given the total number of shards, the shard index, and the test id,
05925 // returns true iff the test should be run on this shard. The test id is
05926 // some arbitrary but unique non-negative integer assigned to each test
05927 // method. Assumes that 0 <= shard_index < total_shards.
05928 bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
05929   return (test_id % total_shards) == shard_index;
05930 }
05931 
05932 // Compares the name of each test with the user-specified filter to
05933 // decide whether the test should be run, then records the result in
05934 // each TestCase and TestInfo object.
05935 // If shard_tests == true, further filters tests based on sharding
05936 // variables in the environment - see
05937 // http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide.
05938 // Returns the number of tests that should run.
05939 int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
05940   const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?
05941       Int32FromEnvOrDie(kTestTotalShards, -1) : -1;
05942   const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?
05943       Int32FromEnvOrDie(kTestShardIndex, -1) : -1;
05944 
05945   // num_runnable_tests are the number of tests that will
05946   // run across all shards (i.e., match filter and are not disabled).
05947   // num_selected_tests are the number of tests to be run on
05948   // this shard.
05949   int num_runnable_tests = 0;
05950   int num_selected_tests = 0;
05951   for (size_t i = 0; i < test_cases_.size(); i++) {
05952     TestCase* const test_case = test_cases_[i];
05953     const std::string &test_case_name = test_case->name();
05954     test_case->set_should_run(false);
05955 
05956     for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
05957       TestInfo* const test_info = test_case->test_info_list()[j];
05958       const std::string test_name(test_info->name());
05959       // A test is disabled if test case name or test name matches
05960       // kDisableTestFilter.
05961       const bool is_disabled =
05962           internal::UnitTestOptions::MatchesFilter(test_case_name,
05963                                                    kDisableTestFilter) ||
05964           internal::UnitTestOptions::MatchesFilter(test_name,
05965                                                    kDisableTestFilter);
05966       test_info->is_disabled_ = is_disabled;
05967 
05968       const bool matches_filter =
05969           internal::UnitTestOptions::FilterMatchesTest(test_case_name,
05970                                                        test_name);
05971       test_info->matches_filter_ = matches_filter;
05972 
05973       const bool is_runnable =
05974           (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
05975           matches_filter;
05976 
05977       const bool is_selected = is_runnable &&
05978           (shard_tests == IGNORE_SHARDING_PROTOCOL ||
05979            ShouldRunTestOnShard(total_shards, shard_index,
05980                                 num_runnable_tests));
05981 
05982       num_runnable_tests += is_runnable;
05983       num_selected_tests += is_selected;
05984 
05985       test_info->should_run_ = is_selected;
05986       test_case->set_should_run(test_case->should_run() || is_selected);
05987     }
05988   }
05989   return num_selected_tests;
05990 }
05991 
05992 // Prints the given C-string on a single line by replacing all '\n'
05993 // characters with string "\\n".  If the output takes more than
05994 // max_length characters, only prints the first max_length characters
05995 // and "...".
05996 static void PrintOnOneLine(const char* str, int max_length) {
05997   if (str != NULL) {
05998     for (int i = 0; *str != '\0'; ++str) {
05999       if (i >= max_length) {
06000         printf("...");
06001         break;
06002       }
06003       if (*str == '\n') {
06004         printf("\\n");
06005         i += 2;
06006       } else {
06007         printf("%c", *str);
06008         ++i;
06009       }
06010     }
06011   }
06012 }
06013 
06014 // Prints the names of the tests matching the user-specified filter flag.
06015 void UnitTestImpl::ListTestsMatchingFilter() {
06016   // Print at most this many characters for each type/value parameter.
06017   const int kMaxParamLength = 250;
06018 
06019   for (size_t i = 0; i < test_cases_.size(); i++) {
06020     const TestCase* const test_case = test_cases_[i];
06021     bool printed_test_case_name = false;
06022 
06023     for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
06024       const TestInfo* const test_info =
06025           test_case->test_info_list()[j];
06026       if (test_info->matches_filter_) {
06027         if (!printed_test_case_name) {
06028           printed_test_case_name = true;
06029           printf("%s.", test_case->name());
06030           if (test_case->type_param() != NULL) {
06031             printf("  # %s = ", kTypeParamLabel);
06032             // We print the type parameter on a single line to make
06033             // the output easy to parse by a program.
06034             PrintOnOneLine(test_case->type_param(), kMaxParamLength);
06035           }
06036           printf("\n");
06037         }
06038         printf("  %s", test_info->name());
06039         if (test_info->value_param() != NULL) {
06040           printf("  # %s = ", kValueParamLabel);
06041           // We print the value parameter on a single line to make the
06042           // output easy to parse by a program.
06043           PrintOnOneLine(test_info->value_param(), kMaxParamLength);
06044         }
06045         printf("\n");
06046       }
06047     }
06048   }
06049   fflush(stdout);
06050 }
06051 
06052 // Sets the OS stack trace getter.
06053 //
06054 // Does nothing if the input and the current OS stack trace getter are
06055 // the same; otherwise, deletes the old getter and makes the input the
06056 // current getter.
06057 void UnitTestImpl::set_os_stack_trace_getter(
06058     OsStackTraceGetterInterface* getter) {
06059   if (os_stack_trace_getter_ != getter) {
06060     delete os_stack_trace_getter_;
06061     os_stack_trace_getter_ = getter;
06062   }
06063 }
06064 
06065 // Returns the current OS stack trace getter if it is not NULL;
06066 // otherwise, creates an OsStackTraceGetter, makes it the current
06067 // getter, and returns it.
06068 OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
06069   if (os_stack_trace_getter_ == NULL) {
06070     os_stack_trace_getter_ = new OsStackTraceGetter;
06071   }
06072 
06073   return os_stack_trace_getter_;
06074 }
06075 
06076 // Returns the TestResult for the test that's currently running, or
06077 // the TestResult for the ad hoc test if no test is running.
06078 TestResult* UnitTestImpl::current_test_result() {
06079   return current_test_info_ ?
06080       &(current_test_info_->result_) : &ad_hoc_test_result_;
06081 }
06082 
06083 // Shuffles all test cases, and the tests within each test case,
06084 // making sure that death tests are still run first.
06085 void UnitTestImpl::ShuffleTests() {
06086   // Shuffles the death test cases.
06087   ShuffleRange(random(), 0, last_death_test_case_ + 1, &test_case_indices_);
06088 
06089   // Shuffles the non-death test cases.
06090   ShuffleRange(random(), last_death_test_case_ + 1,
06091                static_cast<int>(test_cases_.size()), &test_case_indices_);
06092 
06093   // Shuffles the tests inside each test case.
06094   for (size_t i = 0; i < test_cases_.size(); i++) {
06095     test_cases_[i]->ShuffleTests(random());
06096   }
06097 }
06098 
06099 // Restores the test cases and tests to their order before the first shuffle.
06100 void UnitTestImpl::UnshuffleTests() {
06101   for (size_t i = 0; i < test_cases_.size(); i++) {
06102     // Unshuffles the tests in each test case.
06103     test_cases_[i]->UnshuffleTests();
06104     // Resets the index of each test case.
06105     test_case_indices_[i] = static_cast<int>(i);
06106   }
06107 }
06108 
06109 // Returns the current OS stack trace as an std::string.
06110 //
06111 // The maximum number of stack frames to be included is specified by
06112 // the gtest_stack_trace_depth flag.  The skip_count parameter
06113 // specifies the number of top frames to be skipped, which doesn't
06114 // count against the number of frames to be included.
06115 //
06116 // For example, if Foo() calls Bar(), which in turn calls
06117 // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
06118 // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
06119 std::string GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/,
06120                                             int skip_count) {
06121   // We pass skip_count + 1 to skip this wrapper function in addition
06122   // to what the user really wants to skip.
06123   return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
06124 }
06125 
06126 // Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to
06127 // suppress unreachable code warnings.
06128 namespace {
06129 class ClassUniqueToAlwaysTrue {};
06130 }
06131 
06132 bool IsTrue(bool condition) { return condition; }
06133 
06134 bool AlwaysTrue() {
06135 #if GTEST_HAS_EXCEPTIONS
06136   // This condition is always false so AlwaysTrue() never actually throws,
06137   // but it makes the compiler think that it may throw.
06138   if (IsTrue(false))
06139     throw ClassUniqueToAlwaysTrue();
06140 #endif  // GTEST_HAS_EXCEPTIONS
06141   return true;
06142 }
06143 
06144 // If *pstr starts with the given prefix, modifies *pstr to be right
06145 // past the prefix and returns true; otherwise leaves *pstr unchanged
06146 // and returns false.  None of pstr, *pstr, and prefix can be NULL.
06147 bool SkipPrefix(const char* prefix, const char** pstr) {
06148   const size_t prefix_len = strlen(prefix);
06149   if (strncmp(*pstr, prefix, prefix_len) == 0) {
06150     *pstr += prefix_len;
06151     return true;
06152   }
06153   return false;
06154 }
06155 
06156 // Parses a string as a command line flag.  The string should have
06157 // the format "--flag=value".  When def_optional is true, the "=value"
06158 // part can be omitted.
06159 //
06160 // Returns the value of the flag, or NULL if the parsing failed.
06161 const char* ParseFlagValue(const char* str,
06162                            const char* flag,
06163                            bool def_optional) {
06164   // str and flag must not be NULL.
06165   if (str == NULL || flag == NULL) return NULL;
06166 
06167   // The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
06168   const std::string flag_str = std::string("--") + GTEST_FLAG_PREFIX_ + flag;
06169   const size_t flag_len = flag_str.length();
06170   if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;
06171 
06172   // Skips the flag name.
06173   const char* flag_end = str + flag_len;
06174 
06175   // When def_optional is true, it's OK to not have a "=value" part.
06176   if (def_optional && (flag_end[0] == '\0')) {
06177     return flag_end;
06178   }
06179 
06180   // If def_optional is true and there are more characters after the
06181   // flag name, or if def_optional is false, there must be a '=' after
06182   // the flag name.
06183   if (flag_end[0] != '=') return NULL;
06184 
06185   // Returns the string after "=".
06186   return flag_end + 1;
06187 }
06188 
06189 // Parses a string for a bool flag, in the form of either
06190 // "--flag=value" or "--flag".
06191 //
06192 // In the former case, the value is taken as true as long as it does
06193 // not start with '0', 'f', or 'F'.
06194 //
06195 // In the latter case, the value is taken as true.
06196 //
06197 // On success, stores the value of the flag in *value, and returns
06198 // true.  On failure, returns false without changing *value.
06199 bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
06200   // Gets the value of the flag as a string.
06201   const char* const value_str = ParseFlagValue(str, flag, true);
06202 
06203   // Aborts if the parsing failed.
06204   if (value_str == NULL) return false;
06205 
06206   // Converts the string value to a bool.
06207   *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
06208   return true;
06209 }
06210 
06211 // Parses a string for an Int32 flag, in the form of
06212 // "--flag=value".
06213 //
06214 // On success, stores the value of the flag in *value, and returns
06215 // true.  On failure, returns false without changing *value.
06216 bool ParseInt32Flag(const char* str, const char* flag, Int32* value) {
06217   // Gets the value of the flag as a string.
06218   const char* const value_str = ParseFlagValue(str, flag, false);
06219 
06220   // Aborts if the parsing failed.
06221   if (value_str == NULL) return false;
06222 
06223   // Sets *value to the value of the flag.
06224   return ParseInt32(Message() << "The value of flag --" << flag,
06225                     value_str, value);
06226 }
06227 
06228 // Parses a string for a string flag, in the form of
06229 // "--flag=value".
06230 //
06231 // On success, stores the value of the flag in *value, and returns
06232 // true.  On failure, returns false without changing *value.
06233 bool ParseStringFlag(const char* str, const char* flag, std::string* value) {
06234   // Gets the value of the flag as a string.
06235   const char* const value_str = ParseFlagValue(str, flag, false);
06236 
06237   // Aborts if the parsing failed.
06238   if (value_str == NULL) return false;
06239 
06240   // Sets *value to the value of the flag.
06241   *value = value_str;
06242   return true;
06243 }
06244 
06245 // Determines whether a string has a prefix that Google Test uses for its
06246 // flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.
06247 // If Google Test detects that a command line flag has its prefix but is not
06248 // recognized, it will print its help message. Flags starting with
06249 // GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
06250 // internal flags and do not trigger the help message.
06251 static bool HasGoogleTestFlagPrefix(const char* str) {
06252   return (SkipPrefix("--", &str) ||
06253           SkipPrefix("-", &str) ||
06254           SkipPrefix("/", &str)) &&
06255          !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
06256          (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
06257           SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str));
06258 }
06259 
06260 // Prints a string containing code-encoded text.  The following escape
06261 // sequences can be used in the string to control the text color:
06262 //
06263 //   @@    prints a single '@' character.
06264 //   @R    changes the color to red.
06265 //   @G    changes the color to green.
06266 //   @Y    changes the color to yellow.
06267 //   @D    changes to the default terminal text color.
06268 //
06269 // TODO(wan@google.com): Write tests for this once we add stdout
06270 // capturing to Google Test.
06271 static void PrintColorEncoded(const char* str) {
06272   GTestColor color = COLOR_DEFAULT;  // The current color.
06273 
06274   // Conceptually, we split the string into segments divided by escape
06275   // sequences.  Then we print one segment at a time.  At the end of
06276   // each iteration, the str pointer advances to the beginning of the
06277   // next segment.
06278   for (;;) {
06279     const char* p = strchr(str, '@');
06280     if (p == NULL) {
06281       ColoredPrintf(color, "%s", str);
06282       return;
06283     }
06284 
06285     ColoredPrintf(color, "%s", std::string(str, p).c_str());
06286 
06287     const char ch = p[1];
06288     str = p + 2;
06289     if (ch == '@') {
06290       ColoredPrintf(color, "@");
06291     } else if (ch == 'D') {
06292       color = COLOR_DEFAULT;
06293     } else if (ch == 'R') {
06294       color = COLOR_RED;
06295     } else if (ch == 'G') {
06296       color = COLOR_GREEN;
06297     } else if (ch == 'Y') {
06298       color = COLOR_YELLOW;
06299     } else {
06300       --str;
06301     }
06302   }
06303 }
06304 
06305 static const char kColorEncodedHelpMessage[] =
06306 "This program contains tests written using " GTEST_NAME_ ". You can use the\n"
06307 "following command line flags to control its behavior:\n"
06308 "\n"
06309 "Test Selection:\n"
06310 "  @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n"
06311 "      List the names of all tests instead of running them. The name of\n"
06312 "      TEST(Foo, Bar) is \"Foo.Bar\".\n"
06313 "  @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS"
06314     "[@G-@YNEGATIVE_PATTERNS]@D\n"
06315 "      Run only the tests whose name matches one of the positive patterns but\n"
06316 "      none of the negative patterns. '?' matches any single character; '*'\n"
06317 "      matches any substring; ':' separates two patterns.\n"
06318 "  @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n"
06319 "      Run all disabled tests too.\n"
06320 "\n"
06321 "Test Execution:\n"
06322 "  @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n"
06323 "      Run the tests repeatedly; use a negative count to repeat forever.\n"
06324 "  @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n"
06325 "      Randomize tests' orders on every iteration.\n"
06326 "  @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n"
06327 "      Random number seed to use for shuffling test orders (between 1 and\n"
06328 "      99999, or 0 to use a seed based on the current time).\n"
06329 "\n"
06330 "Test Output:\n"
06331 "  @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
06332 "      Enable/disable colored output. The default is @Gauto@D.\n"
06333 "  -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n"
06334 "      Don't print the elapsed time of each test.\n"
06335 "  @G--" GTEST_FLAG_PREFIX_ "output=xml@Y[@G:@YDIRECTORY_PATH@G"
06336     GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n"
06337 "      Generate an XML report in the given directory or with the given file\n"
06338 "      name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n"
06339 #if GTEST_CAN_STREAM_RESULTS_
06340 "  @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n"
06341 "      Stream test results to the given server.\n"
06342 #endif  // GTEST_CAN_STREAM_RESULTS_
06343 "\n"
06344 "Assertion Behavior:\n"
06345 #if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
06346 "  @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
06347 "      Set the default death test style.\n"
06348 #endif  // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
06349 "  @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n"
06350 "      Turn assertion failures into debugger break-points.\n"
06351 "  @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n"
06352 "      Turn assertion failures into C++ exceptions.\n"
06353 "  @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n"
06354 "      Do not report exceptions as test failures. Instead, allow them\n"
06355 "      to crash the program or throw a pop-up (on Windows).\n"
06356 "\n"
06357 "Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set "
06358     "the corresponding\n"
06359 "environment variable of a flag (all letters in upper-case). For example, to\n"
06360 "disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_
06361     "color=no@D or set\n"
06362 "the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n"
06363 "\n"
06364 "For more information, please read the " GTEST_NAME_ " documentation at\n"
06365 "@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n"
06366 "(not one in your own code or tests), please report it to\n"
06367 "@G<" GTEST_DEV_EMAIL_ ">@D.\n";
06368 
06369 // Parses the command line for Google Test flags, without initializing
06370 // other parts of Google Test.  The type parameter CharType can be
06371 // instantiated to either char or wchar_t.
06372 template <typename CharType>
06373 void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
06374   for (int i = 1; i < *argc; i++) {
06375     const std::string arg_string = StreamableToString(argv[i]);
06376     const char* const arg = arg_string.c_str();
06377 
06378     using internal::ParseBoolFlag;
06379     using internal::ParseInt32Flag;
06380     using internal::ParseStringFlag;
06381 
06382     // Do we see a Google Test flag?
06383     if (ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,
06384                       &GTEST_FLAG(also_run_disabled_tests)) ||
06385         ParseBoolFlag(arg, kBreakOnFailureFlag,
06386                       &GTEST_FLAG(break_on_failure)) ||
06387         ParseBoolFlag(arg, kCatchExceptionsFlag,
06388                       &GTEST_FLAG(catch_exceptions)) ||
06389         ParseStringFlag(arg, kColorFlag, &GTEST_FLAG(color)) ||
06390         ParseStringFlag(arg, kDeathTestStyleFlag,
06391                         &GTEST_FLAG(death_test_style)) ||
06392         ParseBoolFlag(arg, kDeathTestUseFork,
06393                       &GTEST_FLAG(death_test_use_fork)) ||
06394         ParseStringFlag(arg, kFilterFlag, &GTEST_FLAG(filter)) ||
06395         ParseStringFlag(arg, kInternalRunDeathTestFlag,
06396                         &GTEST_FLAG(internal_run_death_test)) ||
06397         ParseBoolFlag(arg, kListTestsFlag, &GTEST_FLAG(list_tests)) ||
06398         ParseStringFlag(arg, kOutputFlag, &GTEST_FLAG(output)) ||
06399         ParseBoolFlag(arg, kPrintTimeFlag, &GTEST_FLAG(print_time)) ||
06400         ParseInt32Flag(arg, kRandomSeedFlag, &GTEST_FLAG(random_seed)) ||
06401         ParseInt32Flag(arg, kRepeatFlag, &GTEST_FLAG(repeat)) ||
06402         ParseBoolFlag(arg, kShuffleFlag, &GTEST_FLAG(shuffle)) ||
06403         ParseInt32Flag(arg, kStackTraceDepthFlag,
06404                        &GTEST_FLAG(stack_trace_depth)) ||
06405         ParseStringFlag(arg, kStreamResultToFlag,
06406                         &GTEST_FLAG(stream_result_to)) ||
06407         ParseBoolFlag(arg, kThrowOnFailureFlag,
06408                       &GTEST_FLAG(throw_on_failure))
06409         ) {
06410       // Yes.  Shift the remainder of the argv list left by one.  Note
06411       // that argv has (*argc + 1) elements, the last one always being
06412       // NULL.  The following loop moves the trailing NULL element as
06413       // well.
06414       for (int j = i; j != *argc; j++) {
06415         argv[j] = argv[j + 1];
06416       }
06417 
06418       // Decrements the argument count.
06419       (*argc)--;
06420 
06421       // We also need to decrement the iterator as we just removed
06422       // an element.
06423       i--;
06424     } else if (arg_string == "--help" || arg_string == "-h" ||
06425                arg_string == "-?" || arg_string == "/?" ||
06426                HasGoogleTestFlagPrefix(arg)) {
06427       // Both help flag and unrecognized Google Test flags (excluding
06428       // internal ones) trigger help display.
06429       g_help_flag = true;
06430     }
06431   }
06432 
06433   if (g_help_flag) {
06434     // We print the help here instead of in RUN_ALL_TESTS(), as the
06435     // latter may not be called at all if the user is using Google
06436     // Test with another testing framework.
06437     PrintColorEncoded(kColorEncodedHelpMessage);
06438   }
06439 }
06440 
06441 // Parses the command line for Google Test flags, without initializing
06442 // other parts of Google Test.
06443 void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
06444   ParseGoogleTestFlagsOnlyImpl(argc, argv);
06445 }
06446 void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {
06447   ParseGoogleTestFlagsOnlyImpl(argc, argv);
06448 }
06449 
06450 // The internal implementation of InitGoogleTest().
06451 //
06452 // The type parameter CharType can be instantiated to either char or
06453 // wchar_t.
06454 template <typename CharType>
06455 void InitGoogleTestImpl(int* argc, CharType** argv) {
06456   g_init_gtest_count++;
06457 
06458   // We don't want to run the initialization code twice.
06459   if (g_init_gtest_count != 1) return;
06460 
06461   if (*argc <= 0) return;
06462 
06463   internal::g_executable_path = internal::StreamableToString(argv[0]);
06464 
06465 #if GTEST_HAS_DEATH_TEST
06466 
06467   g_argvs.clear();
06468   for (int i = 0; i != *argc; i++) {
06469     g_argvs.push_back(StreamableToString(argv[i]));
06470   }
06471 
06472 #endif  // GTEST_HAS_DEATH_TEST
06473 
06474   ParseGoogleTestFlagsOnly(argc, argv);
06475   GetUnitTestImpl()->PostFlagParsingInit();
06476 }
06477 
06478 }  // namespace internal
06479 
06480 // Initializes Google Test.  This must be called before calling
06481 // RUN_ALL_TESTS().  In particular, it parses a command line for the
06482 // flags that Google Test recognizes.  Whenever a Google Test flag is
06483 // seen, it is removed from argv, and *argc is decremented.
06484 //
06485 // No value is returned.  Instead, the Google Test flag variables are
06486 // updated.
06487 //
06488 // Calling the function for the second time has no user-visible effect.
06489 void InitGoogleTest(int* argc, char** argv) {
06490   internal::InitGoogleTestImpl(argc, argv);
06491 }
06492 
06493 // This overloaded version can be used in Windows programs compiled in
06494 // UNICODE mode.
06495 void InitGoogleTest(int* argc, wchar_t** argv) {
06496   internal::InitGoogleTestImpl(argc, argv);
06497 }
06498 
06499 }  // namespace testing
06500 // Copyright 2005, Google Inc.
06501 // All rights reserved.
06502 //
06503 // Redistribution and use in source and binary forms, with or without
06504 // modification, are permitted provided that the following conditions are
06505 // met:
06506 //
06507 //     * Redistributions of source code must retain the above copyright
06508 // notice, this list of conditions and the following disclaimer.
06509 //     * Redistributions in binary form must reproduce the above
06510 // copyright notice, this list of conditions and the following disclaimer
06511 // in the documentation and/or other materials provided with the
06512 // distribution.
06513 //     * Neither the name of Google Inc. nor the names of its
06514 // contributors may be used to endorse or promote products derived from
06515 // this software without specific prior written permission.
06516 //
06517 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
06518 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
06519 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
06520 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
06521 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
06522 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
06523 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
06524 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
06525 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
06526 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
06527 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
06528 //
06529 // Author: wan@google.com (Zhanyong Wan), vladl@google.com (Vlad Losev)
06530 //
06531 // This file implements death tests.
06532 
06533 
06534 #if GTEST_HAS_DEATH_TEST
06535 
06536 # if GTEST_OS_MAC
06537 #  include <crt_externs.h>
06538 # endif  // GTEST_OS_MAC
06539 
06540 # include <errno.h>
06541 # include <fcntl.h>
06542 # include <limits.h>
06543 
06544 # if GTEST_OS_LINUX
06545 #  include <signal.h>
06546 # endif  // GTEST_OS_LINUX
06547 
06548 # include <stdarg.h>
06549 
06550 # if GTEST_OS_WINDOWS
06551 #  include <windows.h>
06552 # else
06553 #  include <sys/mman.h>
06554 #  include <sys/wait.h>
06555 # endif  // GTEST_OS_WINDOWS
06556 
06557 # if GTEST_OS_QNX
06558 #  include <spawn.h>
06559 # endif  // GTEST_OS_QNX
06560 
06561 #endif  // GTEST_HAS_DEATH_TEST
06562 
06563 
06564 // Indicates that this translation unit is part of Google Test's
06565 // implementation.  It must come before gtest-internal-inl.h is
06566 // included, or there will be a compiler error.  This trick is to
06567 // prevent a user from accidentally including gtest-internal-inl.h in
06568 // his code.
06569 #define GTEST_IMPLEMENTATION_ 1
06570 #undef GTEST_IMPLEMENTATION_
06571 
06572 namespace testing {
06573 
06574 // Constants.
06575 
06576 // The default death test style.
06577 static const char kDefaultDeathTestStyle[] = "fast";
06578 
06579 GTEST_DEFINE_string_(
06580     death_test_style,
06581     internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle),
06582     "Indicates how to run a death test in a forked child process: "
06583     "\"threadsafe\" (child process re-executes the test binary "
06584     "from the beginning, running only the specific death test) or "
06585     "\"fast\" (child process runs the death test immediately "
06586     "after forking).");
06587 
06588 GTEST_DEFINE_bool_(
06589     death_test_use_fork,
06590     internal::BoolFromGTestEnv("death_test_use_fork", false),
06591     "Instructs to use fork()/_exit() instead of clone() in death tests. "
06592     "Ignored and always uses fork() on POSIX systems where clone() is not "
06593     "implemented. Useful when running under valgrind or similar tools if "
06594     "those do not support clone(). Valgrind 3.3.1 will just fail if "
06595     "it sees an unsupported combination of clone() flags. "
06596     "It is not recommended to use this flag w/o valgrind though it will "
06597     "work in 99% of the cases. Once valgrind is fixed, this flag will "
06598     "most likely be removed.");
06599 
06600 namespace internal {
06601 GTEST_DEFINE_string_(
06602     internal_run_death_test, "",
06603     "Indicates the file, line number, temporal index of "
06604     "the single death test to run, and a file descriptor to "
06605     "which a success code may be sent, all separated by "
06606     "the '|' characters.  This flag is specified if and only if the current "
06607     "process is a sub-process launched for running a thread-safe "
06608     "death test.  FOR INTERNAL USE ONLY.");
06609 }  // namespace internal
06610 
06611 #if GTEST_HAS_DEATH_TEST
06612 
06613 namespace internal {
06614 
06615 // Valid only for fast death tests. Indicates the code is running in the
06616 // child process of a fast style death test.
06617 static bool g_in_fast_death_test_child = false;
06618 
06619 // Returns a Boolean value indicating whether the caller is currently
06620 // executing in the context of the death test child process.  Tools such as
06621 // Valgrind heap checkers may need this to modify their behavior in death
06622 // tests.  IMPORTANT: This is an internal utility.  Using it may break the
06623 // implementation of death tests.  User code MUST NOT use it.
06624 bool InDeathTestChild() {
06625 # if GTEST_OS_WINDOWS
06626 
06627   // On Windows, death tests are thread-safe regardless of the value of the
06628   // death_test_style flag.
06629   return !GTEST_FLAG(internal_run_death_test).empty();
06630 
06631 # else
06632 
06633   if (GTEST_FLAG(death_test_style) == "threadsafe")
06634     return !GTEST_FLAG(internal_run_death_test).empty();
06635   else
06636     return g_in_fast_death_test_child;
06637 #endif
06638 }
06639 
06640 }  // namespace internal
06641 
06642 // ExitedWithCode constructor.
06643 ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {
06644 }
06645 
06646 // ExitedWithCode function-call operator.
06647 bool ExitedWithCode::operator()(int exit_status) const {
06648 # if GTEST_OS_WINDOWS
06649 
06650   return exit_status == exit_code_;
06651 
06652 # else
06653 
06654   return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;
06655 
06656 # endif  // GTEST_OS_WINDOWS
06657 }
06658 
06659 # if !GTEST_OS_WINDOWS
06660 // KilledBySignal constructor.
06661 KilledBySignal::KilledBySignal(int signum) : signum_(signum) {
06662 }
06663 
06664 // KilledBySignal function-call operator.
06665 bool KilledBySignal::operator()(int exit_status) const {
06666   return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;
06667 }
06668 # endif  // !GTEST_OS_WINDOWS
06669 
06670 namespace internal {
06671 
06672 // Utilities needed for death tests.
06673 
06674 // Generates a textual description of a given exit code, in the format
06675 // specified by wait(2).
06676 static std::string ExitSummary(int exit_code) {
06677   Message m;
06678 
06679 # if GTEST_OS_WINDOWS
06680 
06681   m << "Exited with exit status " << exit_code;
06682 
06683 # else
06684 
06685   if (WIFEXITED(exit_code)) {
06686     m << "Exited with exit status " << WEXITSTATUS(exit_code);
06687   } else if (WIFSIGNALED(exit_code)) {
06688     m << "Terminated by signal " << WTERMSIG(exit_code);
06689   }
06690 #  ifdef WCOREDUMP
06691   if (WCOREDUMP(exit_code)) {
06692     m << " (core dumped)";
06693   }
06694 #  endif
06695 # endif  // GTEST_OS_WINDOWS
06696 
06697   return m.GetString();
06698 }
06699 
06700 // Returns true if exit_status describes a process that was terminated
06701 // by a signal, or exited normally with a nonzero exit code.
06702 bool ExitedUnsuccessfully(int exit_status) {
06703   return !ExitedWithCode(0)(exit_status);
06704 }
06705 
06706 # if !GTEST_OS_WINDOWS
06707 // Generates a textual failure message when a death test finds more than
06708 // one thread running, or cannot determine the number of threads, prior
06709 // to executing the given statement.  It is the responsibility of the
06710 // caller not to pass a thread_count of 1.
06711 static std::string DeathTestThreadWarning(size_t thread_count) {
06712   Message msg;
06713   msg << "Death tests use fork(), which is unsafe particularly"
06714       << " in a threaded context. For this test, " << GTEST_NAME_ << " ";
06715   if (thread_count == 0)
06716     msg << "couldn't detect the number of threads.";
06717   else
06718     msg << "detected " << thread_count << " threads.";
06719   return msg.GetString();
06720 }
06721 # endif  // !GTEST_OS_WINDOWS
06722 
06723 // Flag characters for reporting a death test that did not die.
06724 static const char kDeathTestLived = 'L';
06725 static const char kDeathTestReturned = 'R';
06726 static const char kDeathTestThrew = 'T';
06727 static const char kDeathTestInternalError = 'I';
06728 
06729 // An enumeration describing all of the possible ways that a death test can
06730 // conclude.  DIED means that the process died while executing the test
06731 // code; LIVED means that process lived beyond the end of the test code;
06732 // RETURNED means that the test statement attempted to execute a return
06733 // statement, which is not allowed; THREW means that the test statement
06734 // returned control by throwing an exception.  IN_PROGRESS means the test
06735 // has not yet concluded.
06736 // TODO(vladl@google.com): Unify names and possibly values for
06737 // AbortReason, DeathTestOutcome, and flag characters above.
06738 enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW };
06739 
06740 // Routine for aborting the program which is safe to call from an
06741 // exec-style death test child process, in which case the error
06742 // message is propagated back to the parent process.  Otherwise, the
06743 // message is simply printed to stderr.  In either case, the program
06744 // then exits with status 1.
06745 void DeathTestAbort(const std::string& message) {
06746   // On a POSIX system, this function may be called from a threadsafe-style
06747   // death test child process, which operates on a very small stack.  Use
06748   // the heap for any additional non-minuscule memory requirements.
06749   const InternalRunDeathTestFlag* const flag =
06750       GetUnitTestImpl()->internal_run_death_test_flag();
06751   if (flag != NULL) {
06752     FILE* parent = posix::FDOpen(flag->write_fd(), "w");
06753     fputc(kDeathTestInternalError, parent);
06754     fprintf(parent, "%s", message.c_str());
06755     fflush(parent);
06756     _exit(1);
06757   } else {
06758     fprintf(stderr, "%s", message.c_str());
06759     fflush(stderr);
06760     posix::Abort();
06761   }
06762 }
06763 
06764 // A replacement for CHECK that calls DeathTestAbort if the assertion
06765 // fails.
06766 # define GTEST_DEATH_TEST_CHECK_(expression) \
06767   do { \
06768     if (!::testing::internal::IsTrue(expression)) { \
06769       DeathTestAbort( \
06770           ::std::string("CHECK failed: File ") + __FILE__ +  ", line " \
06771           + ::testing::internal::StreamableToString(__LINE__) + ": " \
06772           + #expression); \
06773     } \
06774   } while (::testing::internal::AlwaysFalse())
06775 
06776 // This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for
06777 // evaluating any system call that fulfills two conditions: it must return
06778 // -1 on failure, and set errno to EINTR when it is interrupted and
06779 // should be tried again.  The macro expands to a loop that repeatedly
06780 // evaluates the expression as long as it evaluates to -1 and sets
06781 // errno to EINTR.  If the expression evaluates to -1 but errno is
06782 // something other than EINTR, DeathTestAbort is called.
06783 # define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
06784   do { \
06785     int gtest_retval; \
06786     do { \
06787       gtest_retval = (expression); \
06788     } while (gtest_retval == -1 && errno == EINTR); \
06789     if (gtest_retval == -1) { \
06790       DeathTestAbort( \
06791           ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
06792           + ::testing::internal::StreamableToString(__LINE__) + ": " \
06793           + #expression + " != -1"); \
06794     } \
06795   } while (::testing::internal::AlwaysFalse())
06796 
06797 // Returns the message describing the last system error in errno.
06798 std::string GetLastErrnoDescription() {
06799     return errno == 0 ? "" : posix::StrError(errno);
06800 }
06801 
06802 // This is called from a death test parent process to read a failure
06803 // message from the death test child process and log it with the FATAL
06804 // severity. On Windows, the message is read from a pipe handle. On other
06805 // platforms, it is read from a file descriptor.
06806 static void FailFromInternalError(int fd) {
06807   Message error;
06808   char buffer[256];
06809   int num_read;
06810 
06811   do {
06812     while ((num_read = posix::Read(fd, buffer, 255)) > 0) {
06813       buffer[num_read] = '\0';
06814       error << buffer;
06815     }
06816   } while (num_read == -1 && errno == EINTR);
06817 
06818   if (num_read == 0) {
06819     GTEST_LOG_(FATAL) << error.GetString();
06820   } else {
06821     const int last_error = errno;
06822     GTEST_LOG_(FATAL) << "Error while reading death test internal: "
06823                       << GetLastErrnoDescription() << " [" << last_error << "]";
06824   }
06825 }
06826 
06827 // Death test constructor.  Increments the running death test count
06828 // for the current test.
06829 DeathTest::DeathTest() {
06830   TestInfo* const info = GetUnitTestImpl()->current_test_info();
06831   if (info == NULL) {
06832     DeathTestAbort("Cannot run a death test outside of a TEST or "
06833                    "TEST_F construct");
06834   }
06835 }
06836 
06837 // Creates and returns a death test by dispatching to the current
06838 // death test factory.
06839 bool DeathTest::Create(const char* statement, const RE* regex,
06840                        const char* file, int line, DeathTest** test) {
06841   return GetUnitTestImpl()->death_test_factory()->Create(
06842       statement, regex, file, line, test);
06843 }
06844 
06845 const char* DeathTest::LastMessage() {
06846   return last_death_test_message_.c_str();
06847 }
06848 
06849 void DeathTest::set_last_death_test_message(const std::string& message) {
06850   last_death_test_message_ = message;
06851 }
06852 
06853 std::string DeathTest::last_death_test_message_;
06854 
06855 // Provides cross platform implementation for some death functionality.
06856 class DeathTestImpl : public DeathTest {
06857  protected:
06858   DeathTestImpl(const char* a_statement, const RE* a_regex)
06859       : statement_(a_statement),
06860         regex_(a_regex),
06861         spawned_(false),
06862         status_(-1),
06863         outcome_(IN_PROGRESS),
06864         read_fd_(-1),
06865         write_fd_(-1) {}
06866 
06867   // read_fd_ is expected to be closed and cleared by a derived class.
06868   ~DeathTestImpl() { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); }
06869 
06870   void Abort(AbortReason reason);
06871   virtual bool Passed(bool status_ok);
06872 
06873   const char* statement() const { return statement_; }
06874   const RE* regex() const { return regex_; }
06875   bool spawned() const { return spawned_; }
06876   void set_spawned(bool is_spawned) { spawned_ = is_spawned; }
06877   int status() const { return status_; }
06878   void set_status(int a_status) { status_ = a_status; }
06879   DeathTestOutcome outcome() const { return outcome_; }
06880   void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; }
06881   int read_fd() const { return read_fd_; }
06882   void set_read_fd(int fd) { read_fd_ = fd; }
06883   int write_fd() const { return write_fd_; }
06884   void set_write_fd(int fd) { write_fd_ = fd; }
06885 
06886   // Called in the parent process only. Reads the result code of the death
06887   // test child process via a pipe, interprets it to set the outcome_
06888   // member, and closes read_fd_.  Outputs diagnostics and terminates in
06889   // case of unexpected codes.
06890   void ReadAndInterpretStatusByte();
06891 
06892  private:
06893   // The textual content of the code this object is testing.  This class
06894   // doesn't own this string and should not attempt to delete it.
06895   const char* const statement_;
06896   // The regular expression which test output must match.  DeathTestImpl
06897   // doesn't own this object and should not attempt to delete it.
06898   const RE* const regex_;
06899   // True if the death test child process has been successfully spawned.
06900   bool spawned_;
06901   // The exit status of the child process.
06902   int status_;
06903   // How the death test concluded.
06904   DeathTestOutcome outcome_;
06905   // Descriptor to the read end of the pipe to the child process.  It is
06906   // always -1 in the child process.  The child keeps its write end of the
06907   // pipe in write_fd_.
06908   int read_fd_;
06909   // Descriptor to the child's write end of the pipe to the parent process.
06910   // It is always -1 in the parent process.  The parent keeps its end of the
06911   // pipe in read_fd_.
06912   int write_fd_;
06913 };
06914 
06915 // Called in the parent process only. Reads the result code of the death
06916 // test child process via a pipe, interprets it to set the outcome_
06917 // member, and closes read_fd_.  Outputs diagnostics and terminates in
06918 // case of unexpected codes.
06919 void DeathTestImpl::ReadAndInterpretStatusByte() {
06920   char flag;
06921   int bytes_read;
06922 
06923   // The read() here blocks until data is available (signifying the
06924   // failure of the death test) or until the pipe is closed (signifying
06925   // its success), so it's okay to call this in the parent before
06926   // the child process has exited.
06927   do {
06928     bytes_read = posix::Read(read_fd(), &flag, 1);
06929   } while (bytes_read == -1 && errno == EINTR);
06930 
06931   if (bytes_read == 0) {
06932     set_outcome(DIED);
06933   } else if (bytes_read == 1) {
06934     switch (flag) {
06935       case kDeathTestReturned:
06936         set_outcome(RETURNED);
06937         break;
06938       case kDeathTestThrew:
06939         set_outcome(THREW);
06940         break;
06941       case kDeathTestLived:
06942         set_outcome(LIVED);
06943         break;
06944       case kDeathTestInternalError:
06945         FailFromInternalError(read_fd());  // Does not return.
06946         break;
06947       default:
06948         GTEST_LOG_(FATAL) << "Death test child process reported "
06949                           << "unexpected status byte ("
06950                           << static_cast<unsigned int>(flag) << ")";
06951     }
06952   } else {
06953     GTEST_LOG_(FATAL) << "Read from death test child process failed: "
06954                       << GetLastErrnoDescription();
06955   }
06956   GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd()));
06957   set_read_fd(-1);
06958 }
06959 
06960 // Signals that the death test code which should have exited, didn't.
06961 // Should be called only in a death test child process.
06962 // Writes a status byte to the child's status file descriptor, then
06963 // calls _exit(1).
06964 void DeathTestImpl::Abort(AbortReason reason) {
06965   // The parent process considers the death test to be a failure if
06966   // it finds any data in our pipe.  So, here we write a single flag byte
06967   // to the pipe, then exit.
06968   const char status_ch =
06969       reason == TEST_DID_NOT_DIE ? kDeathTestLived :
06970       reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned;
06971 
06972   GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1));
06973   // We are leaking the descriptor here because on some platforms (i.e.,
06974   // when built as Windows DLL), destructors of global objects will still
06975   // run after calling _exit(). On such systems, write_fd_ will be
06976   // indirectly closed from the destructor of UnitTestImpl, causing double
06977   // close if it is also closed here. On debug configurations, double close
06978   // may assert. As there are no in-process buffers to flush here, we are
06979   // relying on the OS to close the descriptor after the process terminates
06980   // when the destructors are not run.
06981   _exit(1);  // Exits w/o any normal exit hooks (we were supposed to crash)
06982 }
06983 
06984 // Returns an indented copy of stderr output for a death test.
06985 // This makes distinguishing death test output lines from regular log lines
06986 // much easier.
06987 static ::std::string FormatDeathTestOutput(const ::std::string& output) {
06988   ::std::string ret;
06989   for (size_t at = 0; ; ) {
06990     const size_t line_end = output.find('\n', at);
06991     ret += "[  DEATH   ] ";
06992     if (line_end == ::std::string::npos) {
06993       ret += output.substr(at);
06994       break;
06995     }
06996     ret += output.substr(at, line_end + 1 - at);
06997     at = line_end + 1;
06998   }
06999   return ret;
07000 }
07001 
07002 // Assesses the success or failure of a death test, using both private
07003 // members which have previously been set, and one argument:
07004 //
07005 // Private data members:
07006 //   outcome:  An enumeration describing how the death test
07007 //             concluded: DIED, LIVED, THREW, or RETURNED.  The death test
07008 //             fails in the latter three cases.
07009 //   status:   The exit status of the child process. On *nix, it is in the
07010 //             in the format specified by wait(2). On Windows, this is the
07011 //             value supplied to the ExitProcess() API or a numeric code
07012 //             of the exception that terminated the program.
07013 //   regex:    A regular expression object to be applied to
07014 //             the test's captured standard error output; the death test
07015 //             fails if it does not match.
07016 //
07017 // Argument:
07018 //   status_ok: true if exit_status is acceptable in the context of
07019 //              this particular death test, which fails if it is false
07020 //
07021 // Returns true iff all of the above conditions are met.  Otherwise, the
07022 // first failing condition, in the order given above, is the one that is
07023 // reported. Also sets the last death test message string.
07024 bool DeathTestImpl::Passed(bool status_ok) {
07025   if (!spawned())
07026     return false;
07027 
07028   const std::string error_message = GetCapturedStderr();
07029 
07030   bool success = false;
07031   Message buffer;
07032 
07033   buffer << "Death test: " << statement() << "\n";
07034   switch (outcome()) {
07035     case LIVED:
07036       buffer << "    Result: failed to die.\n"
07037              << " Error msg:\n" << FormatDeathTestOutput(error_message);
07038       break;
07039     case THREW:
07040       buffer << "    Result: threw an exception.\n"
07041              << " Error msg:\n" << FormatDeathTestOutput(error_message);
07042       break;
07043     case RETURNED:
07044       buffer << "    Result: illegal return in test statement.\n"
07045              << " Error msg:\n" << FormatDeathTestOutput(error_message);
07046       break;
07047     case DIED:
07048       if (status_ok) {
07049         const bool matched = RE::PartialMatch(error_message.c_str(), *regex());
07050         if (matched) {
07051           success = true;
07052         } else {
07053           buffer << "    Result: died but not with expected error.\n"
07054                  << "  Expected: " << regex()->pattern() << "\n"
07055                  << "Actual msg:\n" << FormatDeathTestOutput(error_message);
07056         }
07057       } else {
07058         buffer << "    Result: died but not with expected exit code:\n"
07059                << "            " << ExitSummary(status()) << "\n"
07060                << "Actual msg:\n" << FormatDeathTestOutput(error_message);
07061       }
07062       break;
07063     case IN_PROGRESS:
07064     default:
07065       GTEST_LOG_(FATAL)
07066           << "DeathTest::Passed somehow called before conclusion of test";
07067   }
07068 
07069   DeathTest::set_last_death_test_message(buffer.GetString());
07070   return success;
07071 }
07072 
07073 # if GTEST_OS_WINDOWS
07074 // WindowsDeathTest implements death tests on Windows. Due to the
07075 // specifics of starting new processes on Windows, death tests there are
07076 // always threadsafe, and Google Test considers the
07077 // --gtest_death_test_style=fast setting to be equivalent to
07078 // --gtest_death_test_style=threadsafe there.
07079 //
07080 // A few implementation notes:  Like the Linux version, the Windows
07081 // implementation uses pipes for child-to-parent communication. But due to
07082 // the specifics of pipes on Windows, some extra steps are required:
07083 //
07084 // 1. The parent creates a communication pipe and stores handles to both
07085 //    ends of it.
07086 // 2. The parent starts the child and provides it with the information
07087 //    necessary to acquire the handle to the write end of the pipe.
07088 // 3. The child acquires the write end of the pipe and signals the parent
07089 //    using a Windows event.
07090 // 4. Now the parent can release the write end of the pipe on its side. If
07091 //    this is done before step 3, the object's reference count goes down to
07092 //    0 and it is destroyed, preventing the child from acquiring it. The
07093 //    parent now has to release it, or read operations on the read end of
07094 //    the pipe will not return when the child terminates.
07095 // 5. The parent reads child's output through the pipe (outcome code and
07096 //    any possible error messages) from the pipe, and its stderr and then
07097 //    determines whether to fail the test.
07098 //
07099 // Note: to distinguish Win32 API calls from the local method and function
07100 // calls, the former are explicitly resolved in the global namespace.
07101 //
07102 class WindowsDeathTest : public DeathTestImpl {
07103  public:
07104   WindowsDeathTest(const char* a_statement,
07105                    const RE* a_regex,
07106                    const char* file,
07107                    int line)
07108       : DeathTestImpl(a_statement, a_regex), file_(file), line_(line) {}
07109 
07110   // All of these virtual functions are inherited from DeathTest.
07111   virtual int Wait();
07112   virtual TestRole AssumeRole();
07113 
07114  private:
07115   // The name of the file in which the death test is located.
07116   const char* const file_;
07117   // The line number on which the death test is located.
07118   const int line_;
07119   // Handle to the write end of the pipe to the child process.
07120   AutoHandle write_handle_;
07121   // Child process handle.
07122   AutoHandle child_handle_;
07123   // Event the child process uses to signal the parent that it has
07124   // acquired the handle to the write end of the pipe. After seeing this
07125   // event the parent can release its own handles to make sure its
07126   // ReadFile() calls return when the child terminates.
07127   AutoHandle event_handle_;
07128 };
07129 
07130 // Waits for the child in a death test to exit, returning its exit
07131 // status, or 0 if no child process exists.  As a side effect, sets the
07132 // outcome data member.
07133 int WindowsDeathTest::Wait() {
07134   if (!spawned())
07135     return 0;
07136 
07137   // Wait until the child either signals that it has acquired the write end
07138   // of the pipe or it dies.
07139   const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() };
07140   switch (::WaitForMultipleObjects(2,
07141                                    wait_handles,
07142                                    FALSE,  // Waits for any of the handles.
07143                                    INFINITE)) {
07144     case WAIT_OBJECT_0:
07145     case WAIT_OBJECT_0 + 1:
07146       break;
07147     default:
07148       GTEST_DEATH_TEST_CHECK_(false);  // Should not get here.
07149   }
07150 
07151   // The child has acquired the write end of the pipe or exited.
07152   // We release the handle on our side and continue.
07153   write_handle_.Reset();
07154   event_handle_.Reset();
07155 
07156   ReadAndInterpretStatusByte();
07157 
07158   // Waits for the child process to exit if it haven't already. This
07159   // returns immediately if the child has already exited, regardless of
07160   // whether previous calls to WaitForMultipleObjects synchronized on this
07161   // handle or not.
07162   GTEST_DEATH_TEST_CHECK_(
07163       WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(),
07164                                              INFINITE));
07165   DWORD status_code;
07166   GTEST_DEATH_TEST_CHECK_(
07167       ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE);
07168   child_handle_.Reset();
07169   set_status(static_cast<int>(status_code));
07170   return status();
07171 }
07172 
07173 // The AssumeRole process for a Windows death test.  It creates a child
07174 // process with the same executable as the current process to run the
07175 // death test.  The child process is given the --gtest_filter and
07176 // --gtest_internal_run_death_test flags such that it knows to run the
07177 // current death test only.
07178 DeathTest::TestRole WindowsDeathTest::AssumeRole() {
07179   const UnitTestImpl* const impl = GetUnitTestImpl();
07180   const InternalRunDeathTestFlag* const flag =
07181       impl->internal_run_death_test_flag();
07182   const TestInfo* const info = impl->current_test_info();
07183   const int death_test_index = info->result()->death_test_count();
07184 
07185   if (flag != NULL) {
07186     // ParseInternalRunDeathTestFlag() has performed all the necessary
07187     // processing.
07188     set_write_fd(flag->write_fd());
07189     return EXECUTE_TEST;
07190   }
07191 
07192   // WindowsDeathTest uses an anonymous pipe to communicate results of
07193   // a death test.
07194   SECURITY_ATTRIBUTES handles_are_inheritable = {
07195     sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };
07196   HANDLE read_handle, write_handle;
07197   GTEST_DEATH_TEST_CHECK_(
07198       ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable,
07199                    0)  // Default buffer size.
07200       != FALSE);
07201   set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle),
07202                                 O_RDONLY));
07203   write_handle_.Reset(write_handle);
07204   event_handle_.Reset(::CreateEvent(
07205       &handles_are_inheritable,
07206       TRUE,    // The event will automatically reset to non-signaled state.
07207       FALSE,   // The initial state is non-signalled.
07208       NULL));  // The even is unnamed.
07209   GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL);
07210   const std::string filter_flag =
07211       std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "=" +
07212       info->test_case_name() + "." + info->name();
07213   const std::string internal_flag =
07214       std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag +
07215       "=" + file_ + "|" + StreamableToString(line_) + "|" +
07216       StreamableToString(death_test_index) + "|" +
07217       StreamableToString(static_cast<unsigned int>(::GetCurrentProcessId())) +
07218       // size_t has the same width as pointers on both 32-bit and 64-bit
07219       // Windows platforms.
07220       // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx.
07221       "|" + StreamableToString(reinterpret_cast<size_t>(write_handle)) +
07222       "|" + StreamableToString(reinterpret_cast<size_t>(event_handle_.Get()));
07223 
07224   char executable_path[_MAX_PATH + 1];  // NOLINT
07225   GTEST_DEATH_TEST_CHECK_(
07226       _MAX_PATH + 1 != ::GetModuleFileNameA(NULL,
07227                                             executable_path,
07228                                             _MAX_PATH));
07229 
07230   std::string command_line =
07231       std::string(::GetCommandLineA()) + " " + filter_flag + " \"" +
07232       internal_flag + "\"";
07233 
07234   DeathTest::set_last_death_test_message("");
07235 
07236   CaptureStderr();
07237   // Flush the log buffers since the log streams are shared with the child.
07238   FlushInfoLog();
07239 
07240   // The child process will share the standard handles with the parent.
07241   STARTUPINFOA startup_info;
07242   memset(&startup_info, 0, sizeof(STARTUPINFO));
07243   startup_info.dwFlags = STARTF_USESTDHANDLES;
07244   startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE);
07245   startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE);
07246   startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE);
07247 
07248   PROCESS_INFORMATION process_info;
07249   GTEST_DEATH_TEST_CHECK_(::CreateProcessA(
07250       executable_path,
07251       const_cast<char*>(command_line.c_str()),
07252       NULL,   // Retuned process handle is not inheritable.
07253       NULL,   // Retuned thread handle is not inheritable.
07254       TRUE,   // Child inherits all inheritable handles (for write_handle_).
07255       0x0,    // Default creation flags.
07256       NULL,   // Inherit the parent's environment.
07257       UnitTest::GetInstance()->original_working_dir(),
07258       &startup_info,
07259       &process_info) != FALSE);
07260   child_handle_.Reset(process_info.hProcess);
07261   ::CloseHandle(process_info.hThread);
07262   set_spawned(true);
07263   return OVERSEE_TEST;
07264 }
07265 # else  // We are not on Windows.
07266 
07267 // ForkingDeathTest provides implementations for most of the abstract
07268 // methods of the DeathTest interface.  Only the AssumeRole method is
07269 // left undefined.
07270 class ForkingDeathTest : public DeathTestImpl {
07271  public:
07272   ForkingDeathTest(const char* statement, const RE* regex);
07273 
07274   // All of these virtual functions are inherited from DeathTest.
07275   virtual int Wait();
07276 
07277  protected:
07278   void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; }
07279 
07280  private:
07281   // PID of child process during death test; 0 in the child process itself.
07282   pid_t child_pid_;
07283 };
07284 
07285 // Constructs a ForkingDeathTest.
07286 ForkingDeathTest::ForkingDeathTest(const char* a_statement, const RE* a_regex)
07287     : DeathTestImpl(a_statement, a_regex),
07288       child_pid_(-1) {}
07289 
07290 // Waits for the child in a death test to exit, returning its exit
07291 // status, or 0 if no child process exists.  As a side effect, sets the
07292 // outcome data member.
07293 int ForkingDeathTest::Wait() {
07294   if (!spawned())
07295     return 0;
07296 
07297   ReadAndInterpretStatusByte();
07298 
07299   int status_value;
07300   GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0));
07301   set_status(status_value);
07302   return status_value;
07303 }
07304 
07305 // A concrete death test class that forks, then immediately runs the test
07306 // in the child process.
07307 class NoExecDeathTest : public ForkingDeathTest {
07308  public:
07309   NoExecDeathTest(const char* a_statement, const RE* a_regex) :
07310       ForkingDeathTest(a_statement, a_regex) { }
07311   virtual TestRole AssumeRole();
07312 };
07313 
07314 // The AssumeRole process for a fork-and-run death test.  It implements a
07315 // straightforward fork, with a simple pipe to transmit the status byte.
07316 DeathTest::TestRole NoExecDeathTest::AssumeRole() {
07317   const size_t thread_count = GetThreadCount();
07318   if (thread_count != 1) {
07319     GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count);
07320   }
07321 
07322   int pipe_fd[2];
07323   GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
07324 
07325   DeathTest::set_last_death_test_message("");
07326   CaptureStderr();
07327   // When we fork the process below, the log file buffers are copied, but the
07328   // file descriptors are shared.  We flush all log files here so that closing
07329   // the file descriptors in the child process doesn't throw off the
07330   // synchronization between descriptors and buffers in the parent process.
07331   // This is as close to the fork as possible to avoid a race condition in case
07332   // there are multiple threads running before the death test, and another
07333   // thread writes to the log file.
07334   FlushInfoLog();
07335 
07336   const pid_t child_pid = fork();
07337   GTEST_DEATH_TEST_CHECK_(child_pid != -1);
07338   set_child_pid(child_pid);
07339   if (child_pid == 0) {
07340     GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0]));
07341     set_write_fd(pipe_fd[1]);
07342     // Redirects all logging to stderr in the child process to prevent
07343     // concurrent writes to the log files.  We capture stderr in the parent
07344     // process and append the child process' output to a log.
07345     LogToStderr();
07346     // Event forwarding to the listeners of event listener API mush be shut
07347     // down in death test subprocesses.
07348     GetUnitTestImpl()->listeners()->SuppressEventForwarding();
07349     g_in_fast_death_test_child = true;
07350     return EXECUTE_TEST;
07351   } else {
07352     GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
07353     set_read_fd(pipe_fd[0]);
07354     set_spawned(true);
07355     return OVERSEE_TEST;
07356   }
07357 }
07358 
07359 // A concrete death test class that forks and re-executes the main
07360 // program from the beginning, with command-line flags set that cause
07361 // only this specific death test to be run.
07362 class ExecDeathTest : public ForkingDeathTest {
07363  public:
07364   ExecDeathTest(const char* a_statement, const RE* a_regex,
07365                 const char* file, int line) :
07366       ForkingDeathTest(a_statement, a_regex), file_(file), line_(line) { }
07367   virtual TestRole AssumeRole();
07368  private:
07369   static ::std::vector<testing::internal::string>
07370   GetArgvsForDeathTestChildProcess() {
07371     ::std::vector<testing::internal::string> args = GetInjectableArgvs();
07372     return args;
07373   }
07374   // The name of the file in which the death test is located.
07375   const char* const file_;
07376   // The line number on which the death test is located.
07377   const int line_;
07378 };
07379 
07380 // Utility class for accumulating command-line arguments.
07381 class Arguments {
07382  public:
07383   Arguments() {
07384     args_.push_back(NULL);
07385   }
07386 
07387   ~Arguments() {
07388     for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
07389          ++i) {
07390       free(*i);
07391     }
07392   }
07393   void AddArgument(const char* argument) {
07394     args_.insert(args_.end() - 1, posix::StrDup(argument));
07395   }
07396 
07397   template <typename Str>
07398   void AddArguments(const ::std::vector<Str>& arguments) {
07399     for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
07400          i != arguments.end();
07401          ++i) {
07402       args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
07403     }
07404   }
07405   char* const* Argv() {
07406     return &args_[0];
07407   }
07408 
07409  private:
07410   std::vector<char*> args_;
07411 };
07412 
07413 // A struct that encompasses the arguments to the child process of a
07414 // threadsafe-style death test process.
07415 struct ExecDeathTestArgs {
07416   char* const* argv;  // Command-line arguments for the child's call to exec
07417   int close_fd;       // File descriptor to close; the read end of a pipe
07418 };
07419 
07420 #  if GTEST_OS_MAC
07421 inline char** GetEnviron() {
07422   // When Google Test is built as a framework on MacOS X, the environ variable
07423   // is unavailable. Apple's documentation (man environ) recommends using
07424   // _NSGetEnviron() instead.
07425   return *_NSGetEnviron();
07426 }
07427 #  else
07428 // Some POSIX platforms expect you to declare environ. extern "C" makes
07429 // it reside in the global namespace.
07430 extern "C" char** environ;
07431 inline char** GetEnviron() { return environ; }
07432 #  endif  // GTEST_OS_MAC
07433 
07434 #  if !GTEST_OS_QNX
07435 // The main function for a threadsafe-style death test child process.
07436 // This function is called in a clone()-ed process and thus must avoid
07437 // any potentially unsafe operations like malloc or libc functions.
07438 static int ExecDeathTestChildMain(void* child_arg) {
07439   ExecDeathTestArgs* const args = static_cast<ExecDeathTestArgs*>(child_arg);
07440   GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd));
07441 
07442   // We need to execute the test program in the same environment where
07443   // it was originally invoked.  Therefore we change to the original
07444   // working directory first.
07445   const char* const original_dir =
07446       UnitTest::GetInstance()->original_working_dir();
07447   // We can safely call chdir() as it's a direct system call.
07448   if (chdir(original_dir) != 0) {
07449     DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
07450                    GetLastErrnoDescription());
07451     return EXIT_FAILURE;
07452   }
07453 
07454   // We can safely call execve() as it's a direct system call.  We
07455   // cannot use execvp() as it's a libc function and thus potentially
07456   // unsafe.  Since execve() doesn't search the PATH, the user must
07457   // invoke the test program via a valid path that contains at least
07458   // one path separator.
07459   execve(args->argv[0], args->argv, GetEnviron());
07460   DeathTestAbort(std::string("execve(") + args->argv[0] + ", ...) in " +
07461                  original_dir + " failed: " +
07462                  GetLastErrnoDescription());
07463   return EXIT_FAILURE;
07464 }
07465 #  endif  // !GTEST_OS_QNX
07466 
07467 // Two utility routines that together determine the direction the stack
07468 // grows.
07469 // This could be accomplished more elegantly by a single recursive
07470 // function, but we want to guard against the unlikely possibility of
07471 // a smart compiler optimizing the recursion away.
07472 //
07473 // GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining
07474 // StackLowerThanAddress into StackGrowsDown, which then doesn't give
07475 // correct answer.
07476 void StackLowerThanAddress(const void* ptr, bool* result) GTEST_NO_INLINE_;
07477 void StackLowerThanAddress(const void* ptr, bool* result) {
07478   int dummy;
07479   *result = (&dummy < ptr);
07480 }
07481 
07482 bool StackGrowsDown() {
07483   int dummy;
07484   bool result;
07485   StackLowerThanAddress(&dummy, &result);
07486   return result;
07487 }
07488 
07489 // Spawns a child process with the same executable as the current process in
07490 // a thread-safe manner and instructs it to run the death test.  The
07491 // implementation uses fork(2) + exec.  On systems where clone(2) is
07492 // available, it is used instead, being slightly more thread-safe.  On QNX,
07493 // fork supports only single-threaded environments, so this function uses
07494 // spawn(2) there instead.  The function dies with an error message if
07495 // anything goes wrong.
07496 static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
07497   ExecDeathTestArgs args = { argv, close_fd };
07498   pid_t child_pid = -1;
07499 
07500 #  if GTEST_OS_QNX
07501   // Obtains the current directory and sets it to be closed in the child
07502   // process.
07503   const int cwd_fd = open(".", O_RDONLY);
07504   GTEST_DEATH_TEST_CHECK_(cwd_fd != -1);
07505   GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC));
07506   // We need to execute the test program in the same environment where
07507   // it was originally invoked.  Therefore we change to the original
07508   // working directory first.
07509   const char* const original_dir =
07510       UnitTest::GetInstance()->original_working_dir();
07511   // We can safely call chdir() as it's a direct system call.
07512   if (chdir(original_dir) != 0) {
07513     DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
07514                    GetLastErrnoDescription());
07515     return EXIT_FAILURE;
07516   }
07517 
07518   int fd_flags;
07519   // Set close_fd to be closed after spawn.
07520   GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD));
07521   GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD,
07522                                         fd_flags | FD_CLOEXEC));
07523   struct inheritance inherit = {0};
07524   // spawn is a system call.
07525   child_pid = spawn(args.argv[0], 0, NULL, &inherit, args.argv, GetEnviron());
07526   // Restores the current working directory.
07527   GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1);
07528   GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));
07529 
07530 #  else   // GTEST_OS_QNX
07531 #   if GTEST_OS_LINUX
07532   // When a SIGPROF signal is received while fork() or clone() are executing,
07533   // the process may hang. To avoid this, we ignore SIGPROF here and re-enable
07534   // it after the call to fork()/clone() is complete.
07535   struct sigaction saved_sigprof_action;
07536   struct sigaction ignore_sigprof_action;
07537   memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action));
07538   sigemptyset(&ignore_sigprof_action.sa_mask);
07539   ignore_sigprof_action.sa_handler = SIG_IGN;
07540   GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction(
07541       SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));
07542 #   endif  // GTEST_OS_LINUX
07543 
07544 #   if GTEST_HAS_CLONE
07545   const bool use_fork = GTEST_FLAG(death_test_use_fork);
07546 
07547   if (!use_fork) {
07548     static const bool stack_grows_down = StackGrowsDown();
07549     const size_t stack_size = getpagesize();
07550     // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead.
07551     void* const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE,
07552                              MAP_ANON | MAP_PRIVATE, -1, 0);
07553     GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED);
07554 
07555     // Maximum stack alignment in bytes:  For a downward-growing stack, this
07556     // amount is subtracted from size of the stack space to get an address
07557     // that is within the stack space and is aligned on all systems we care
07558     // about.  As far as I know there is no ABI with stack alignment greater
07559     // than 64.  We assume stack and stack_size already have alignment of
07560     // kMaxStackAlignment.
07561     const size_t kMaxStackAlignment = 64;
07562     void* const stack_top =
07563         static_cast<char*>(stack) +
07564             (stack_grows_down ? stack_size - kMaxStackAlignment : 0);
07565     GTEST_DEATH_TEST_CHECK_(stack_size > kMaxStackAlignment &&
07566         reinterpret_cast<intptr_t>(stack_top) % kMaxStackAlignment == 0);
07567 
07568     child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args);
07569 
07570     GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);
07571   }
07572 #   else
07573   const bool use_fork = true;
07574 #   endif  // GTEST_HAS_CLONE
07575 
07576   if (use_fork && (child_pid = fork()) == 0) {
07577       ExecDeathTestChildMain(&args);
07578       _exit(0);
07579   }
07580 #  endif  // GTEST_OS_QNX
07581 #  if GTEST_OS_LINUX
07582   GTEST_DEATH_TEST_CHECK_SYSCALL_(
07583       sigaction(SIGPROF, &saved_sigprof_action, NULL));
07584 #  endif  // GTEST_OS_LINUX
07585 
07586   GTEST_DEATH_TEST_CHECK_(child_pid != -1);
07587   return child_pid;
07588 }
07589 
07590 // The AssumeRole process for a fork-and-exec death test.  It re-executes the
07591 // main program from the beginning, setting the --gtest_filter
07592 // and --gtest_internal_run_death_test flags to cause only the current
07593 // death test to be re-run.
07594 DeathTest::TestRole ExecDeathTest::AssumeRole() {
07595   const UnitTestImpl* const impl = GetUnitTestImpl();
07596   const InternalRunDeathTestFlag* const flag =
07597       impl->internal_run_death_test_flag();
07598   const TestInfo* const info = impl->current_test_info();
07599   const int death_test_index = info->result()->death_test_count();
07600 
07601   if (flag != NULL) {
07602     set_write_fd(flag->write_fd());
07603     return EXECUTE_TEST;
07604   }
07605 
07606   int pipe_fd[2];
07607   GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
07608   // Clear the close-on-exec flag on the write end of the pipe, lest
07609   // it be closed when the child process does an exec:
07610   GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
07611 
07612   const std::string filter_flag =
07613       std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "="
07614       + info->test_case_name() + "." + info->name();
07615   const std::string internal_flag =
07616       std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "="
07617       + file_ + "|" + StreamableToString(line_) + "|"
07618       + StreamableToString(death_test_index) + "|"
07619       + StreamableToString(pipe_fd[1]);
07620   Arguments args;
07621   args.AddArguments(GetArgvsForDeathTestChildProcess());
07622   args.AddArgument(filter_flag.c_str());
07623   args.AddArgument(internal_flag.c_str());
07624 
07625   DeathTest::set_last_death_test_message("");
07626 
07627   CaptureStderr();
07628   // See the comment in NoExecDeathTest::AssumeRole for why the next line
07629   // is necessary.
07630   FlushInfoLog();
07631 
07632   const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]);
07633   GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
07634   set_child_pid(child_pid);
07635   set_read_fd(pipe_fd[0]);
07636   set_spawned(true);
07637   return OVERSEE_TEST;
07638 }
07639 
07640 # endif  // !GTEST_OS_WINDOWS
07641 
07642 // Creates a concrete DeathTest-derived class that depends on the
07643 // --gtest_death_test_style flag, and sets the pointer pointed to
07644 // by the "test" argument to its address.  If the test should be
07645 // skipped, sets that pointer to NULL.  Returns true, unless the
07646 // flag is set to an invalid value.
07647 bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex,
07648                                      const char* file, int line,
07649                                      DeathTest** test) {
07650   UnitTestImpl* const impl = GetUnitTestImpl();
07651   const InternalRunDeathTestFlag* const flag =
07652       impl->internal_run_death_test_flag();
07653   const int death_test_index = impl->current_test_info()
07654       ->increment_death_test_count();
07655 
07656   if (flag != NULL) {
07657     if (death_test_index > flag->index()) {
07658       DeathTest::set_last_death_test_message(
07659           "Death test count (" + StreamableToString(death_test_index)
07660           + ") somehow exceeded expected maximum ("
07661           + StreamableToString(flag->index()) + ")");
07662       return false;
07663     }
07664 
07665     if (!(flag->file() == file && flag->line() == line &&
07666           flag->index() == death_test_index)) {
07667       *test = NULL;
07668       return true;
07669     }
07670   }
07671 
07672 # if GTEST_OS_WINDOWS
07673 
07674   if (GTEST_FLAG(death_test_style) == "threadsafe" ||
07675       GTEST_FLAG(death_test_style) == "fast") {
07676     *test = new WindowsDeathTest(statement, regex, file, line);
07677   }
07678 
07679 # else
07680 
07681   if (GTEST_FLAG(death_test_style) == "threadsafe") {
07682     *test = new ExecDeathTest(statement, regex, file, line);
07683   } else if (GTEST_FLAG(death_test_style) == "fast") {
07684     *test = new NoExecDeathTest(statement, regex);
07685   }
07686 
07687 # endif  // GTEST_OS_WINDOWS
07688 
07689   else {  // NOLINT - this is more readable than unbalanced brackets inside #if.
07690     DeathTest::set_last_death_test_message(
07691         "Unknown death test style \"" + GTEST_FLAG(death_test_style)
07692         + "\" encountered");
07693     return false;
07694   }
07695 
07696   return true;
07697 }
07698 
07699 // Splits a given string on a given delimiter, populating a given
07700 // vector with the fields.  GTEST_HAS_DEATH_TEST implies that we have
07701 // ::std::string, so we can use it here.
07702 static void SplitString(const ::std::string& str, char delimiter,
07703                         ::std::vector< ::std::string>* dest) {
07704   ::std::vector< ::std::string> parsed;
07705   ::std::string::size_type pos = 0;
07706   while (::testing::internal::AlwaysTrue()) {
07707     const ::std::string::size_type colon = str.find(delimiter, pos);
07708     if (colon == ::std::string::npos) {
07709       parsed.push_back(str.substr(pos));
07710       break;
07711     } else {
07712       parsed.push_back(str.substr(pos, colon - pos));
07713       pos = colon + 1;
07714     }
07715   }
07716   dest->swap(parsed);
07717 }
07718 
07719 # if GTEST_OS_WINDOWS
07720 // Recreates the pipe and event handles from the provided parameters,
07721 // signals the event, and returns a file descriptor wrapped around the pipe
07722 // handle. This function is called in the child process only.
07723 int GetStatusFileDescriptor(unsigned int parent_process_id,
07724                             size_t write_handle_as_size_t,
07725                             size_t event_handle_as_size_t) {
07726   AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,
07727                                                    FALSE,  // Non-inheritable.
07728                                                    parent_process_id));
07729   if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {
07730     DeathTestAbort("Unable to open parent process " +
07731                    StreamableToString(parent_process_id));
07732   }
07733 
07734   // TODO(vladl@google.com): Replace the following check with a
07735   // compile-time assertion when available.
07736   GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t));
07737 
07738   const HANDLE write_handle =
07739       reinterpret_cast<HANDLE>(write_handle_as_size_t);
07740   HANDLE dup_write_handle;
07741 
07742   // The newly initialized handle is accessible only in in the parent
07743   // process. To obtain one accessible within the child, we need to use
07744   // DuplicateHandle.
07745   if (!::DuplicateHandle(parent_process_handle.Get(), write_handle,
07746                          ::GetCurrentProcess(), &dup_write_handle,
07747                          0x0,    // Requested privileges ignored since
07748                                  // DUPLICATE_SAME_ACCESS is used.
07749                          FALSE,  // Request non-inheritable handler.
07750                          DUPLICATE_SAME_ACCESS)) {
07751     DeathTestAbort("Unable to duplicate the pipe handle " +
07752                    StreamableToString(write_handle_as_size_t) +
07753                    " from the parent process " +
07754                    StreamableToString(parent_process_id));
07755   }
07756 
07757   const HANDLE event_handle = reinterpret_cast<HANDLE>(event_handle_as_size_t);
07758   HANDLE dup_event_handle;
07759 
07760   if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,
07761                          ::GetCurrentProcess(), &dup_event_handle,
07762                          0x0,
07763                          FALSE,
07764                          DUPLICATE_SAME_ACCESS)) {
07765     DeathTestAbort("Unable to duplicate the event handle " +
07766                    StreamableToString(event_handle_as_size_t) +
07767                    " from the parent process " +
07768                    StreamableToString(parent_process_id));
07769   }
07770 
07771   const int write_fd =
07772       ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND);
07773   if (write_fd == -1) {
07774     DeathTestAbort("Unable to convert pipe handle " +
07775                    StreamableToString(write_handle_as_size_t) +
07776                    " to a file descriptor");
07777   }
07778 
07779   // Signals the parent that the write end of the pipe has been acquired
07780   // so the parent can release its own write end.
07781   ::SetEvent(dup_event_handle);
07782 
07783   return write_fd;
07784 }
07785 # endif  // GTEST_OS_WINDOWS
07786 
07787 // Returns a newly created InternalRunDeathTestFlag object with fields
07788 // initialized from the GTEST_FLAG(internal_run_death_test) flag if
07789 // the flag is specified; otherwise returns NULL.
07790 InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
07791   if (GTEST_FLAG(internal_run_death_test) == "") return NULL;
07792 
07793   // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we
07794   // can use it here.
07795   int line = -1;
07796   int index = -1;
07797   ::std::vector< ::std::string> fields;
07798   SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields);
07799   int write_fd = -1;
07800 
07801 # if GTEST_OS_WINDOWS
07802 
07803   unsigned int parent_process_id = 0;
07804   size_t write_handle_as_size_t = 0;
07805   size_t event_handle_as_size_t = 0;
07806 
07807   if (fields.size() != 6
07808       || !ParseNaturalNumber(fields[1], &line)
07809       || !ParseNaturalNumber(fields[2], &index)
07810       || !ParseNaturalNumber(fields[3], &parent_process_id)
07811       || !ParseNaturalNumber(fields[4], &write_handle_as_size_t)
07812       || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
07813     DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
07814                    GTEST_FLAG(internal_run_death_test));
07815   }
07816   write_fd = GetStatusFileDescriptor(parent_process_id,
07817                                      write_handle_as_size_t,
07818                                      event_handle_as_size_t);
07819 # else
07820 
07821   if (fields.size() != 4
07822       || !ParseNaturalNumber(fields[1], &line)
07823       || !ParseNaturalNumber(fields[2], &index)
07824       || !ParseNaturalNumber(fields[3], &write_fd)) {
07825     DeathTestAbort("Bad --gtest_internal_run_death_test flag: "
07826         + GTEST_FLAG(internal_run_death_test));
07827   }
07828 
07829 # endif  // GTEST_OS_WINDOWS
07830 
07831   return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);
07832 }
07833 
07834 }  // namespace internal
07835 
07836 #endif  // GTEST_HAS_DEATH_TEST
07837 
07838 }  // namespace testing
07839 // Copyright 2008, Google Inc.
07840 // All rights reserved.
07841 //
07842 // Redistribution and use in source and binary forms, with or without
07843 // modification, are permitted provided that the following conditions are
07844 // met:
07845 //
07846 //     * Redistributions of source code must retain the above copyright
07847 // notice, this list of conditions and the following disclaimer.
07848 //     * Redistributions in binary form must reproduce the above
07849 // copyright notice, this list of conditions and the following disclaimer
07850 // in the documentation and/or other materials provided with the
07851 // distribution.
07852 //     * Neither the name of Google Inc. nor the names of its
07853 // contributors may be used to endorse or promote products derived from
07854 // this software without specific prior written permission.
07855 //
07856 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
07857 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
07858 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
07859 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
07860 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
07861 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
07862 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
07863 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
07864 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
07865 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
07866 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
07867 //
07868 // Authors: keith.ray@gmail.com (Keith Ray)
07869 
07870 
07871 #include <stdlib.h>
07872 
07873 #if GTEST_OS_WINDOWS_MOBILE
07874 # include <windows.h>
07875 #elif GTEST_OS_WINDOWS
07876 # include <direct.h>
07877 # include <io.h>
07878 #elif GTEST_OS_SYMBIAN
07879 // Symbian OpenC has PATH_MAX in sys/syslimits.h
07880 # include <sys/syslimits.h>
07881 #else
07882 # include <limits.h>
07883 # include <climits>  // Some Linux distributions define PATH_MAX here.
07884 #endif  // GTEST_OS_WINDOWS_MOBILE
07885 
07886 #if GTEST_OS_WINDOWS
07887 # define GTEST_PATH_MAX_ _MAX_PATH
07888 #elif defined(PATH_MAX)
07889 # define GTEST_PATH_MAX_ PATH_MAX
07890 #elif defined(_XOPEN_PATH_MAX)
07891 # define GTEST_PATH_MAX_ _XOPEN_PATH_MAX
07892 #else
07893 # define GTEST_PATH_MAX_ _POSIX_PATH_MAX
07894 #endif  // GTEST_OS_WINDOWS
07895 
07896 
07897 namespace testing {
07898 namespace internal {
07899 
07900 #if GTEST_OS_WINDOWS
07901 // On Windows, '\\' is the standard path separator, but many tools and the
07902 // Windows API also accept '/' as an alternate path separator. Unless otherwise
07903 // noted, a file path can contain either kind of path separators, or a mixture
07904 // of them.
07905 const char kPathSeparator = '\\';
07906 const char kAlternatePathSeparator = '/';
07907 const char kPathSeparatorString[] = "\\";
07908 const char kAlternatePathSeparatorString[] = "/";
07909 # if GTEST_OS_WINDOWS_MOBILE
07910 // Windows CE doesn't have a current directory. You should not use
07911 // the current directory in tests on Windows CE, but this at least
07912 // provides a reasonable fallback.
07913 const char kCurrentDirectoryString[] = "\\";
07914 // Windows CE doesn't define INVALID_FILE_ATTRIBUTES
07915 const DWORD kInvalidFileAttributes = 0xffffffff;
07916 # else
07917 const char kCurrentDirectoryString[] = ".\\";
07918 # endif  // GTEST_OS_WINDOWS_MOBILE
07919 #else
07920 const char kPathSeparator = '/';
07921 const char kPathSeparatorString[] = "/";
07922 const char kCurrentDirectoryString[] = "./";
07923 #endif  // GTEST_OS_WINDOWS
07924 
07925 // Returns whether the given character is a valid path separator.
07926 static bool IsPathSeparator(char c) {
07927 #if GTEST_HAS_ALT_PATH_SEP_
07928   return (c == kPathSeparator) || (c == kAlternatePathSeparator);
07929 #else
07930   return c == kPathSeparator;
07931 #endif
07932 }
07933 
07934 // Returns the current working directory, or "" if unsuccessful.
07935 FilePath FilePath::GetCurrentDir() {
07936 #if GTEST_OS_WINDOWS_MOBILE
07937   // Windows CE doesn't have a current directory, so we just return
07938   // something reasonable.
07939   return FilePath(kCurrentDirectoryString);
07940 #elif GTEST_OS_WINDOWS
07941   char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
07942   return FilePath(_getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
07943 #else
07944   char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
07945   return FilePath(getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
07946 #endif  // GTEST_OS_WINDOWS_MOBILE
07947 }
07948 
07949 // Returns a copy of the FilePath with the case-insensitive extension removed.
07950 // Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
07951 // FilePath("dir/file"). If a case-insensitive extension is not
07952 // found, returns a copy of the original FilePath.
07953 FilePath FilePath::RemoveExtension(const char* extension) const {
07954   const std::string dot_extension = std::string(".") + extension;
07955   if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) {
07956     return FilePath(pathname_.substr(
07957         0, pathname_.length() - dot_extension.length()));
07958   }
07959   return *this;
07960 }
07961 
07962 // Returns a pointer to the last occurence of a valid path separator in
07963 // the FilePath. On Windows, for example, both '/' and '\' are valid path
07964 // separators. Returns NULL if no path separator was found.
07965 const char* FilePath::FindLastPathSeparator() const {
07966   const char* const last_sep = strrchr(c_str(), kPathSeparator);
07967 #if GTEST_HAS_ALT_PATH_SEP_
07968   const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator);
07969   // Comparing two pointers of which only one is NULL is undefined.
07970   if (last_alt_sep != NULL &&
07971       (last_sep == NULL || last_alt_sep > last_sep)) {
07972     return last_alt_sep;
07973   }
07974 #endif
07975   return last_sep;
07976 }
07977 
07978 // Returns a copy of the FilePath with the directory part removed.
07979 // Example: FilePath("path/to/file").RemoveDirectoryName() returns
07980 // FilePath("file"). If there is no directory part ("just_a_file"), it returns
07981 // the FilePath unmodified. If there is no file part ("just_a_dir/") it
07982 // returns an empty FilePath ("").
07983 // On Windows platform, '\' is the path separator, otherwise it is '/'.
07984 FilePath FilePath::RemoveDirectoryName() const {
07985   const char* const last_sep = FindLastPathSeparator();
07986   return last_sep ? FilePath(last_sep + 1) : *this;
07987 }
07988 
07989 // RemoveFileName returns the directory path with the filename removed.
07990 // Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
07991 // If the FilePath is "a_file" or "/a_file", RemoveFileName returns
07992 // FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
07993 // not have a file, like "just/a/dir/", it returns the FilePath unmodified.
07994 // On Windows platform, '\' is the path separator, otherwise it is '/'.
07995 FilePath FilePath::RemoveFileName() const {
07996   const char* const last_sep = FindLastPathSeparator();
07997   std::string dir;
07998   if (last_sep) {
07999     dir = std::string(c_str(), last_sep + 1 - c_str());
08000   } else {
08001     dir = kCurrentDirectoryString;
08002   }
08003   return FilePath(dir);
08004 }
08005 
08006 // Helper functions for naming files in a directory for xml output.
08007 
08008 // Given directory = "dir", base_name = "test", number = 0,
08009 // extension = "xml", returns "dir/test.xml". If number is greater
08010 // than zero (e.g., 12), returns "dir/test_12.xml".
08011 // On Windows platform, uses \ as the separator rather than /.
08012 FilePath FilePath::MakeFileName(const FilePath& directory,
08013                                 const FilePath& base_name,
08014                                 int number,
08015                                 const char* extension) {
08016   std::string file;
08017   if (number == 0) {
08018     file = base_name.string() + "." + extension;
08019   } else {
08020     file = base_name.string() + "_" + StreamableToString(number)
08021         + "." + extension;
08022   }
08023   return ConcatPaths(directory, FilePath(file));
08024 }
08025 
08026 // Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml".
08027 // On Windows, uses \ as the separator rather than /.
08028 FilePath FilePath::ConcatPaths(const FilePath& directory,
08029                                const FilePath& relative_path) {
08030   if (directory.IsEmpty())
08031     return relative_path;
08032   const FilePath dir(directory.RemoveTrailingPathSeparator());
08033   return FilePath(dir.string() + kPathSeparator + relative_path.string());
08034 }
08035 
08036 // Returns true if pathname describes something findable in the file-system,
08037 // either a file, directory, or whatever.
08038 bool FilePath::FileOrDirectoryExists() const {
08039 #if GTEST_OS_WINDOWS_MOBILE
08040   LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());
08041   const DWORD attributes = GetFileAttributes(unicode);
08042   delete [] unicode;
08043   return attributes != kInvalidFileAttributes;
08044 #else
08045   posix::StatStruct file_stat;
08046   return posix::Stat(pathname_.c_str(), &file_stat) == 0;
08047 #endif  // GTEST_OS_WINDOWS_MOBILE
08048 }
08049 
08050 // Returns true if pathname describes a directory in the file-system
08051 // that exists.
08052 bool FilePath::DirectoryExists() const {
08053   bool result = false;
08054 #if GTEST_OS_WINDOWS
08055   // Don't strip off trailing separator if path is a root directory on
08056   // Windows (like "C:\\").
08057   const FilePath& path(IsRootDirectory() ? *this :
08058                                            RemoveTrailingPathSeparator());
08059 #else
08060   const FilePath& path(*this);
08061 #endif
08062 
08063 #if GTEST_OS_WINDOWS_MOBILE
08064   LPCWSTR unicode = String::AnsiToUtf16(path.c_str());
08065   const DWORD attributes = GetFileAttributes(unicode);
08066   delete [] unicode;
08067   if ((attributes != kInvalidFileAttributes) &&
08068       (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
08069     result = true;
08070   }
08071 #else
08072   posix::StatStruct file_stat;
08073   result = posix::Stat(path.c_str(), &file_stat) == 0 &&
08074       posix::IsDir(file_stat);
08075 #endif  // GTEST_OS_WINDOWS_MOBILE
08076 
08077   return result;
08078 }
08079 
08080 // Returns true if pathname describes a root directory.