Home | History | Annotate | Download | only in src
      1 // Copyright 2005, Google Inc.
      2 // All rights reserved.
      3 //
      4 // Redistribution and use in source and binary forms, with or without
      5 // modification, are permitted provided that the following conditions are
      6 // met:
      7 //
      8 //     * Redistributions of source code must retain the above copyright
      9 // notice, this list of conditions and the following disclaimer.
     10 //     * Redistributions in binary form must reproduce the above
     11 // copyright notice, this list of conditions and the following disclaimer
     12 // in the documentation and/or other materials provided with the
     13 // distribution.
     14 //     * Neither the name of Google Inc. nor the names of its
     15 // contributors may be used to endorse or promote products derived from
     16 // this software without specific prior written permission.
     17 //
     18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
     19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
     20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
     21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
     22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
     23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
     24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
     28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     29 
     30 // Utility functions and classes used by the Google C++ testing framework.
     31 //
     32 // Author: wan (at) google.com (Zhanyong Wan)
     33 //
     34 // This file contains purely Google Test's internal implementation.  Please
     35 // DO NOT #INCLUDE IT IN A USER PROGRAM.
     36 
     37 #ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_
     38 #define GTEST_SRC_GTEST_INTERNAL_INL_H_
     39 
     40 // GTEST_IMPLEMENTATION_ is defined to 1 iff the current translation unit is
     41 // part of Google Test's implementation; otherwise it's undefined.
     42 #if !GTEST_IMPLEMENTATION_
     43 // A user is trying to include this from his code - just say no.
     44 # error "gtest-internal-inl.h is part of Google Test's internal implementation."
     45 # error "It must not be included except by Google Test itself."
     46 #endif  // GTEST_IMPLEMENTATION_
     47 
     48 #ifndef _WIN32_WCE
     49 # include <errno.h>
     50 #endif  // !_WIN32_WCE
     51 #include <stddef.h>
     52 #include <stdlib.h>  // For strtoll/_strtoul64/malloc/free.
     53 #include <string.h>  // For memmove.
     54 
     55 #include <algorithm>
     56 #include <string>
     57 #include <vector>
     58 
     59 #include "gtest/internal/gtest-port.h"
     60 
     61 #if GTEST_CAN_STREAM_RESULTS_
     62 # include <arpa/inet.h>  // NOLINT
     63 # include <netdb.h>  // NOLINT
     64 #endif
     65 
     66 #if GTEST_OS_WINDOWS
     67 # include <windows.h>  // NOLINT
     68 #endif  // GTEST_OS_WINDOWS
     69 
     70 #include "gtest/gtest.h"  // NOLINT
     71 #include "gtest/gtest-spi.h"
     72 
     73 namespace testing {
     74 
     75 // Declares the flags.
     76 //
     77 // We don't want the users to modify this flag in the code, but want
     78 // Google Test's own unit tests to be able to access it. Therefore we
     79 // declare it here as opposed to in gtest.h.
     80 GTEST_DECLARE_bool_(death_test_use_fork);
     81 
     82 namespace internal {
     83 
     84 // The value of GetTestTypeId() as seen from within the Google Test
     85 // library.  This is solely for testing GetTestTypeId().
     86 GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest;
     87 
     88 // Names of the flags (needed for parsing Google Test flags).
     89 const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests";
     90 const char kBreakOnFailureFlag[] = "break_on_failure";
     91 const char kCatchExceptionsFlag[] = "catch_exceptions";
     92 const char kColorFlag[] = "color";
     93 const char kFilterFlag[] = "filter";
     94 const char kListTestsFlag[] = "list_tests";
     95 const char kOutputFlag[] = "output";
     96 const char kPrintTimeFlag[] = "print_time";
     97 const char kRandomSeedFlag[] = "random_seed";
     98 const char kRepeatFlag[] = "repeat";
     99 const char kShuffleFlag[] = "shuffle";
    100 const char kStackTraceDepthFlag[] = "stack_trace_depth";
    101 const char kStreamResultToFlag[] = "stream_result_to";
    102 const char kThrowOnFailureFlag[] = "throw_on_failure";
    103 
    104 // A valid random seed must be in [1, kMaxRandomSeed].
    105 const int kMaxRandomSeed = 99999;
    106 
    107 // g_help_flag is true iff the --help flag or an equivalent form is
    108 // specified on the command line.
    109 GTEST_API_ extern bool g_help_flag;
    110 
    111 // Returns the current time in milliseconds.
    112 GTEST_API_ TimeInMillis GetTimeInMillis();
    113 
    114 // Returns true iff Google Test should use colors in the output.
    115 GTEST_API_ bool ShouldUseColor(bool stdout_is_tty);
    116 
    117 // Formats the given time in milliseconds as seconds.
    118 GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms);
    119 
    120 // Converts the given time in milliseconds to a date string in the ISO 8601
    121 // format, without the timezone information.  N.B.: due to the use the
    122 // non-reentrant localtime() function, this function is not thread safe.  Do
    123 // not use it in any code that can be called from multiple threads.
    124 GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms);
    125 
    126 // Parses a string for an Int32 flag, in the form of "--flag=value".
    127 //
    128 // On success, stores the value of the flag in *value, and returns
    129 // true.  On failure, returns false without changing *value.
    130 GTEST_API_ bool ParseInt32Flag(
    131     const char* str, const char* flag, Int32* value);
    132 
    133 // Returns a random seed in range [1, kMaxRandomSeed] based on the
    134 // given --gtest_random_seed flag value.
    135 inline int GetRandomSeedFromFlag(Int32 random_seed_flag) {
    136   const unsigned int raw_seed = (random_seed_flag == 0) ?
    137       static_cast<unsigned int>(GetTimeInMillis()) :
    138       static_cast<unsigned int>(random_seed_flag);
    139 
    140   // Normalizes the actual seed to range [1, kMaxRandomSeed] such that
    141   // it's easy to type.
    142   const int normalized_seed =
    143       static_cast<int>((raw_seed - 1U) %
    144                        static_cast<unsigned int>(kMaxRandomSeed)) + 1;
    145   return normalized_seed;
    146 }
    147 
    148 // Returns the first valid random seed after 'seed'.  The behavior is
    149 // undefined if 'seed' is invalid.  The seed after kMaxRandomSeed is
    150 // considered to be 1.
    151 inline int GetNextRandomSeed(int seed) {
    152   GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed)
    153       << "Invalid random seed " << seed << " - must be in [1, "
    154       << kMaxRandomSeed << "].";
    155   const int next_seed = seed + 1;
    156   return (next_seed > kMaxRandomSeed) ? 1 : next_seed;
    157 }
    158 
    159 // This class saves the values of all Google Test flags in its c'tor, and
    160 // restores them in its d'tor.
    161 class GTestFlagSaver {
    162  public:
    163   // The c'tor.
    164   GTestFlagSaver() {
    165     also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests);
    166     break_on_failure_ = GTEST_FLAG(break_on_failure);
    167     catch_exceptions_ = GTEST_FLAG(catch_exceptions);
    168     color_ = GTEST_FLAG(color);
    169     death_test_style_ = GTEST_FLAG(death_test_style);
    170     death_test_use_fork_ = GTEST_FLAG(death_test_use_fork);
    171     filter_ = GTEST_FLAG(filter);
    172     internal_run_death_test_ = GTEST_FLAG(internal_run_death_test);
    173     list_tests_ = GTEST_FLAG(list_tests);
    174     output_ = GTEST_FLAG(output);
    175     print_time_ = GTEST_FLAG(print_time);
    176     random_seed_ = GTEST_FLAG(random_seed);
    177     repeat_ = GTEST_FLAG(repeat);
    178     shuffle_ = GTEST_FLAG(shuffle);
    179     stack_trace_depth_ = GTEST_FLAG(stack_trace_depth);
    180     stream_result_to_ = GTEST_FLAG(stream_result_to);
    181     throw_on_failure_ = GTEST_FLAG(throw_on_failure);
    182   }
    183 
    184   // The d'tor is not virtual.  DO NOT INHERIT FROM THIS CLASS.
    185   ~GTestFlagSaver() {
    186     GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_;
    187     GTEST_FLAG(break_on_failure) = break_on_failure_;
    188     GTEST_FLAG(catch_exceptions) = catch_exceptions_;
    189     GTEST_FLAG(color) = color_;
    190     GTEST_FLAG(death_test_style) = death_test_style_;
    191     GTEST_FLAG(death_test_use_fork) = death_test_use_fork_;
    192     GTEST_FLAG(filter) = filter_;
    193     GTEST_FLAG(internal_run_death_test) = internal_run_death_test_;
    194     GTEST_FLAG(list_tests) = list_tests_;
    195     GTEST_FLAG(output) = output_;
    196     GTEST_FLAG(print_time) = print_time_;
    197     GTEST_FLAG(random_seed) = random_seed_;
    198     GTEST_FLAG(repeat) = repeat_;
    199     GTEST_FLAG(shuffle) = shuffle_;
    200     GTEST_FLAG(stack_trace_depth) = stack_trace_depth_;
    201     GTEST_FLAG(stream_result_to) = stream_result_to_;
    202     GTEST_FLAG(throw_on_failure) = throw_on_failure_;
    203   }
    204 
    205  private:
    206   // Fields for saving the original values of flags.
    207   bool also_run_disabled_tests_;
    208   bool break_on_failure_;
    209   bool catch_exceptions_;
    210   std::string color_;
    211   std::string death_test_style_;
    212   bool death_test_use_fork_;
    213   std::string filter_;
    214   std::string internal_run_death_test_;
    215   bool list_tests_;
    216   std::string output_;
    217   bool print_time_;
    218   internal::Int32 random_seed_;
    219   internal::Int32 repeat_;
    220   bool shuffle_;
    221   internal::Int32 stack_trace_depth_;
    222   std::string stream_result_to_;
    223   bool throw_on_failure_;
    224 } GTEST_ATTRIBUTE_UNUSED_;
    225 
    226 // Converts a Unicode code point to a narrow string in UTF-8 encoding.
    227 // code_point parameter is of type UInt32 because wchar_t may not be
    228 // wide enough to contain a code point.
    229 // If the code_point is not a valid Unicode code point
    230 // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
    231 // to "(Invalid Unicode 0xXXXXXXXX)".
    232 GTEST_API_ std::string CodePointToUtf8(UInt32 code_point);
    233 
    234 // Converts a wide string to a narrow string in UTF-8 encoding.
    235 // The wide string is assumed to have the following encoding:
    236 //   UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
    237 //   UTF-32 if sizeof(wchar_t) == 4 (on Linux)
    238 // Parameter str points to a null-terminated wide string.
    239 // Parameter num_chars may additionally limit the number
    240 // of wchar_t characters processed. -1 is used when the entire string
    241 // should be processed.
    242 // If the string contains code points that are not valid Unicode code points
    243 // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
    244 // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
    245 // and contains invalid UTF-16 surrogate pairs, values in those pairs
    246 // will be encoded as individual Unicode characters from Basic Normal Plane.
    247 GTEST_API_ std::string WideStringToUtf8(const wchar_t* str, int num_chars);
    248 
    249 // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
    250 // if the variable is present. If a file already exists at this location, this
    251 // function will write over it. If the variable is present, but the file cannot
    252 // be created, prints an error and exits.
    253 void WriteToShardStatusFileIfNeeded();
    254 
    255 // Checks whether sharding is enabled by examining the relevant
    256 // environment variable values. If the variables are present,
    257 // but inconsistent (e.g., shard_index >= total_shards), prints
    258 // an error and exits. If in_subprocess_for_death_test, sharding is
    259 // disabled because it must only be applied to the original test
    260 // process. Otherwise, we could filter out death tests we intended to execute.
    261 GTEST_API_ bool ShouldShard(const char* total_shards_str,
    262                             const char* shard_index_str,
    263                             bool in_subprocess_for_death_test);
    264 
    265 // Parses the environment variable var as an Int32. If it is unset,
    266 // returns default_val. If it is not an Int32, prints an error and
    267 // and aborts.
    268 GTEST_API_ Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val);
    269 
    270 // Given the total number of shards, the shard index, and the test id,
    271 // returns true iff the test should be run on this shard. The test id is
    272 // some arbitrary but unique non-negative integer assigned to each test
    273 // method. Assumes that 0 <= shard_index < total_shards.
    274 GTEST_API_ bool ShouldRunTestOnShard(
    275     int total_shards, int shard_index, int test_id);
    276 
    277 // STL container utilities.
    278 
    279 // Returns the number of elements in the given container that satisfy
    280 // the given predicate.
    281 template <class Container, typename Predicate>
    282 inline int CountIf(const Container& c, Predicate predicate) {
    283   // Implemented as an explicit loop since std::count_if() in libCstd on
    284   // Solaris has a non-standard signature.
    285   int count = 0;
    286   for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) {
    287     if (predicate(*it))
    288       ++count;
    289   }
    290   return count;
    291 }
    292 
    293 // Applies a function/functor to each element in the container.
    294 template <class Container, typename Functor>
    295 void ForEach(const Container& c, Functor functor) {
    296   std::for_each(c.begin(), c.end(), functor);
    297 }
    298 
    299 // Returns the i-th element of the vector, or default_value if i is not
    300 // in range [0, v.size()).
    301 template <typename E>
    302 inline E GetElementOr(const std::vector<E>& v, int i, E default_value) {
    303   return (i < 0 || i >= static_cast<int>(v.size())) ? default_value : v[i];
    304 }
    305 
    306 // Performs an in-place shuffle of a range of the vector's elements.
    307 // 'begin' and 'end' are element indices as an STL-style range;
    308 // i.e. [begin, end) are shuffled, where 'end' == size() means to
    309 // shuffle to the end of the vector.
    310 template <typename E>
    311 void ShuffleRange(internal::Random* random, int begin, int end,
    312                   std::vector<E>* v) {
    313   const int size = static_cast<int>(v->size());
    314   GTEST_CHECK_(0 <= begin && begin <= size)
    315       << "Invalid shuffle range start " << begin << ": must be in range [0, "
    316       << size << "].";
    317   GTEST_CHECK_(begin <= end && end <= size)
    318       << "Invalid shuffle range finish " << end << ": must be in range ["
    319       << begin << ", " << size << "].";
    320 
    321   // Fisher-Yates shuffle, from
    322   // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
    323   for (int range_width = end - begin; range_width >= 2; range_width--) {
    324     const int last_in_range = begin + range_width - 1;
    325     const int selected = begin + random->Generate(range_width);
    326     std::swap((*v)[selected], (*v)[last_in_range]);
    327   }
    328 }
    329 
    330 // Performs an in-place shuffle of the vector's elements.
    331 template <typename E>
    332 inline void Shuffle(internal::Random* random, std::vector<E>* v) {
    333   ShuffleRange(random, 0, static_cast<int>(v->size()), v);
    334 }
    335 
    336 // A function for deleting an object.  Handy for being used as a
    337 // functor.
    338 template <typename T>
    339 static void Delete(T* x) {
    340   delete x;
    341 }
    342 
    343 // A predicate that checks the key of a TestProperty against a known key.
    344 //
    345 // TestPropertyKeyIs is copyable.
    346 class TestPropertyKeyIs {
    347  public:
    348   // Constructor.
    349   //
    350   // TestPropertyKeyIs has NO default constructor.
    351   explicit TestPropertyKeyIs(const char* key)
    352       : key_(key) {}
    353 
    354   // Returns true iff the test name of test property matches on key_.
    355   bool operator()(const TestProperty& test_property) const {
    356     return test_property.key() == key_;
    357   }
    358 
    359  private:
    360   std::string key_;
    361 };
    362 
    363 // Class UnitTestOptions.
    364 //
    365 // This class contains functions for processing options the user
    366 // specifies when running the tests.  It has only static members.
    367 //
    368 // In most cases, the user can specify an option using either an
    369 // environment variable or a command line flag.  E.g. you can set the
    370 // test filter using either GTEST_FILTER or --gtest_filter.  If both
    371 // the variable and the flag are present, the latter overrides the
    372 // former.
    373 class GTEST_API_ UnitTestOptions {
    374  public:
    375   // Functions for processing the gtest_output flag.
    376 
    377   // Returns the output format, or "" for normal printed output.
    378   static std::string GetOutputFormat();
    379 
    380   // Returns the absolute path of the requested output file, or the
    381   // default (test_detail.xml in the original working directory) if
    382   // none was explicitly specified.
    383   static std::string GetAbsolutePathToOutputFile();
    384 
    385   // Functions for processing the gtest_filter flag.
    386 
    387   // Returns true iff the wildcard pattern matches the string.  The
    388   // first ':' or '\0' character in pattern marks the end of it.
    389   //
    390   // This recursive algorithm isn't very efficient, but is clear and
    391   // works well enough for matching test names, which are short.
    392   static bool PatternMatchesString(const char *pattern, const char *str);
    393 
    394   // Returns true iff the user-specified filter matches the test case
    395   // name and the test name.
    396   static bool FilterMatchesTest(const std::string &test_case_name,
    397                                 const std::string &test_name);
    398 
    399 #if GTEST_OS_WINDOWS
    400   // Function for supporting the gtest_catch_exception flag.
    401 
    402   // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
    403   // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
    404   // This function is useful as an __except condition.
    405   static int GTestShouldProcessSEH(DWORD exception_code);
    406 #endif  // GTEST_OS_WINDOWS
    407 
    408   // Returns true if "name" matches the ':' separated list of glob-style
    409   // filters in "filter".
    410   static bool MatchesFilter(const std::string& name, const char* filter);
    411 };
    412 
    413 // Returns the current application's name, removing directory path if that
    414 // is present.  Used by UnitTestOptions::GetOutputFile.
    415 GTEST_API_ FilePath GetCurrentExecutableName();
    416 
    417 // The role interface for getting the OS stack trace as a string.
    418 class OsStackTraceGetterInterface {
    419  public:
    420   OsStackTraceGetterInterface() {}
    421   virtual ~OsStackTraceGetterInterface() {}
    422 
    423   // Returns the current OS stack trace as an std::string.  Parameters:
    424   //
    425   //   max_depth  - the maximum number of stack frames to be included
    426   //                in the trace.
    427   //   skip_count - the number of top frames to be skipped; doesn't count
    428   //                against max_depth.
    429   virtual string CurrentStackTrace(int max_depth, int skip_count) = 0;
    430 
    431   // UponLeavingGTest() should be called immediately before Google Test calls
    432   // user code. It saves some information about the current stack that
    433   // CurrentStackTrace() will use to find and hide Google Test stack frames.
    434   virtual void UponLeavingGTest() = 0;
    435 
    436  private:
    437   GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface);
    438 };
    439 
    440 // A working implementation of the OsStackTraceGetterInterface interface.
    441 class OsStackTraceGetter : public OsStackTraceGetterInterface {
    442  public:
    443   OsStackTraceGetter() : caller_frame_(NULL) {}
    444 
    445   virtual string CurrentStackTrace(int max_depth, int skip_count)
    446       GTEST_LOCK_EXCLUDED_(mutex_);
    447 
    448   virtual void UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_);
    449 
    450   // This string is inserted in place of stack frames that are part of
    451   // Google Test's implementation.
    452   static const char* const kElidedFramesMarker;
    453 
    454  private:
    455   Mutex mutex_;  // protects all internal state
    456 
    457   // We save the stack frame below the frame that calls user code.
    458   // We do this because the address of the frame immediately below
    459   // the user code changes between the call to UponLeavingGTest()
    460   // and any calls to CurrentStackTrace() from within the user code.
    461   void* caller_frame_;
    462 
    463   GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter);
    464 };
    465 
    466 // Information about a Google Test trace point.
    467 struct TraceInfo {
    468   const char* file;
    469   int line;
    470   std::string message;
    471 };
    472 
    473 // This is the default global test part result reporter used in UnitTestImpl.
    474 // This class should only be used by UnitTestImpl.
    475 class DefaultGlobalTestPartResultReporter
    476   : public TestPartResultReporterInterface {
    477  public:
    478   explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test);
    479   // Implements the TestPartResultReporterInterface. Reports the test part
    480   // result in the current test.
    481   virtual void ReportTestPartResult(const TestPartResult& result);
    482 
    483  private:
    484   UnitTestImpl* const unit_test_;
    485 
    486   GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter);
    487 };
    488 
    489 // This is the default per thread test part result reporter used in
    490 // UnitTestImpl. This class should only be used by UnitTestImpl.
    491 class DefaultPerThreadTestPartResultReporter
    492     : public TestPartResultReporterInterface {
    493  public:
    494   explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test);
    495   // Implements the TestPartResultReporterInterface. The implementation just
    496   // delegates to the current global test part result reporter of *unit_test_.
    497   virtual void ReportTestPartResult(const TestPartResult& result);
    498 
    499  private:
    500   UnitTestImpl* const unit_test_;
    501 
    502   GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter);
    503 };
    504 
    505 // The private implementation of the UnitTest class.  We don't protect
    506 // the methods under a mutex, as this class is not accessible by a
    507 // user and the UnitTest class that delegates work to this class does
    508 // proper locking.
    509 class GTEST_API_ UnitTestImpl {
    510  public:
    511   explicit UnitTestImpl(UnitTest* parent);
    512   virtual ~UnitTestImpl();
    513 
    514   // There are two different ways to register your own TestPartResultReporter.
    515   // You can register your own repoter to listen either only for test results
    516   // from the current thread or for results from all threads.
    517   // By default, each per-thread test result repoter just passes a new
    518   // TestPartResult to the global test result reporter, which registers the
    519   // test part result for the currently running test.
    520 
    521   // Returns the global test part result reporter.
    522   TestPartResultReporterInterface* GetGlobalTestPartResultReporter();
    523 
    524   // Sets the global test part result reporter.
    525   void SetGlobalTestPartResultReporter(
    526       TestPartResultReporterInterface* reporter);
    527 
    528   // Returns the test part result reporter for the current thread.
    529   TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread();
    530 
    531   // Sets the test part result reporter for the current thread.
    532   void SetTestPartResultReporterForCurrentThread(
    533       TestPartResultReporterInterface* reporter);
    534 
    535   // Gets the number of successful test cases.
    536   int successful_test_case_count() const;
    537 
    538   // Gets the number of failed test cases.
    539   int failed_test_case_count() const;
    540 
    541   // Gets the number of all test cases.
    542   int total_test_case_count() const;
    543 
    544   // Gets the number of all test cases that contain at least one test
    545   // that should run.
    546   int test_case_to_run_count() const;
    547 
    548   // Gets the number of successful tests.
    549   int successful_test_count() const;
    550 
    551   // Gets the number of failed tests.
    552   int failed_test_count() const;
    553 
    554   // Gets the number of disabled tests.
    555   int disabled_test_count() const;
    556 
    557   // Gets the number of all tests.
    558   int total_test_count() const;
    559 
    560   // Gets the number of tests that should run.
    561   int test_to_run_count() const;
    562 
    563   // Gets the time of the test program start, in ms from the start of the
    564   // UNIX epoch.
    565   TimeInMillis start_timestamp() const { return start_timestamp_; }
    566 
    567   // Gets the elapsed time, in milliseconds.
    568   TimeInMillis elapsed_time() const { return elapsed_time_; }
    569 
    570   // Returns true iff the unit test passed (i.e. all test cases passed).
    571   bool Passed() const { return !Failed(); }
    572 
    573   // Returns true iff the unit test failed (i.e. some test case failed
    574   // or something outside of all tests failed).
    575   bool Failed() const {
    576     return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed();
    577   }
    578 
    579   // Gets the i-th test case among all the test cases. i can range from 0 to
    580   // total_test_case_count() - 1. If i is not in that range, returns NULL.
    581   const TestCase* GetTestCase(int i) const {
    582     const int index = GetElementOr(test_case_indices_, i, -1);
    583     return index < 0 ? NULL : test_cases_[i];
    584   }
    585 
    586   // Gets the i-th test case among all the test cases. i can range from 0 to
    587   // total_test_case_count() - 1. If i is not in that range, returns NULL.
    588   TestCase* GetMutableTestCase(int i) {
    589     const int index = GetElementOr(test_case_indices_, i, -1);
    590     return index < 0 ? NULL : test_cases_[index];
    591   }
    592 
    593   // Provides access to the event listener list.
    594   TestEventListeners* listeners() { return &listeners_; }
    595 
    596   // Returns the TestResult for the test that's currently running, or
    597   // the TestResult for the ad hoc test if no test is running.
    598   TestResult* current_test_result();
    599 
    600   // Returns the TestResult for the ad hoc test.
    601   const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; }
    602 
    603   // Sets the OS stack trace getter.
    604   //
    605   // Does nothing if the input and the current OS stack trace getter
    606   // are the same; otherwise, deletes the old getter and makes the
    607   // input the current getter.
    608   void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter);
    609 
    610   // Returns the current OS stack trace getter if it is not NULL;
    611   // otherwise, creates an OsStackTraceGetter, makes it the current
    612   // getter, and returns it.
    613   OsStackTraceGetterInterface* os_stack_trace_getter();
    614 
    615   // Returns the current OS stack trace as an std::string.
    616   //
    617   // The maximum number of stack frames to be included is specified by
    618   // the gtest_stack_trace_depth flag.  The skip_count parameter
    619   // specifies the number of top frames to be skipped, which doesn't
    620   // count against the number of frames to be included.
    621   //
    622   // For example, if Foo() calls Bar(), which in turn calls
    623   // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
    624   // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
    625   std::string CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_;
    626 
    627   // Finds and returns a TestCase with the given name.  If one doesn't
    628   // exist, creates one and returns it.
    629   //
    630   // Arguments:
    631   //
    632   //   test_case_name: name of the test case
    633   //   type_param:     the name of the test's type parameter, or NULL if
    634   //                   this is not a typed or a type-parameterized test.
    635   //   set_up_tc:      pointer to the function that sets up the test case
    636   //   tear_down_tc:   pointer to the function that tears down the test case
    637   TestCase* GetTestCase(const char* test_case_name,
    638                         const char* type_param,
    639                         Test::SetUpTestCaseFunc set_up_tc,
    640                         Test::TearDownTestCaseFunc tear_down_tc);
    641 
    642   // Adds a TestInfo to the unit test.
    643   //
    644   // Arguments:
    645   //
    646   //   set_up_tc:    pointer to the function that sets up the test case
    647   //   tear_down_tc: pointer to the function that tears down the test case
    648   //   test_info:    the TestInfo object
    649   void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc,
    650                    Test::TearDownTestCaseFunc tear_down_tc,
    651                    TestInfo* test_info) {
    652     // In order to support thread-safe death tests, we need to
    653     // remember the original working directory when the test program
    654     // was first invoked.  We cannot do this in RUN_ALL_TESTS(), as
    655     // the user may have changed the current directory before calling
    656     // RUN_ALL_TESTS().  Therefore we capture the current directory in
    657     // AddTestInfo(), which is called to register a TEST or TEST_F
    658     // before main() is reached.
    659     if (original_working_dir_.IsEmpty()) {
    660       original_working_dir_.Set(FilePath::GetCurrentDir());
    661       GTEST_CHECK_(!original_working_dir_.IsEmpty())
    662           << "Failed to get the current working directory.";
    663     }
    664 
    665     GetTestCase(test_info->test_case_name(),
    666                 test_info->type_param(),
    667                 set_up_tc,
    668                 tear_down_tc)->AddTestInfo(test_info);
    669   }
    670 
    671 #if GTEST_HAS_PARAM_TEST
    672   // Returns ParameterizedTestCaseRegistry object used to keep track of
    673   // value-parameterized tests and instantiate and register them.
    674   internal::ParameterizedTestCaseRegistry& parameterized_test_registry() {
    675     return parameterized_test_registry_;
    676   }
    677 #endif  // GTEST_HAS_PARAM_TEST
    678 
    679   // Sets the TestCase object for the test that's currently running.
    680   void set_current_test_case(TestCase* a_current_test_case) {
    681     current_test_case_ = a_current_test_case;
    682   }
    683 
    684   // Sets the TestInfo object for the test that's currently running.  If
    685   // current_test_info is NULL, the assertion results will be stored in
    686   // ad_hoc_test_result_.
    687   void set_current_test_info(TestInfo* a_current_test_info) {
    688     current_test_info_ = a_current_test_info;
    689   }
    690 
    691   // Registers all parameterized tests defined using TEST_P and
    692   // INSTANTIATE_TEST_CASE_P, creating regular tests for each test/parameter
    693   // combination. This method can be called more then once; it has guards
    694   // protecting from registering the tests more then once.  If
    695   // value-parameterized tests are disabled, RegisterParameterizedTests is
    696   // present but does nothing.
    697   void RegisterParameterizedTests();
    698 
    699   // Runs all tests in this UnitTest object, prints the result, and
    700   // returns true if all tests are successful.  If any exception is
    701   // thrown during a test, this test is considered to be failed, but
    702   // the rest of the tests will still be run.
    703   bool RunAllTests();
    704 
    705   // Clears the results of all tests, except the ad hoc tests.
    706   void ClearNonAdHocTestResult() {
    707     ForEach(test_cases_, TestCase::ClearTestCaseResult);
    708   }
    709 
    710   // Clears the results of ad-hoc test assertions.
    711   void ClearAdHocTestResult() {
    712     ad_hoc_test_result_.Clear();
    713   }
    714 
    715   enum ReactionToSharding {
    716     HONOR_SHARDING_PROTOCOL,
    717     IGNORE_SHARDING_PROTOCOL
    718   };
    719 
    720   // Matches the full name of each test against the user-specified
    721   // filter to decide whether the test should run, then records the
    722   // result in each TestCase and TestInfo object.
    723   // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests
    724   // based on sharding variables in the environment.
    725   // Returns the number of tests that should run.
    726   int FilterTests(ReactionToSharding shard_tests);
    727 
    728   // Prints the names of the tests matching the user-specified filter flag.
    729   void ListTestsMatchingFilter();
    730 
    731   const TestCase* current_test_case() const { return current_test_case_; }
    732   TestInfo* current_test_info() { return current_test_info_; }
    733   const TestInfo* current_test_info() const { return current_test_info_; }
    734 
    735   // Returns the vector of environments that need to be set-up/torn-down
    736   // before/after the tests are run.
    737   std::vector<Environment*>& environments() { return environments_; }
    738 
    739   // Getters for the per-thread Google Test trace stack.
    740   std::vector<TraceInfo>& gtest_trace_stack() {
    741     return *(gtest_trace_stack_.pointer());
    742   }
    743   const std::vector<TraceInfo>& gtest_trace_stack() const {
    744     return gtest_trace_stack_.get();
    745   }
    746 
    747 #if GTEST_HAS_DEATH_TEST
    748   void InitDeathTestSubprocessControlInfo() {
    749     internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());
    750   }
    751   // Returns a pointer to the parsed --gtest_internal_run_death_test
    752   // flag, or NULL if that flag was not specified.
    753   // This information is useful only in a death test child process.
    754   // Must not be called before a call to InitGoogleTest.
    755   const InternalRunDeathTestFlag* internal_run_death_test_flag() const {
    756     return internal_run_death_test_flag_.get();
    757   }
    758 
    759   // Returns a pointer to the current death test factory.
    760   internal::DeathTestFactory* death_test_factory() {
    761     return death_test_factory_.get();
    762   }
    763 
    764   void SuppressTestEventsIfInSubprocess();
    765 
    766   friend class ReplaceDeathTestFactory;
    767 #endif  // GTEST_HAS_DEATH_TEST
    768 
    769   // Initializes the event listener performing XML output as specified by
    770   // UnitTestOptions. Must not be called before InitGoogleTest.
    771   void ConfigureXmlOutput();
    772 
    773 #if GTEST_CAN_STREAM_RESULTS_
    774   // Initializes the event listener for streaming test results to a socket.
    775   // Must not be called before InitGoogleTest.
    776   void ConfigureStreamingOutput();
    777 #endif
    778 
    779   // Performs initialization dependent upon flag values obtained in
    780   // ParseGoogleTestFlagsOnly.  Is called from InitGoogleTest after the call to
    781   // ParseGoogleTestFlagsOnly.  In case a user neglects to call InitGoogleTest
    782   // this function is also called from RunAllTests.  Since this function can be
    783   // called more than once, it has to be idempotent.
    784   void PostFlagParsingInit();
    785 
    786   // Gets the random seed used at the start of the current test iteration.
    787   int random_seed() const { return random_seed_; }
    788 
    789   // Gets the random number generator.
    790   internal::Random* random() { return &random_; }
    791 
    792   // Shuffles all test cases, and the tests within each test case,
    793   // making sure that death tests are still run first.
    794   void ShuffleTests();
    795 
    796   // Restores the test cases and tests to their order before the first shuffle.
    797   void UnshuffleTests();
    798 
    799   // Returns the value of GTEST_FLAG(catch_exceptions) at the moment
    800   // UnitTest::Run() starts.
    801   bool catch_exceptions() const { return catch_exceptions_; }
    802 
    803  private:
    804   friend class ::testing::UnitTest;
    805 
    806   // Used by UnitTest::Run() to capture the state of
    807   // GTEST_FLAG(catch_exceptions) at the moment it starts.
    808   void set_catch_exceptions(bool value) { catch_exceptions_ = value; }
    809 
    810   // The UnitTest object that owns this implementation object.
    811   UnitTest* const parent_;
    812 
    813   // The working directory when the first TEST() or TEST_F() was
    814   // executed.
    815   internal::FilePath original_working_dir_;
    816 
    817   // The default test part result reporters.
    818   DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_;
    819   DefaultPerThreadTestPartResultReporter
    820       default_per_thread_test_part_result_reporter_;
    821 
    822   // Points to (but doesn't own) the global test part result reporter.
    823   TestPartResultReporterInterface* global_test_part_result_repoter_;
    824 
    825   // Protects read and write access to global_test_part_result_reporter_.
    826   internal::Mutex global_test_part_result_reporter_mutex_;
    827 
    828   // Points to (but doesn't own) the per-thread test part result reporter.
    829   internal::ThreadLocal<TestPartResultReporterInterface*>
    830       per_thread_test_part_result_reporter_;
    831 
    832   // The vector of environments that need to be set-up/torn-down
    833   // before/after the tests are run.
    834   std::vector<Environment*> environments_;
    835 
    836   // The vector of TestCases in their original order.  It owns the
    837   // elements in the vector.
    838   std::vector<TestCase*> test_cases_;
    839 
    840   // Provides a level of indirection for the test case list to allow
    841   // easy shuffling and restoring the test case order.  The i-th
    842   // element of this vector is the index of the i-th test case in the
    843   // shuffled order.
    844   std::vector<int> test_case_indices_;
    845 
    846 #if GTEST_HAS_PARAM_TEST
    847   // ParameterizedTestRegistry object used to register value-parameterized
    848   // tests.
    849   internal::ParameterizedTestCaseRegistry parameterized_test_registry_;
    850 
    851   // Indicates whether RegisterParameterizedTests() has been called already.
    852   bool parameterized_tests_registered_;
    853 #endif  // GTEST_HAS_PARAM_TEST
    854 
    855   // Index of the last death test case registered.  Initially -1.
    856   int last_death_test_case_;
    857 
    858   // This points to the TestCase for the currently running test.  It
    859   // changes as Google Test goes through one test case after another.
    860   // When no test is running, this is set to NULL and Google Test
    861   // stores assertion results in ad_hoc_test_result_.  Initially NULL.
    862   TestCase* current_test_case_;
    863 
    864   // This points to the TestInfo for the currently running test.  It
    865   // changes as Google Test goes through one test after another.  When
    866   // no test is running, this is set to NULL and Google Test stores
    867   // assertion results in ad_hoc_test_result_.  Initially NULL.
    868   TestInfo* current_test_info_;
    869 
    870   // Normally, a user only writes assertions inside a TEST or TEST_F,
    871   // or inside a function called by a TEST or TEST_F.  Since Google
    872   // Test keeps track of which test is current running, it can
    873   // associate such an assertion with the test it belongs to.
    874   //
    875   // If an assertion is encountered when no TEST or TEST_F is running,
    876   // Google Test attributes the assertion result to an imaginary "ad hoc"
    877   // test, and records the result in ad_hoc_test_result_.
    878   TestResult ad_hoc_test_result_;
    879 
    880   // The list of event listeners that can be used to track events inside
    881   // Google Test.
    882   TestEventListeners listeners_;
    883 
    884   // The OS stack trace getter.  Will be deleted when the UnitTest
    885   // object is destructed.  By default, an OsStackTraceGetter is used,
    886   // but the user can set this field to use a custom getter if that is
    887   // desired.
    888   OsStackTraceGetterInterface* os_stack_trace_getter_;
    889 
    890   // True iff PostFlagParsingInit() has been called.
    891   bool post_flag_parse_init_performed_;
    892 
    893   // The random number seed used at the beginning of the test run.
    894   int random_seed_;
    895 
    896   // Our random number generator.
    897   internal::Random random_;
    898 
    899   // The time of the test program start, in ms from the start of the
    900   // UNIX epoch.
    901   TimeInMillis start_timestamp_;
    902 
    903   // How long the test took to run, in milliseconds.
    904   TimeInMillis elapsed_time_;
    905 
    906 #if GTEST_HAS_DEATH_TEST
    907   // The decomposed components of the gtest_internal_run_death_test flag,
    908   // parsed when RUN_ALL_TESTS is called.
    909   internal::scoped_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;
    910   internal::scoped_ptr<internal::DeathTestFactory> death_test_factory_;
    911 #endif  // GTEST_HAS_DEATH_TEST
    912 
    913   // A per-thread stack of traces created by the SCOPED_TRACE() macro.
    914   internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_;
    915 
    916   // The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests()
    917   // starts.
    918   bool catch_exceptions_;
    919 
    920   GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl);
    921 };  // class UnitTestImpl
    922 
    923 // Convenience function for accessing the global UnitTest
    924 // implementation object.
    925 inline UnitTestImpl* GetUnitTestImpl() {
    926   return UnitTest::GetInstance()->impl();
    927 }
    928 
    929 #if GTEST_USES_SIMPLE_RE
    930 
    931 // Internal helper functions for implementing the simple regular
    932 // expression matcher.
    933 GTEST_API_ bool IsInSet(char ch, const char* str);
    934 GTEST_API_ bool IsAsciiDigit(char ch);
    935 GTEST_API_ bool IsAsciiPunct(char ch);
    936 GTEST_API_ bool IsRepeat(char ch);
    937 GTEST_API_ bool IsAsciiWhiteSpace(char ch);
    938 GTEST_API_ bool IsAsciiWordChar(char ch);
    939 GTEST_API_ bool IsValidEscape(char ch);
    940 GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch);
    941 GTEST_API_ bool ValidateRegex(const char* regex);
    942 GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str);
    943 GTEST_API_ bool MatchRepetitionAndRegexAtHead(
    944     bool escaped, char ch, char repeat, const char* regex, const char* str);
    945 GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str);
    946 
    947 #endif  // GTEST_USES_SIMPLE_RE
    948 
    949 // Parses the command line for Google Test flags, without initializing
    950 // other parts of Google Test.
    951 GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv);
    952 GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv);
    953 
    954 #if GTEST_HAS_DEATH_TEST
    955 
    956 // Returns the message describing the last system error, regardless of the
    957 // platform.
    958 GTEST_API_ std::string GetLastErrnoDescription();
    959 
    960 # if GTEST_OS_WINDOWS
    961 // Provides leak-safe Windows kernel handle ownership.
    962 class AutoHandle {
    963  public:
    964   AutoHandle() : handle_(INVALID_HANDLE_VALUE) {}
    965   explicit AutoHandle(HANDLE handle) : handle_(handle) {}
    966 
    967   ~AutoHandle() { Reset(); }
    968 
    969   HANDLE Get() const { return handle_; }
    970   void Reset() { Reset(INVALID_HANDLE_VALUE); }
    971   void Reset(HANDLE handle) {
    972     if (handle != handle_) {
    973       if (handle_ != INVALID_HANDLE_VALUE)
    974         ::CloseHandle(handle_);
    975       handle_ = handle;
    976     }
    977   }
    978 
    979  private:
    980   HANDLE handle_;
    981 
    982   GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle);
    983 };
    984 # endif  // GTEST_OS_WINDOWS
    985 
    986 // Attempts to parse a string into a positive integer pointed to by the
    987 // number parameter.  Returns true if that is possible.
    988 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use
    989 // it here.
    990 template <typename Integer>
    991 bool ParseNaturalNumber(const ::std::string& str, Integer* number) {
    992   // Fail fast if the given string does not begin with a digit;
    993   // this bypasses strtoXXX's "optional leading whitespace and plus
    994   // or minus sign" semantics, which are undesirable here.
    995   if (str.empty() || !IsDigit(str[0])) {
    996     return false;
    997   }
    998   errno = 0;
    999 
   1000   char* end;
   1001   // BiggestConvertible is the largest integer type that system-provided
   1002   // string-to-number conversion routines can return.
   1003 
   1004 # if GTEST_OS_WINDOWS && !defined(__GNUC__)
   1005 
   1006   // MSVC and C++ Builder define __int64 instead of the standard long long.
   1007   typedef unsigned __int64 BiggestConvertible;
   1008   const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10);
   1009 
   1010 # else
   1011 
   1012   typedef unsigned long long BiggestConvertible;  // NOLINT
   1013   const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10);
   1014 
   1015 # endif  // GTEST_OS_WINDOWS && !defined(__GNUC__)
   1016 
   1017   const bool parse_success = *end == '\0' && errno == 0;
   1018 
   1019   // TODO(vladl (at) google.com): Convert this to compile time assertion when it is
   1020   // available.
   1021   GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed));
   1022 
   1023   const Integer result = static_cast<Integer>(parsed);
   1024   if (parse_success && static_cast<BiggestConvertible>(result) == parsed) {
   1025     *number = result;
   1026     return true;
   1027   }
   1028   return false;
   1029 }
   1030 #endif  // GTEST_HAS_DEATH_TEST
   1031 
   1032 // TestResult contains some private methods that should be hidden from
   1033 // Google Test user but are required for testing. This class allow our tests
   1034 // to access them.
   1035 //
   1036 // This class is supplied only for the purpose of testing Google Test's own
   1037 // constructs. Do not use it in user tests, either directly or indirectly.
   1038 class TestResultAccessor {
   1039  public:
   1040   static void RecordProperty(TestResult* test_result,
   1041                              const TestProperty& property) {
   1042     test_result->RecordProperty(property);
   1043   }
   1044 
   1045   static void ClearTestPartResults(TestResult* test_result) {
   1046     test_result->ClearTestPartResults();
   1047   }
   1048 
   1049   static const std::vector<testing::TestPartResult>& test_part_results(
   1050       const TestResult& test_result) {
   1051     return test_result.test_part_results();
   1052   }
   1053 };
   1054 
   1055 #if GTEST_CAN_STREAM_RESULTS_
   1056 
   1057 // Streams test results to the given port on the given host machine.
   1058 class StreamingListener : public EmptyTestEventListener {
   1059  public:
   1060   // Abstract base class for writing strings to a socket.
   1061   class AbstractSocketWriter {
   1062    public:
   1063     virtual ~AbstractSocketWriter() {}
   1064 
   1065     // Sends a string to the socket.
   1066     virtual void Send(const string& message) = 0;
   1067 
   1068     // Closes the socket.
   1069     virtual void CloseConnection() {}
   1070 
   1071     // Sends a string and a newline to the socket.
   1072     void SendLn(const string& message) {
   1073       Send(message + "\n");
   1074     }
   1075   };
   1076 
   1077   // Concrete class for actually writing strings to a socket.
   1078   class SocketWriter : public AbstractSocketWriter {
   1079    public:
   1080     SocketWriter(const string& host, const string& port)
   1081         : sockfd_(-1), host_name_(host), port_num_(port) {
   1082       MakeConnection();
   1083     }
   1084 
   1085     virtual ~SocketWriter() {
   1086       if (sockfd_ != -1)
   1087         CloseConnection();
   1088     }
   1089 
   1090     // Sends a string to the socket.
   1091     virtual void Send(const string& message) {
   1092       GTEST_CHECK_(sockfd_ != -1)
   1093           << "Send() can be called only when there is a connection.";
   1094 
   1095       const int len = static_cast<int>(message.length());
   1096       if (write(sockfd_, message.c_str(), len) != len) {
   1097         GTEST_LOG_(WARNING)
   1098             << "stream_result_to: failed to stream to "
   1099             << host_name_ << ":" << port_num_;
   1100       }
   1101     }
   1102 
   1103    private:
   1104     // Creates a client socket and connects to the server.
   1105     void MakeConnection();
   1106 
   1107     // Closes the socket.
   1108     void CloseConnection() {
   1109       GTEST_CHECK_(sockfd_ != -1)
   1110           << "CloseConnection() can be called only when there is a connection.";
   1111 
   1112       close(sockfd_);
   1113       sockfd_ = -1;
   1114     }
   1115 
   1116     int sockfd_;  // socket file descriptor
   1117     const string host_name_;
   1118     const string port_num_;
   1119 
   1120     GTEST_DISALLOW_COPY_AND_ASSIGN_(SocketWriter);
   1121   };  // class SocketWriter
   1122 
   1123   // Escapes '=', '&', '%', and '\n' characters in str as "%xx".
   1124   static string UrlEncode(const char* str);
   1125 
   1126   StreamingListener(const string& host, const string& port)
   1127       : socket_writer_(new SocketWriter(host, port)) { Start(); }
   1128 
   1129   explicit StreamingListener(AbstractSocketWriter* socket_writer)
   1130       : socket_writer_(socket_writer) { Start(); }
   1131 
   1132   void OnTestProgramStart(const UnitTest& /* unit_test */) {
   1133     SendLn("event=TestProgramStart");
   1134   }
   1135 
   1136   void OnTestProgramEnd(const UnitTest& unit_test) {
   1137     // Note that Google Test current only report elapsed time for each
   1138     // test iteration, not for the entire test program.
   1139     SendLn("event=TestProgramEnd&passed=" + FormatBool(unit_test.Passed()));
   1140 
   1141     // Notify the streaming server to stop.
   1142     socket_writer_->CloseConnection();
   1143   }
   1144 
   1145   void OnTestIterationStart(const UnitTest& /* unit_test */, int iteration) {
   1146     SendLn("event=TestIterationStart&iteration=" +
   1147            StreamableToString(iteration));
   1148   }
   1149 
   1150   void OnTestIterationEnd(const UnitTest& unit_test, int /* iteration */) {
   1151     SendLn("event=TestIterationEnd&passed=" +
   1152            FormatBool(unit_test.Passed()) + "&elapsed_time=" +
   1153            StreamableToString(unit_test.elapsed_time()) + "ms");
   1154   }
   1155 
   1156   void OnTestCaseStart(const TestCase& test_case) {
   1157     SendLn(std::string("event=TestCaseStart&name=") + test_case.name());
   1158   }
   1159 
   1160   void OnTestCaseEnd(const TestCase& test_case) {
   1161     SendLn("event=TestCaseEnd&passed=" + FormatBool(test_case.Passed())
   1162            + "&elapsed_time=" + StreamableToString(test_case.elapsed_time())
   1163            + "ms");
   1164   }
   1165 
   1166   void OnTestStart(const TestInfo& test_info) {
   1167     SendLn(std::string("event=TestStart&name=") + test_info.name());
   1168   }
   1169 
   1170   void OnTestEnd(const TestInfo& test_info) {
   1171     SendLn("event=TestEnd&passed=" +
   1172            FormatBool((test_info.result())->Passed()) +
   1173            "&elapsed_time=" +
   1174            StreamableToString((test_info.result())->elapsed_time()) + "ms");
   1175   }
   1176 
   1177   void OnTestPartResult(const TestPartResult& test_part_result) {
   1178     const char* file_name = test_part_result.file_name();
   1179     if (file_name == NULL)
   1180       file_name = "";
   1181     SendLn("event=TestPartResult&file=" + UrlEncode(file_name) +
   1182            "&line=" + StreamableToString(test_part_result.line_number()) +
   1183            "&message=" + UrlEncode(test_part_result.message()));
   1184   }
   1185 
   1186  private:
   1187   // Sends the given message and a newline to the socket.
   1188   void SendLn(const string& message) { socket_writer_->SendLn(message); }
   1189 
   1190   // Called at the start of streaming to notify the receiver what
   1191   // protocol we are using.
   1192   void Start() { SendLn("gtest_streaming_protocol_version=1.0"); }
   1193 
   1194   string FormatBool(bool value) { return value ? "1" : "0"; }
   1195 
   1196   const scoped_ptr<AbstractSocketWriter> socket_writer_;
   1197 
   1198   GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener);
   1199 };  // class StreamingListener
   1200 
   1201 #endif  // GTEST_CAN_STREAM_RESULTS_
   1202 
   1203 }  // namespace internal
   1204 }  // namespace testing
   1205 
   1206 #endif  // GTEST_SRC_GTEST_INTERNAL_INL_H_
   1207