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