Qucs-core  0.0.19
gtest-internal-inl.h
Go to the documentation of this file.
00001 // Copyright 2005, Google Inc.
00002 // All rights reserved.
00003 //
00004 // Redistribution and use in source and binary forms, with or without
00005 // modification, are permitted provided that the following conditions are
00006 // met:
00007 //
00008 //     * Redistributions of source code must retain the above copyright
00009 // notice, this list of conditions and the following disclaimer.
00010 //     * Redistributions in binary form must reproduce the above
00011 // copyright notice, this list of conditions and the following disclaimer
00012 // in the documentation and/or other materials provided with the
00013 // distribution.
00014 //     * Neither the name of Google Inc. nor the names of its
00015 // contributors may be used to endorse or promote products derived from
00016 // this software without specific prior written permission.
00017 //
00018 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
00019 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
00020 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
00021 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
00022 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
00023 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
00024 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
00025 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
00026 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
00027 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
00028 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
00029 
00030 // Utility functions and classes used by the Google C++ testing framework.
00031 //
00032 // Author: wan@google.com (Zhanyong Wan)
00033 //
00034 // This file contains purely Google Test's internal implementation.  Please
00035 // DO NOT #INCLUDE IT IN A USER PROGRAM.
00036 
00037 #ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_
00038 #define GTEST_SRC_GTEST_INTERNAL_INL_H_
00039 
00040 // GTEST_IMPLEMENTATION_ is defined to 1 iff the current translation unit is
00041 // part of Google Test's implementation; otherwise it's undefined.
00042 #if !GTEST_IMPLEMENTATION_
00043 // A user is trying to include this from his code - just say no.
00044 # error "gtest-internal-inl.h is part of Google Test's internal implementation."
00045 # error "It must not be included except by Google Test itself."
00046 #endif  // GTEST_IMPLEMENTATION_
00047 
00048 #ifndef _WIN32_WCE
00049 # include <errno.h>
00050 #endif  // !_WIN32_WCE
00051 #include <stddef.h>
00052 #include <stdlib.h>  // For strtoll/_strtoul64/malloc/free.
00053 #include <string.h>  // For memmove.
00054 
00055 #include <algorithm>
00056 #include <string>
00057 #include <vector>
00058 
00059 #include "gtest/internal/gtest-port.h"
00060 
00061 #if GTEST_CAN_STREAM_RESULTS_
00062 # include <arpa/inet.h>  // NOLINT
00063 # include <netdb.h>  // NOLINT
00064 #endif
00065 
00066 #if GTEST_OS_WINDOWS
00067 # include <windows.h>  // NOLINT
00068 #endif  // GTEST_OS_WINDOWS
00069 
00070 #include "gtest/gtest.h"  // NOLINT
00071 #include "gtest/gtest-spi.h"
00072 
00073 namespace testing {
00074 
00075 // Declares the flags.
00076 //
00077 // We don't want the users to modify this flag in the code, but want
00078 // Google Test's own unit tests to be able to access it. Therefore we
00079 // declare it here as opposed to in gtest.h.
00080 GTEST_DECLARE_bool_(death_test_use_fork);
00081 
00082 namespace internal {
00083 
00084 // The value of GetTestTypeId() as seen from within the Google Test
00085 // library.  This is solely for testing GetTestTypeId().
00086 GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest;
00087 
00088 // Names of the flags (needed for parsing Google Test flags).
00089 const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests";
00090 const char kBreakOnFailureFlag[] = "break_on_failure";
00091 const char kCatchExceptionsFlag[] = "catch_exceptions";
00092 const char kColorFlag[] = "color";
00093 const char kFilterFlag[] = "filter";
00094 const char kListTestsFlag[] = "list_tests";
00095 const char kOutputFlag[] = "output";
00096 const char kPrintTimeFlag[] = "print_time";
00097 const char kRandomSeedFlag[] = "random_seed";
00098 const char kRepeatFlag[] = "repeat";
00099 const char kShuffleFlag[] = "shuffle";
00100 const char kStackTraceDepthFlag[] = "stack_trace_depth";
00101 const char kStreamResultToFlag[] = "stream_result_to";
00102 const char kThrowOnFailureFlag[] = "throw_on_failure";
00103 
00104 // A valid random seed must be in [1, kMaxRandomSeed].
00105 const int kMaxRandomSeed = 99999;
00106 
00107 // g_help_flag is true iff the --help flag or an equivalent form is
00108 // specified on the command line.
00109 GTEST_API_ extern bool g_help_flag;
00110 
00111 // Returns the current time in milliseconds.
00112 GTEST_API_ TimeInMillis GetTimeInMillis();
00113 
00114 // Returns true iff Google Test should use colors in the output.
00115 GTEST_API_ bool ShouldUseColor(bool stdout_is_tty);
00116 
00117 // Formats the given time in milliseconds as seconds.
00118 GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms);
00119 
00120 // Converts the given time in milliseconds to a date string in the ISO 8601
00121 // format, without the timezone information.  N.B.: due to the use the
00122 // non-reentrant localtime() function, this function is not thread safe.  Do
00123 // not use it in any code that can be called from multiple threads.
00124 GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms);
00125 
00126 // Parses a string for an Int32 flag, in the form of "--flag=value".
00127 //
00128 // On success, stores the value of the flag in *value, and returns
00129 // true.  On failure, returns false without changing *value.
00130 GTEST_API_ bool ParseInt32Flag(
00131     const char* str, const char* flag, Int32* value);
00132 
00133 // Returns a random seed in range [1, kMaxRandomSeed] based on the
00134 // given --gtest_random_seed flag value.
00135 inline int GetRandomSeedFromFlag(Int32 random_seed_flag) {
00136   const unsigned int raw_seed = (random_seed_flag == 0) ?
00137       static_cast<unsigned int>(GetTimeInMillis()) :
00138       static_cast<unsigned int>(random_seed_flag);
00139 
00140   // Normalizes the actual seed to range [1, kMaxRandomSeed] such that
00141   // it's easy to type.
00142   const int normalized_seed =
00143       static_cast<int>((raw_seed - 1U) %
00144                        static_cast<unsigned int>(kMaxRandomSeed)) + 1;
00145   return normalized_seed;
00146 }
00147 
00148 // Returns the first valid random seed after 'seed'.  The behavior is
00149 // undefined if 'seed' is invalid.  The seed after kMaxRandomSeed is
00150 // considered to be 1.
00151 inline int GetNextRandomSeed(int seed) {
00152   GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed)
00153       << "Invalid random seed " << seed << " - must be in [1, "
00154       << kMaxRandomSeed << "].";
00155   const int next_seed = seed + 1;
00156   return (next_seed > kMaxRandomSeed) ? 1 : next_seed;
00157 }
00158 
00159 // This class saves the values of all Google Test flags in its c'tor, and
00160 // restores them in its d'tor.
00161 class GTestFlagSaver {
00162  public:
00163   // The c'tor.
00164   GTestFlagSaver() {
00165     also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests);
00166     break_on_failure_ = GTEST_FLAG(break_on_failure);
00167     catch_exceptions_ = GTEST_FLAG(catch_exceptions);
00168     color_ = GTEST_FLAG(color);
00169     death_test_style_ = GTEST_FLAG(death_test_style);
00170     death_test_use_fork_ = GTEST_FLAG(death_test_use_fork);
00171     filter_ = GTEST_FLAG(filter);
00172     internal_run_death_test_ = GTEST_FLAG(internal_run_death_test);
00173     list_tests_ = GTEST_FLAG(list_tests);
00174     output_ = GTEST_FLAG(output);
00175     print_time_ = GTEST_FLAG(print_time);
00176     random_seed_ = GTEST_FLAG(random_seed);
00177     repeat_ = GTEST_FLAG(repeat);
00178     shuffle_ = GTEST_FLAG(shuffle);
00179     stack_trace_depth_ = GTEST_FLAG(stack_trace_depth);
00180     stream_result_to_ = GTEST_FLAG(stream_result_to);
00181     throw_on_failure_ = GTEST_FLAG(throw_on_failure);
00182   }
00183 
00184   // The d'tor is not virtual.  DO NOT INHERIT FROM THIS CLASS.
00185   ~GTestFlagSaver() {
00186     GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_;
00187     GTEST_FLAG(break_on_failure) = break_on_failure_;
00188     GTEST_FLAG(catch_exceptions) = catch_exceptions_;
00189     GTEST_FLAG(color) = color_;
00190     GTEST_FLAG(death_test_style) = death_test_style_;
00191     GTEST_FLAG(death_test_use_fork) = death_test_use_fork_;
00192     GTEST_FLAG(filter) = filter_;
00193     GTEST_FLAG(internal_run_death_test) = internal_run_death_test_;
00194     GTEST_FLAG(list_tests) = list_tests_;
00195     GTEST_FLAG(output) = output_;
00196     GTEST_FLAG(print_time) = print_time_;
00197     GTEST_FLAG(random_seed) = random_seed_;
00198     GTEST_FLAG(repeat) = repeat_;
00199     GTEST_FLAG(shuffle) = shuffle_;
00200     GTEST_FLAG(stack_trace_depth) = stack_trace_depth_;
00201     GTEST_FLAG(stream_result_to) = stream_result_to_;
00202     GTEST_FLAG(throw_on_failure) = throw_on_failure_;
00203   }
00204 
00205  private:
00206   // Fields for saving the original values of flags.
00207   bool also_run_disabled_tests_;
00208   bool break_on_failure_;
00209   bool catch_exceptions_;
00210   std::string color_;
00211   std::string death_test_style_;
00212   bool death_test_use_fork_;
00213   std::string filter_;
00214   std::string internal_run_death_test_;
00215   bool list_tests_;
00216   std::string output_;
00217   bool print_time_;
00218   internal::Int32 random_seed_;
00219   internal::Int32 repeat_;
00220   bool shuffle_;
00221   internal::Int32 stack_trace_depth_;
00222   std::string stream_result_to_;
00223   bool throw_on_failure_;
00224 } GTEST_ATTRIBUTE_UNUSED_;
00225 
00226 // Converts a Unicode code point to a narrow string in UTF-8 encoding.
00227 // code_point parameter is of type UInt32 because wchar_t may not be
00228 // wide enough to contain a code point.
00229 // If the code_point is not a valid Unicode code point
00230 // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
00231 // to "(Invalid Unicode 0xXXXXXXXX)".
00232 GTEST_API_ std::string CodePointToUtf8(UInt32 code_point);
00233 
00234 // Converts a wide string to a narrow string in UTF-8 encoding.
00235 // The wide string is assumed to have the following encoding:
00236 //   UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
00237 //   UTF-32 if sizeof(wchar_t) == 4 (on Linux)
00238 // Parameter str points to a null-terminated wide string.
00239 // Parameter num_chars may additionally limit the number
00240 // of wchar_t characters processed. -1 is used when the entire string
00241 // should be processed.
00242 // If the string contains code points that are not valid Unicode code points
00243 // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
00244 // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
00245 // and contains invalid UTF-16 surrogate pairs, values in those pairs
00246 // will be encoded as individual Unicode characters from Basic Normal Plane.
00247 GTEST_API_ std::string WideStringToUtf8(const wchar_t* str, int num_chars);
00248 
00249 // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
00250 // if the variable is present. If a file already exists at this location, this
00251 // function will write over it. If the variable is present, but the file cannot
00252 // be created, prints an error and exits.
00253 void WriteToShardStatusFileIfNeeded();
00254 
00255 // Checks whether sharding is enabled by examining the relevant
00256 // environment variable values. If the variables are present,
00257 // but inconsistent (e.g., shard_index >= total_shards), prints
00258 // an error and exits. If in_subprocess_for_death_test, sharding is
00259 // disabled because it must only be applied to the original test
00260 // process. Otherwise, we could filter out death tests we intended to execute.
00261 GTEST_API_ bool ShouldShard(const char* total_shards_str,
00262                             const char* shard_index_str,
00263                             bool in_subprocess_for_death_test);
00264 
00265 // Parses the environment variable var as an Int32. If it is unset,
00266 // returns default_val. If it is not an Int32, prints an error and
00267 // and aborts.
00268 GTEST_API_ Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val);
00269 
00270 // Given the total number of shards, the shard index, and the test id,
00271 // returns true iff the test should be run on this shard. The test id is
00272 // some arbitrary but unique non-negative integer assigned to each test
00273 // method. Assumes that 0 <= shard_index < total_shards.
00274 GTEST_API_ bool ShouldRunTestOnShard(
00275     int total_shards, int shard_index, int test_id);
00276 
00277 // STL container utilities.
00278 
00279 // Returns the number of elements in the given container that satisfy
00280 // the given predicate.
00281 template <class Container, typename Predicate>
00282 inline int CountIf(const Container& c, Predicate predicate) {
00283   // Implemented as an explicit loop since std::count_if() in libCstd on
00284   // Solaris has a non-standard signature.
00285   int count = 0;
00286   for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) {
00287     if (predicate(*it))
00288       ++count;
00289   }
00290   return count;
00291 }
00292 
00293 // Applies a function/functor to each element in the container.
00294 template <class Container, typename Functor>
00295 void ForEach(const Container& c, Functor functor) {
00296   std::for_each(c.begin(), c.end(), functor);
00297 }
00298 
00299 // Returns the i-th element of the vector, or default_value if i is not
00300 // in range [0, v.size()).
00301 template <typename E>
00302 inline E GetElementOr(const std::vector<E>& v, int i, E default_value) {
00303   return (i < 0 || i >= static_cast<int>(v.size())) ? default_value : v[i];
00304 }
00305 
00306 // Performs an in-place shuffle of a range of the vector's elements.
00307 // 'begin' and 'end' are element indices as an STL-style range;
00308 // i.e. [begin, end) are shuffled, where 'end' == size() means to
00309 // shuffle to the end of the vector.
00310 template <typename E>
00311 void ShuffleRange(internal::Random* random, int begin, int end,
00312                   std::vector<E>* v) {
00313   const int size = static_cast<int>(v->size());
00314   GTEST_CHECK_(0 <= begin && begin <= size)
00315       << "Invalid shuffle range start " << begin << ": must be in range [0, "
00316       << size << "].";
00317   GTEST_CHECK_(begin <= end && end <= size)
00318       << "Invalid shuffle range finish " << end << ": must be in range ["
00319       << begin << ", " << size << "].";
00320 
00321   // Fisher-Yates shuffle, from
00322   // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
00323   for (int range_width = end - begin; range_width >= 2; range_width--) {
00324     const int last_in_range = begin + range_width - 1;
00325     const int selected = begin + random->Generate(range_width);
00326     std::swap((*v)[selected], (*v)[last_in_range]);
00327   }
00328 }
00329 
00330 // Performs an in-place shuffle of the vector's elements.
00331 template <typename E>
00332 inline void Shuffle(internal::Random* random, std::vector<E>* v) {
00333   ShuffleRange(random, 0, static_cast<int>(v->size()), v);
00334 }
00335 
00336 // A function for deleting an object.  Handy for being used as a
00337 // functor.
00338 template <typename T>
00339 static void Delete(T* x) {
00340   delete x;
00341 }
00342 
00343 // A predicate that checks the key of a TestProperty against a known key.
00344 //
00345 // TestPropertyKeyIs is copyable.
00346 class TestPropertyKeyIs {
00347  public:
00348   // Constructor.
00349   //
00350   // TestPropertyKeyIs has NO default constructor.
00351   explicit TestPropertyKeyIs(const std::string& key) : key_(key) {}
00352 
00353   // Returns true iff the test name of test property matches on key_.
00354   bool operator()(const TestProperty& test_property) const {
00355     return test_property.key() == key_;
00356   }
00357 
00358  private:
00359   std::string key_;
00360 };
00361 
00362 // Class UnitTestOptions.
00363 //
00364 // This class contains functions for processing options the user
00365 // specifies when running the tests.  It has only static members.
00366 //
00367 // In most cases, the user can specify an option using either an
00368 // environment variable or a command line flag.  E.g. you can set the
00369 // test filter using either GTEST_FILTER or --gtest_filter.  If both
00370 // the variable and the flag are present, the latter overrides the
00371 // former.
00372 class GTEST_API_ UnitTestOptions {
00373  public:
00374   // Functions for processing the gtest_output flag.
00375 
00376   // Returns the output format, or "" for normal printed output.
00377   static std::string GetOutputFormat();
00378 
00379   // Returns the absolute path of the requested output file, or the
00380   // default (test_detail.xml in the original working directory) if
00381   // none was explicitly specified.
00382   static std::string GetAbsolutePathToOutputFile();
00383 
00384   // Functions for processing the gtest_filter flag.
00385 
00386   // Returns true iff the wildcard pattern matches the string.  The
00387   // first ':' or '\0' character in pattern marks the end of it.
00388   //
00389   // This recursive algorithm isn't very efficient, but is clear and
00390   // works well enough for matching test names, which are short.
00391   static bool PatternMatchesString(const char *pattern, const char *str);
00392 
00393   // Returns true iff the user-specified filter matches the test case
00394   // name and the test name.
00395   static bool FilterMatchesTest(const std::string &test_case_name,
00396                                 const std::string &test_name);
00397 
00398 #if GTEST_OS_WINDOWS
00399   // Function for supporting the gtest_catch_exception flag.
00400 
00401   // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
00402   // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
00403   // This function is useful as an __except condition.
00404   static int GTestShouldProcessSEH(DWORD exception_code);
00405 #endif  // GTEST_OS_WINDOWS
00406 
00407   // Returns true if "name" matches the ':' separated list of glob-style
00408   // filters in "filter".
00409   static bool MatchesFilter(const std::string& name, const char* filter);
00410 };
00411 
00412 // Returns the current application's name, removing directory path if that
00413 // is present.  Used by UnitTestOptions::GetOutputFile.
00414 GTEST_API_ FilePath GetCurrentExecutableName();
00415 
00416 // The role interface for getting the OS stack trace as a string.
00417 class OsStackTraceGetterInterface {
00418  public:
00419   OsStackTraceGetterInterface() {}
00420   virtual ~OsStackTraceGetterInterface() {}
00421 
00422   // Returns the current OS stack trace as an std::string.  Parameters:
00423   //
00424   //   max_depth  - the maximum number of stack frames to be included
00425   //                in the trace.
00426   //   skip_count - the number of top frames to be skipped; doesn't count
00427   //                against max_depth.
00428   virtual string CurrentStackTrace(int max_depth, int skip_count) = 0;
00429 
00430   // UponLeavingGTest() should be called immediately before Google Test calls
00431   // user code. It saves some information about the current stack that
00432   // CurrentStackTrace() will use to find and hide Google Test stack frames.
00433   virtual void UponLeavingGTest() = 0;
00434 
00435  private:
00436   GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface);
00437 };
00438 
00439 // A working implementation of the OsStackTraceGetterInterface interface.
00440 class OsStackTraceGetter : public OsStackTraceGetterInterface {
00441  public:
00442   OsStackTraceGetter() : caller_frame_(NULL) {}
00443 
00444   virtual string CurrentStackTrace(int max_depth, int skip_count)
00445       GTEST_LOCK_EXCLUDED_(mutex_);
00446 
00447   virtual void UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_);
00448 
00449   // This string is inserted in place of stack frames that are part of
00450   // Google Test's implementation.
00451   static const char* const kElidedFramesMarker;
00452 
00453  private:
00454   Mutex mutex_;  // protects all internal state
00455 
00456   // We save the stack frame below the frame that calls user code.
00457   // We do this because the address of the frame immediately below
00458   // the user code changes between the call to UponLeavingGTest()
00459   // and any calls to CurrentStackTrace() from within the user code.
00460   void* caller_frame_;
00461 
00462   GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter);
00463 };
00464 
00465 // Information about a Google Test trace point.
00466 struct TraceInfo {
00467   const char* file;
00468   int line;
00469   std::string message;
00470 };
00471 
00472 // This is the default global test part result reporter used in UnitTestImpl.
00473 // This class should only be used by UnitTestImpl.
00474 class DefaultGlobalTestPartResultReporter
00475   : public TestPartResultReporterInterface {
00476  public:
00477   explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test);
00478   // Implements the TestPartResultReporterInterface. Reports the test part
00479   // result in the current test.
00480   virtual void ReportTestPartResult(const TestPartResult& result);
00481 
00482  private:
00483   UnitTestImpl* const unit_test_;
00484 
00485   GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter);
00486 };
00487 
00488 // This is the default per thread test part result reporter used in
00489 // UnitTestImpl. This class should only be used by UnitTestImpl.
00490 class DefaultPerThreadTestPartResultReporter
00491     : public TestPartResultReporterInterface {
00492  public:
00493   explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test);
00494   // Implements the TestPartResultReporterInterface. The implementation just
00495   // delegates to the current global test part result reporter of *unit_test_.
00496   virtual void ReportTestPartResult(const TestPartResult& result);
00497 
00498  private:
00499   UnitTestImpl* const unit_test_;
00500 
00501   GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter);
00502 };
00503 
00504 // The private implementation of the UnitTest class.  We don't protect
00505 // the methods under a mutex, as this class is not accessible by a
00506 // user and the UnitTest class that delegates work to this class does
00507 // proper locking.
00508 class GTEST_API_ UnitTestImpl {
00509  public:
00510   explicit UnitTestImpl(UnitTest* parent);
00511   virtual ~UnitTestImpl();
00512 
00513   // There are two different ways to register your own TestPartResultReporter.
00514   // You can register your own repoter to listen either only for test results
00515   // from the current thread or for results from all threads.
00516   // By default, each per-thread test result repoter just passes a new
00517   // TestPartResult to the global test result reporter, which registers the
00518   // test part result for the currently running test.
00519 
00520   // Returns the global test part result reporter.
00521   TestPartResultReporterInterface* GetGlobalTestPartResultReporter();
00522 
00523   // Sets the global test part result reporter.
00524   void SetGlobalTestPartResultReporter(
00525       TestPartResultReporterInterface* reporter);
00526 
00527   // Returns the test part result reporter for the current thread.
00528   TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread();
00529 
00530   // Sets the test part result reporter for the current thread.
00531   void SetTestPartResultReporterForCurrentThread(
00532       TestPartResultReporterInterface* reporter);
00533 
00534   // Gets the number of successful test cases.
00535   int successful_test_case_count() const;
00536 
00537   // Gets the number of failed test cases.
00538   int failed_test_case_count() const;
00539 
00540   // Gets the number of all test cases.
00541   int total_test_case_count() const;
00542 
00543   // Gets the number of all test cases that contain at least one test
00544   // that should run.
00545   int test_case_to_run_count() const;
00546 
00547   // Gets the number of successful tests.
00548   int successful_test_count() const;
00549 
00550   // Gets the number of failed tests.
00551   int failed_test_count() const;
00552 
00553   // Gets the number of disabled tests that will be reported in the XML report.
00554   int reportable_disabled_test_count() const;
00555 
00556   // Gets the number of disabled tests.
00557   int disabled_test_count() const;
00558 
00559   // Gets the number of tests to be printed in the XML report.
00560   int reportable_test_count() const;
00561 
00562   // Gets the number of all tests.
00563   int total_test_count() const;
00564 
00565   // Gets the number of tests that should run.
00566   int test_to_run_count() const;
00567 
00568   // Gets the time of the test program start, in ms from the start of the
00569   // UNIX epoch.
00570   TimeInMillis start_timestamp() const { return start_timestamp_; }
00571 
00572   // Gets the elapsed time, in milliseconds.
00573   TimeInMillis elapsed_time() const { return elapsed_time_; }
00574 
00575   // Returns true iff the unit test passed (i.e. all test cases passed).
00576   bool Passed() const { return !Failed(); }
00577 
00578   // Returns true iff the unit test failed (i.e. some test case failed
00579   // or something outside of all tests failed).
00580   bool Failed() const {
00581     return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed();
00582   }
00583 
00584   // Gets the i-th test case among all the test cases. i can range from 0 to
00585   // total_test_case_count() - 1. If i is not in that range, returns NULL.
00586   const TestCase* GetTestCase(int i) const {
00587     const int index = GetElementOr(test_case_indices_, i, -1);
00588     return index < 0 ? NULL : test_cases_[i];
00589   }
00590 
00591   // Gets the i-th test case among all the test cases. i can range from 0 to
00592   // total_test_case_count() - 1. If i is not in that range, returns NULL.
00593   TestCase* GetMutableTestCase(int i) {
00594     const int index = GetElementOr(test_case_indices_, i, -1);
00595     return index < 0 ? NULL : test_cases_[index];
00596   }
00597 
00598   // Provides access to the event listener list.
00599   TestEventListeners* listeners() { return &listeners_; }
00600 
00601   // Returns the TestResult for the test that's currently running, or
00602   // the TestResult for the ad hoc test if no test is running.
00603   TestResult* current_test_result();
00604 
00605   // Returns the TestResult for the ad hoc test.
00606   const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; }
00607 
00608   // Sets the OS stack trace getter.
00609   //
00610   // Does nothing if the input and the current OS stack trace getter
00611   // are the same; otherwise, deletes the old getter and makes the
00612   // input the current getter.
00613   void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter);
00614 
00615   // Returns the current OS stack trace getter if it is not NULL;
00616   // otherwise, creates an OsStackTraceGetter, makes it the current
00617   // getter, and returns it.
00618   OsStackTraceGetterInterface* os_stack_trace_getter();
00619 
00620   // Returns the current OS stack trace as an std::string.
00621   //
00622   // The maximum number of stack frames to be included is specified by
00623   // the gtest_stack_trace_depth flag.  The skip_count parameter
00624   // specifies the number of top frames to be skipped, which doesn't
00625   // count against the number of frames to be included.
00626   //
00627   // For example, if Foo() calls Bar(), which in turn calls
00628   // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
00629   // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
00630   std::string CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_;
00631 
00632   // Finds and returns a TestCase with the given name.  If one doesn't
00633   // exist, creates one and returns it.
00634   //
00635   // Arguments:
00636   //
00637   //   test_case_name: name of the test case
00638   //   type_param:     the name of the test's type parameter, or NULL if
00639   //                   this is not a typed or a type-parameterized test.
00640   //   set_up_tc:      pointer to the function that sets up the test case
00641   //   tear_down_tc:   pointer to the function that tears down the test case
00642   TestCase* GetTestCase(const char* test_case_name,
00643                         const char* type_param,
00644                         Test::SetUpTestCaseFunc set_up_tc,
00645                         Test::TearDownTestCaseFunc tear_down_tc);
00646 
00647   // Adds a TestInfo to the unit test.
00648   //
00649   // Arguments:
00650   //
00651   //   set_up_tc:    pointer to the function that sets up the test case
00652   //   tear_down_tc: pointer to the function that tears down the test case
00653   //   test_info:    the TestInfo object
00654   void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc,
00655                    Test::TearDownTestCaseFunc tear_down_tc,
00656                    TestInfo* test_info) {
00657     // In order to support thread-safe death tests, we need to
00658     // remember the original working directory when the test program
00659     // was first invoked.  We cannot do this in RUN_ALL_TESTS(), as
00660     // the user may have changed the current directory before calling
00661     // RUN_ALL_TESTS().  Therefore we capture the current directory in
00662     // AddTestInfo(), which is called to register a TEST or TEST_F
00663     // before main() is reached.
00664     if (original_working_dir_.IsEmpty()) {
00665       original_working_dir_.Set(FilePath::GetCurrentDir());
00666       GTEST_CHECK_(!original_working_dir_.IsEmpty())
00667           << "Failed to get the current working directory.";
00668     }
00669 
00670     GetTestCase(test_info->test_case_name(),
00671                 test_info->type_param(),
00672                 set_up_tc,
00673                 tear_down_tc)->AddTestInfo(test_info);
00674   }
00675 
00676 #if GTEST_HAS_PARAM_TEST
00677   // Returns ParameterizedTestCaseRegistry object used to keep track of
00678   // value-parameterized tests and instantiate and register them.
00679   internal::ParameterizedTestCaseRegistry& parameterized_test_registry() {
00680     return parameterized_test_registry_;
00681   }
00682 #endif  // GTEST_HAS_PARAM_TEST
00683 
00684   // Sets the TestCase object for the test that's currently running.
00685   void set_current_test_case(TestCase* a_current_test_case) {
00686     current_test_case_ = a_current_test_case;
00687   }
00688 
00689   // Sets the TestInfo object for the test that's currently running.  If
00690   // current_test_info is NULL, the assertion results will be stored in
00691   // ad_hoc_test_result_.
00692   void set_current_test_info(TestInfo* a_current_test_info) {
00693     current_test_info_ = a_current_test_info;
00694   }
00695 
00696   // Registers all parameterized tests defined using TEST_P and
00697   // INSTANTIATE_TEST_CASE_P, creating regular tests for each test/parameter
00698   // combination. This method can be called more then once; it has guards
00699   // protecting from registering the tests more then once.  If
00700   // value-parameterized tests are disabled, RegisterParameterizedTests is
00701   // present but does nothing.
00702   void RegisterParameterizedTests();
00703 
00704   // Runs all tests in this UnitTest object, prints the result, and
00705   // returns true if all tests are successful.  If any exception is
00706   // thrown during a test, this test is considered to be failed, but
00707   // the rest of the tests will still be run.
00708   bool RunAllTests();
00709 
00710   // Clears the results of all tests, except the ad hoc tests.
00711   void ClearNonAdHocTestResult() {
00712     ForEach(test_cases_, TestCase::ClearTestCaseResult);
00713   }
00714 
00715   // Clears the results of ad-hoc test assertions.
00716   void ClearAdHocTestResult() {
00717     ad_hoc_test_result_.Clear();
00718   }
00719 
00720   // Adds a TestProperty to the current TestResult object when invoked in a
00721   // context of a test or a test case, or to the global property set. If the
00722   // result already contains a property with the same key, the value will be
00723   // updated.
00724   void RecordProperty(const TestProperty& test_property);
00725 
00726   enum ReactionToSharding {
00727     HONOR_SHARDING_PROTOCOL,
00728     IGNORE_SHARDING_PROTOCOL
00729   };
00730 
00731   // Matches the full name of each test against the user-specified
00732   // filter to decide whether the test should run, then records the
00733   // result in each TestCase and TestInfo object.
00734   // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests
00735   // based on sharding variables in the environment.
00736   // Returns the number of tests that should run.
00737   int FilterTests(ReactionToSharding shard_tests);
00738 
00739   // Prints the names of the tests matching the user-specified filter flag.
00740   void ListTestsMatchingFilter();
00741 
00742   const TestCase* current_test_case() const { return current_test_case_; }
00743   TestInfo* current_test_info() { return current_test_info_; }
00744   const TestInfo* current_test_info() const { return current_test_info_; }
00745 
00746   // Returns the vector of environments that need to be set-up/torn-down
00747   // before/after the tests are run.
00748   std::vector<Environment*>& environments() { return environments_; }
00749 
00750   // Getters for the per-thread Google Test trace stack.
00751   std::vector<TraceInfo>& gtest_trace_stack() {
00752     return *(gtest_trace_stack_.pointer());
00753   }
00754   const std::vector<TraceInfo>& gtest_trace_stack() const {
00755     return gtest_trace_stack_.get();
00756   }
00757 
00758 #if GTEST_HAS_DEATH_TEST
00759   void InitDeathTestSubprocessControlInfo() {
00760     internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());
00761   }
00762   // Returns a pointer to the parsed --gtest_internal_run_death_test
00763   // flag, or NULL if that flag was not specified.
00764   // This information is useful only in a death test child process.
00765   // Must not be called before a call to InitGoogleTest.
00766   const InternalRunDeathTestFlag* internal_run_death_test_flag() const {
00767     return internal_run_death_test_flag_.get();
00768   }
00769 
00770   // Returns a pointer to the current death test factory.
00771   internal::DeathTestFactory* death_test_factory() {
00772     return death_test_factory_.get();
00773   }
00774 
00775   void SuppressTestEventsIfInSubprocess();
00776 
00777   friend class ReplaceDeathTestFactory;
00778 #endif  // GTEST_HAS_DEATH_TEST
00779 
00780   // Initializes the event listener performing XML output as specified by
00781   // UnitTestOptions. Must not be called before InitGoogleTest.
00782   void ConfigureXmlOutput();
00783 
00784 #if GTEST_CAN_STREAM_RESULTS_
00785   // Initializes the event listener for streaming test results to a socket.
00786   // Must not be called before InitGoogleTest.
00787   void ConfigureStreamingOutput();
00788 #endif
00789 
00790   // Performs initialization dependent upon flag values obtained in
00791   // ParseGoogleTestFlagsOnly.  Is called from InitGoogleTest after the call to
00792   // ParseGoogleTestFlagsOnly.  In case a user neglects to call InitGoogleTest
00793   // this function is also called from RunAllTests.  Since this function can be
00794   // called more than once, it has to be idempotent.
00795   void PostFlagParsingInit();
00796 
00797   // Gets the random seed used at the start of the current test iteration.
00798   int random_seed() const { return random_seed_; }
00799 
00800   // Gets the random number generator.
00801   internal::Random* random() { return &random_; }
00802 
00803   // Shuffles all test cases, and the tests within each test case,
00804   // making sure that death tests are still run first.
00805   void ShuffleTests();
00806 
00807   // Restores the test cases and tests to their order before the first shuffle.
00808   void UnshuffleTests();
00809 
00810   // Returns the value of GTEST_FLAG(catch_exceptions) at the moment
00811   // UnitTest::Run() starts.
00812   bool catch_exceptions() const { return catch_exceptions_; }
00813 
00814  private:
00815   friend class ::testing::UnitTest;
00816 
00817   // Used by UnitTest::Run() to capture the state of
00818   // GTEST_FLAG(catch_exceptions) at the moment it starts.
00819   void set_catch_exceptions(bool value) { catch_exceptions_ = value; }
00820 
00821   // The UnitTest object that owns this implementation object.
00822   UnitTest* const parent_;
00823 
00824   // The working directory when the first TEST() or TEST_F() was
00825   // executed.
00826   internal::FilePath original_working_dir_;
00827 
00828   // The default test part result reporters.
00829   DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_;
00830   DefaultPerThreadTestPartResultReporter
00831       default_per_thread_test_part_result_reporter_;
00832 
00833   // Points to (but doesn't own) the global test part result reporter.
00834   TestPartResultReporterInterface* global_test_part_result_repoter_;
00835 
00836   // Protects read and write access to global_test_part_result_reporter_.
00837   internal::Mutex global_test_part_result_reporter_mutex_;
00838 
00839   // Points to (but doesn't own) the per-thread test part result reporter.
00840   internal::ThreadLocal<TestPartResultReporterInterface*>
00841       per_thread_test_part_result_reporter_;
00842 
00843   // The vector of environments that need to be set-up/torn-down
00844   // before/after the tests are run.
00845   std::vector<Environment*> environments_;
00846 
00847   // The vector of TestCases in their original order.  It owns the
00848   // elements in the vector.
00849   std::vector<TestCase*> test_cases_;
00850 
00851   // Provides a level of indirection for the test case list to allow
00852   // easy shuffling and restoring the test case order.  The i-th
00853   // element of this vector is the index of the i-th test case in the
00854   // shuffled order.
00855   std::vector<int> test_case_indices_;
00856 
00857 #if GTEST_HAS_PARAM_TEST
00858   // ParameterizedTestRegistry object used to register value-parameterized
00859   // tests.
00860   internal::ParameterizedTestCaseRegistry parameterized_test_registry_;
00861 
00862   // Indicates whether RegisterParameterizedTests() has been called already.
00863   bool parameterized_tests_registered_;
00864 #endif  // GTEST_HAS_PARAM_TEST
00865 
00866   // Index of the last death test case registered.  Initially -1.
00867   int last_death_test_case_;
00868 
00869   // This points to the TestCase for the currently running test.  It
00870   // changes as Google Test goes through one test case after another.
00871   // When no test is running, this is set to NULL and Google Test
00872   // stores assertion results in ad_hoc_test_result_.  Initially NULL.
00873   TestCase* current_test_case_;
00874 
00875   // This points to the TestInfo for the currently running test.  It
00876   // changes as Google Test goes through one test after another.  When
00877   // no test is running, this is set to NULL and Google Test stores
00878   // assertion results in ad_hoc_test_result_.  Initially NULL.
00879   TestInfo* current_test_info_;
00880 
00881   // Normally, a user only writes assertions inside a TEST or TEST_F,
00882   // or inside a function called by a TEST or TEST_F.  Since Google
00883   // Test keeps track of which test is current running, it can
00884   // associate such an assertion with the test it belongs to.
00885   //
00886   // If an assertion is encountered when no TEST or TEST_F is running,
00887   // Google Test attributes the assertion result to an imaginary "ad hoc"
00888   // test, and records the result in ad_hoc_test_result_.
00889   TestResult ad_hoc_test_result_;
00890 
00891   // The list of event listeners that can be used to track events inside
00892   // Google Test.
00893   TestEventListeners listeners_;
00894 
00895   // The OS stack trace getter.  Will be deleted when the UnitTest
00896   // object is destructed.  By default, an OsStackTraceGetter is used,
00897   // but the user can set this field to use a custom getter if that is
00898   // desired.
00899   OsStackTraceGetterInterface* os_stack_trace_getter_;
00900 
00901   // True iff PostFlagParsingInit() has been called.
00902   bool post_flag_parse_init_performed_;
00903 
00904   // The random number seed used at the beginning of the test run.
00905   int random_seed_;
00906 
00907   // Our random number generator.
00908   internal::Random random_;
00909 
00910   // The time of the test program start, in ms from the start of the
00911   // UNIX epoch.
00912   TimeInMillis start_timestamp_;
00913 
00914   // How long the test took to run, in milliseconds.
00915   TimeInMillis elapsed_time_;
00916 
00917 #if GTEST_HAS_DEATH_TEST
00918   // The decomposed components of the gtest_internal_run_death_test flag,
00919   // parsed when RUN_ALL_TESTS is called.
00920   internal::scoped_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;
00921   internal::scoped_ptr<internal::DeathTestFactory> death_test_factory_;
00922 #endif  // GTEST_HAS_DEATH_TEST
00923 
00924   // A per-thread stack of traces created by the SCOPED_TRACE() macro.
00925   internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_;
00926 
00927   // The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests()
00928   // starts.
00929   bool catch_exceptions_;
00930 
00931   GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl);
00932 };  // class UnitTestImpl
00933 
00934 // Convenience function for accessing the global UnitTest
00935 // implementation object.
00936 inline UnitTestImpl* GetUnitTestImpl() {
00937   return UnitTest::GetInstance()->impl();
00938 }
00939 
00940 #if GTEST_USES_SIMPLE_RE
00941 
00942 // Internal helper functions for implementing the simple regular
00943 // expression matcher.
00944 GTEST_API_ bool IsInSet(char ch, const char* str);
00945 GTEST_API_ bool IsAsciiDigit(char ch);
00946 GTEST_API_ bool IsAsciiPunct(char ch);
00947 GTEST_API_ bool IsRepeat(char ch);
00948 GTEST_API_ bool IsAsciiWhiteSpace(char ch);
00949 GTEST_API_ bool IsAsciiWordChar(char ch);
00950 GTEST_API_ bool IsValidEscape(char ch);
00951 GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch);
00952 GTEST_API_ bool ValidateRegex(const char* regex);
00953 GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str);
00954 GTEST_API_ bool MatchRepetitionAndRegexAtHead(
00955     bool escaped, char ch, char repeat, const char* regex, const char* str);
00956 GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str);
00957 
00958 #endif  // GTEST_USES_SIMPLE_RE
00959 
00960 // Parses the command line for Google Test flags, without initializing
00961 // other parts of Google Test.
00962 GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv);
00963 GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv);
00964 
00965 #if GTEST_HAS_DEATH_TEST
00966 
00967 // Returns the message describing the last system error, regardless of the
00968 // platform.
00969 GTEST_API_ std::string GetLastErrnoDescription();
00970 
00971 # if GTEST_OS_WINDOWS
00972 // Provides leak-safe Windows kernel handle ownership.
00973 class AutoHandle {
00974  public:
00975   AutoHandle() : handle_(INVALID_HANDLE_VALUE) {}
00976   explicit AutoHandle(HANDLE handle) : handle_(handle) {}
00977 
00978   ~AutoHandle() { Reset(); }
00979 
00980   HANDLE Get() const { return handle_; }
00981   void Reset() { Reset(INVALID_HANDLE_VALUE); }
00982   void Reset(HANDLE handle) {
00983     if (handle != handle_) {
00984       if (handle_ != INVALID_HANDLE_VALUE)
00985         ::CloseHandle(handle_);
00986       handle_ = handle;
00987     }
00988   }
00989 
00990  private:
00991   HANDLE handle_;
00992 
00993   GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle);
00994 };
00995 # endif  // GTEST_OS_WINDOWS
00996 
00997 // Attempts to parse a string into a positive integer pointed to by the
00998 // number parameter.  Returns true if that is possible.
00999 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use
01000 // it here.
01001 template <typename Integer>
01002 bool ParseNaturalNumber(const ::std::string& str, Integer* number) {
01003   // Fail fast if the given string does not begin with a digit;
01004   // this bypasses strtoXXX's "optional leading whitespace and plus
01005   // or minus sign" semantics, which are undesirable here.
01006   if (str.empty() || !IsDigit(str[0])) {
01007     return false;
01008   }
01009   errno = 0;
01010 
01011   char* end;
01012   // BiggestConvertible is the largest integer type that system-provided
01013   // string-to-number conversion routines can return.
01014 
01015 # if GTEST_OS_WINDOWS && !defined(__GNUC__)
01016 
01017   // MSVC and C++ Builder define __int64 instead of the standard long long.
01018   typedef unsigned __int64 BiggestConvertible;
01019   const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10);
01020 
01021 # else
01022 
01023   typedef unsigned long long BiggestConvertible;  // NOLINT
01024   const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10);
01025 
01026 # endif  // GTEST_OS_WINDOWS && !defined(__GNUC__)
01027 
01028   const bool parse_success = *end == '\0' && errno == 0;
01029 
01030   // TODO(vladl@google.com): Convert this to compile time assertion when it is
01031   // available.
01032   GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed));
01033 
01034   const Integer result = static_cast<Integer>(parsed);
01035   if (parse_success && static_cast<BiggestConvertible>(result) == parsed) {
01036     *number = result;
01037     return true;
01038   }
01039   return false;
01040 }
01041 #endif  // GTEST_HAS_DEATH_TEST
01042 
01043 // TestResult contains some private methods that should be hidden from
01044 // Google Test user but are required for testing. This class allow our tests
01045 // to access them.
01046 //
01047 // This class is supplied only for the purpose of testing Google Test's own
01048 // constructs. Do not use it in user tests, either directly or indirectly.
01049 class TestResultAccessor {
01050  public:
01051   static void RecordProperty(TestResult* test_result,
01052                              const std::string& xml_element,
01053                              const TestProperty& property) {
01054     test_result->RecordProperty(xml_element, property);
01055   }
01056 
01057   static void ClearTestPartResults(TestResult* test_result) {
01058     test_result->ClearTestPartResults();
01059   }
01060 
01061   static const std::vector<testing::TestPartResult>& test_part_results(
01062       const TestResult& test_result) {
01063     return test_result.test_part_results();
01064   }
01065 };
01066 
01067 #if GTEST_CAN_STREAM_RESULTS_
01068 
01069 // Streams test results to the given port on the given host machine.
01070 class StreamingListener : public EmptyTestEventListener {
01071  public:
01072   // Abstract base class for writing strings to a socket.
01073   class AbstractSocketWriter {
01074    public:
01075     virtual ~AbstractSocketWriter() {}
01076 
01077     // Sends a string to the socket.
01078     virtual void Send(const string& message) = 0;
01079 
01080     // Closes the socket.
01081     virtual void CloseConnection() {}
01082 
01083     // Sends a string and a newline to the socket.
01084     void SendLn(const string& message) {
01085       Send(message + "\n");
01086     }
01087   };
01088 
01089   // Concrete class for actually writing strings to a socket.
01090   class SocketWriter : public AbstractSocketWriter {
01091    public:
01092     SocketWriter(const string& host, const string& port)
01093         : sockfd_(-1), host_name_(host), port_num_(port) {
01094       MakeConnection();
01095     }
01096 
01097     virtual ~SocketWriter() {
01098       if (sockfd_ != -1)
01099         CloseConnection();
01100     }
01101 
01102     // Sends a string to the socket.
01103     virtual void Send(const string& message) {
01104       GTEST_CHECK_(sockfd_ != -1)
01105           << "Send() can be called only when there is a connection.";
01106 
01107       const int len = static_cast<int>(message.length());
01108       if (write(sockfd_, message.c_str(), len) != len) {
01109         GTEST_LOG_(WARNING)
01110             << "stream_result_to: failed to stream to "
01111             << host_name_ << ":" << port_num_;
01112       }
01113     }
01114 
01115    private:
01116     // Creates a client socket and connects to the server.
01117     void MakeConnection();
01118 
01119     // Closes the socket.
01120     void CloseConnection() {
01121       GTEST_CHECK_(sockfd_ != -1)
01122           << "CloseConnection() can be called only when there is a connection.";
01123 
01124       close(sockfd_);
01125       sockfd_ = -1;
01126     }
01127 
01128     int sockfd_;  // socket file descriptor
01129     const string host_name_;
01130     const string port_num_;
01131 
01132     GTEST_DISALLOW_COPY_AND_ASSIGN_(SocketWriter);
01133   };  // class SocketWriter
01134 
01135   // Escapes '=', '&', '%', and '\n' characters in str as "%xx".
01136   static string UrlEncode(const char* str);
01137 
01138   StreamingListener(const string& host, const string& port)
01139       : socket_writer_(new SocketWriter(host, port)) { Start(); }
01140 
01141   explicit StreamingListener(AbstractSocketWriter* socket_writer)
01142       : socket_writer_(socket_writer) { Start(); }
01143 
01144   void OnTestProgramStart(const UnitTest& /* unit_test */) {
01145     SendLn("event=TestProgramStart");
01146   }
01147 
01148   void OnTestProgramEnd(const UnitTest& unit_test) {
01149     // Note that Google Test current only report elapsed time for each
01150     // test iteration, not for the entire test program.
01151     SendLn("event=TestProgramEnd&passed=" + FormatBool(unit_test.Passed()));
01152 
01153     // Notify the streaming server to stop.
01154     socket_writer_->CloseConnection();
01155   }
01156 
01157   void OnTestIterationStart(const UnitTest& /* unit_test */, int iteration) {
01158     SendLn("event=TestIterationStart&iteration=" +
01159            StreamableToString(iteration));
01160   }
01161 
01162   void OnTestIterationEnd(const UnitTest& unit_test, int /* iteration */) {
01163     SendLn("event=TestIterationEnd&passed=" +
01164            FormatBool(unit_test.Passed()) + "&elapsed_time=" +
01165            StreamableToString(unit_test.elapsed_time()) + "ms");
01166   }
01167 
01168   void OnTestCaseStart(const TestCase& test_case) {
01169     SendLn(std::string("event=TestCaseStart&name=") + test_case.name());
01170   }
01171 
01172   void OnTestCaseEnd(const TestCase& test_case) {
01173     SendLn("event=TestCaseEnd&passed=" + FormatBool(test_case.Passed())
01174            + "&elapsed_time=" + StreamableToString(test_case.elapsed_time())
01175            + "ms");
01176   }
01177 
01178   void OnTestStart(const TestInfo& test_info) {
01179     SendLn(std::string("event=TestStart&name=") + test_info.name());
01180   }
01181 
01182   void OnTestEnd(const TestInfo& test_info) {
01183     SendLn("event=TestEnd&passed=" +
01184            FormatBool((test_info.result())->Passed()) +
01185            "&elapsed_time=" +
01186            StreamableToString((test_info.result())->elapsed_time()) + "ms");
01187   }
01188 
01189   void OnTestPartResult(const TestPartResult& test_part_result) {
01190     const char* file_name = test_part_result.file_name();
01191     if (file_name == NULL)
01192       file_name = "";
01193     SendLn("event=TestPartResult&file=" + UrlEncode(file_name) +
01194            "&line=" + StreamableToString(test_part_result.line_number()) +
01195            "&message=" + UrlEncode(test_part_result.message()));
01196   }
01197 
01198  private:
01199   // Sends the given message and a newline to the socket.
01200   void SendLn(const string& message) { socket_writer_->SendLn(message); }
01201 
01202   // Called at the start of streaming to notify the receiver what
01203   // protocol we are using.
01204   void Start() { SendLn("gtest_streaming_protocol_version=1.0"); }
01205 
01206   string FormatBool(bool value) { return value ? "1" : "0"; }
01207 
01208   const scoped_ptr<AbstractSocketWriter> socket_writer_;
01209 
01210   GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener);
01211 };  // class StreamingListener
01212 
01213 #endif  // GTEST_CAN_STREAM_RESULTS_
01214 
01215 }  // namespace internal
01216 }  // namespace testing
01217 
01218 #endif  // GTEST_SRC_GTEST_INTERNAL_INL_H_