• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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@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.
GetRandomSeedFromFlag(Int32 random_seed_flag)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.
GetNextRandomSeed(int seed)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.
GTestFlagSaver()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.
~GTestFlagSaver()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>
CountIf(const Container & c,Predicate 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>
ForEach(const Container & c,Functor 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>
GetElementOr(const std::vector<E> & v,int i,E default_value)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>
ShuffleRange(internal::Random * random,int begin,int end,std::vector<E> * v)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>
Shuffle(internal::Random * random,std::vector<E> * v)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>
Delete(T * x)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.
TestPropertyKeyIs(const std::string & key)351   explicit TestPropertyKeyIs(const std::string& key) : key_(key) {}
352 
353   // Returns true iff the test name of test property matches on key_.
operator()354   bool operator()(const TestProperty& test_property) const {
355     return test_property.key() == key_;
356   }
357 
358  private:
359   std::string key_;
360 };
361 
362 // Class UnitTestOptions.
363 //
364 // This class contains functions for processing options the user
365 // specifies when running the tests.  It has only static members.
366 //
367 // In most cases, the user can specify an option using either an
368 // environment variable or a command line flag.  E.g. you can set the
369 // test filter using either GTEST_FILTER or --gtest_filter.  If both
370 // the variable and the flag are present, the latter overrides the
371 // former.
372 class GTEST_API_ UnitTestOptions {
373  public:
374   // Functions for processing the gtest_output flag.
375 
376   // Returns the output format, or "" for normal printed output.
377   static std::string GetOutputFormat();
378 
379   // Returns the absolute path of the requested output file, or the
380   // default (test_detail.xml in the original working directory) if
381   // none was explicitly specified.
382   static std::string GetAbsolutePathToOutputFile();
383 
384   // Functions for processing the gtest_filter flag.
385 
386   // Returns true iff the wildcard pattern matches the string.  The
387   // first ':' or '\0' character in pattern marks the end of it.
388   //
389   // This recursive algorithm isn't very efficient, but is clear and
390   // works well enough for matching test names, which are short.
391   static bool PatternMatchesString(const char *pattern, const char *str);
392 
393   // Returns true iff the user-specified filter matches the test case
394   // name and the test name.
395   static bool FilterMatchesTest(const std::string &test_case_name,
396                                 const std::string &test_name);
397 
398 #if GTEST_OS_WINDOWS
399   // Function for supporting the gtest_catch_exception flag.
400 
401   // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
402   // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
403   // This function is useful as an __except condition.
404   static int GTestShouldProcessSEH(DWORD exception_code);
405 #endif  // GTEST_OS_WINDOWS
406 
407   // Returns true if "name" matches the ':' separated list of glob-style
408   // filters in "filter".
409   static bool MatchesFilter(const std::string& name, const char* filter);
410 };
411 
412 // Returns the current application's name, removing directory path if that
413 // is present.  Used by UnitTestOptions::GetOutputFile.
414 GTEST_API_ FilePath GetCurrentExecutableName();
415 
416 // The role interface for getting the OS stack trace as a string.
417 class OsStackTraceGetterInterface {
418  public:
OsStackTraceGetterInterface()419   OsStackTraceGetterInterface() {}
~OsStackTraceGetterInterface()420   virtual ~OsStackTraceGetterInterface() {}
421 
422   // Returns the current OS stack trace as an std::string.  Parameters:
423   //
424   //   max_depth  - the maximum number of stack frames to be included
425   //                in the trace.
426   //   skip_count - the number of top frames to be skipped; doesn't count
427   //                against max_depth.
428   virtual string CurrentStackTrace(int max_depth, int skip_count) = 0;
429 
430   // UponLeavingGTest() should be called immediately before Google Test calls
431   // user code. It saves some information about the current stack that
432   // CurrentStackTrace() will use to find and hide Google Test stack frames.
433   virtual void UponLeavingGTest() = 0;
434 
435  private:
436   GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface);
437 };
438 
439 // A working implementation of the OsStackTraceGetterInterface interface.
440 class OsStackTraceGetter : public OsStackTraceGetterInterface {
441  public:
OsStackTraceGetter()442   OsStackTraceGetter() : caller_frame_(NULL) {}
443 
444   virtual string CurrentStackTrace(int max_depth, int skip_count)
445       GTEST_LOCK_EXCLUDED_(mutex_);
446 
447   virtual void UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_);
448 
449   // This string is inserted in place of stack frames that are part of
450   // Google Test's implementation.
451   static const char* const kElidedFramesMarker;
452 
453  private:
454   Mutex mutex_;  // protects all internal state
455 
456   // We save the stack frame below the frame that calls user code.
457   // We do this because the address of the frame immediately below
458   // the user code changes between the call to UponLeavingGTest()
459   // and any calls to CurrentStackTrace() from within the user code.
460   void* caller_frame_;
461 
462   GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter);
463 };
464 
465 // Information about a Google Test trace point.
466 struct TraceInfo {
467   const char* file;
468   int line;
469   std::string message;
470 };
471 
472 // This is the default global test part result reporter used in UnitTestImpl.
473 // This class should only be used by UnitTestImpl.
474 class DefaultGlobalTestPartResultReporter
475   : public TestPartResultReporterInterface {
476  public:
477   explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test);
478   // Implements the TestPartResultReporterInterface. Reports the test part
479   // result in the current test.
480   virtual void ReportTestPartResult(const TestPartResult& result);
481 
482  private:
483   UnitTestImpl* const unit_test_;
484 
485   GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter);
486 };
487 
488 // This is the default per thread test part result reporter used in
489 // UnitTestImpl. This class should only be used by UnitTestImpl.
490 class DefaultPerThreadTestPartResultReporter
491     : public TestPartResultReporterInterface {
492  public:
493   explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test);
494   // Implements the TestPartResultReporterInterface. The implementation just
495   // delegates to the current global test part result reporter of *unit_test_.
496   virtual void ReportTestPartResult(const TestPartResult& result);
497 
498  private:
499   UnitTestImpl* const unit_test_;
500 
501   GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter);
502 };
503 
504 // The private implementation of the UnitTest class.  We don't protect
505 // the methods under a mutex, as this class is not accessible by a
506 // user and the UnitTest class that delegates work to this class does
507 // proper locking.
508 class GTEST_API_ UnitTestImpl {
509  public:
510   explicit UnitTestImpl(UnitTest* parent);
511   virtual ~UnitTestImpl();
512 
513   // There are two different ways to register your own TestPartResultReporter.
514   // You can register your own repoter to listen either only for test results
515   // from the current thread or for results from all threads.
516   // By default, each per-thread test result repoter just passes a new
517   // TestPartResult to the global test result reporter, which registers the
518   // test part result for the currently running test.
519 
520   // Returns the global test part result reporter.
521   TestPartResultReporterInterface* GetGlobalTestPartResultReporter();
522 
523   // Sets the global test part result reporter.
524   void SetGlobalTestPartResultReporter(
525       TestPartResultReporterInterface* reporter);
526 
527   // Returns the test part result reporter for the current thread.
528   TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread();
529 
530   // Sets the test part result reporter for the current thread.
531   void SetTestPartResultReporterForCurrentThread(
532       TestPartResultReporterInterface* reporter);
533 
534   // Gets the number of successful test cases.
535   int successful_test_case_count() const;
536 
537   // Gets the number of failed test cases.
538   int failed_test_case_count() const;
539 
540   // Gets the number of all test cases.
541   int total_test_case_count() const;
542 
543   // Gets the number of all test cases that contain at least one test
544   // that should run.
545   int test_case_to_run_count() const;
546 
547   // Gets the number of successful tests.
548   int successful_test_count() const;
549 
550   // Gets the number of failed tests.
551   int failed_test_count() const;
552 
553   // Gets the number of disabled tests.
554   int disabled_test_count() const;
555 
556   // Gets the number of all tests.
557   int total_test_count() const;
558 
559   // Gets the number of tests that should run.
560   int test_to_run_count() const;
561 
562   // Gets the time of the test program start, in ms from the start of the
563   // UNIX epoch.
start_timestamp()564   TimeInMillis start_timestamp() const { return start_timestamp_; }
565 
566   // Gets the elapsed time, in milliseconds.
elapsed_time()567   TimeInMillis elapsed_time() const { return elapsed_time_; }
568 
569   // Returns true iff the unit test passed (i.e. all test cases passed).
Passed()570   bool Passed() const { return !Failed(); }
571 
572   // Returns true iff the unit test failed (i.e. some test case failed
573   // or something outside of all tests failed).
Failed()574   bool Failed() const {
575     return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed();
576   }
577 
578   // Gets the i-th test case among all the test cases. i can range from 0 to
579   // total_test_case_count() - 1. If i is not in that range, returns NULL.
GetTestCase(int i)580   const TestCase* GetTestCase(int i) const {
581     const int index = GetElementOr(test_case_indices_, i, -1);
582     return index < 0 ? NULL : test_cases_[i];
583   }
584 
585   // Gets the i-th test case among all the test cases. i can range from 0 to
586   // total_test_case_count() - 1. If i is not in that range, returns NULL.
GetMutableTestCase(int i)587   TestCase* GetMutableTestCase(int i) {
588     const int index = GetElementOr(test_case_indices_, i, -1);
589     return index < 0 ? NULL : test_cases_[index];
590   }
591 
592   // Provides access to the event listener list.
listeners()593   TestEventListeners* listeners() { return &listeners_; }
594 
595   // Returns the TestResult for the test that's currently running, or
596   // the TestResult for the ad hoc test if no test is running.
597   TestResult* current_test_result();
598 
599   // Returns the TestResult for the ad hoc test.
ad_hoc_test_result()600   const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; }
601 
602   // Sets the OS stack trace getter.
603   //
604   // Does nothing if the input and the current OS stack trace getter
605   // are the same; otherwise, deletes the old getter and makes the
606   // input the current getter.
607   void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter);
608 
609   // Returns the current OS stack trace getter if it is not NULL;
610   // otherwise, creates an OsStackTraceGetter, makes it the current
611   // getter, and returns it.
612   OsStackTraceGetterInterface* os_stack_trace_getter();
613 
614   // Returns the current OS stack trace as an std::string.
615   //
616   // The maximum number of stack frames to be included is specified by
617   // the gtest_stack_trace_depth flag.  The skip_count parameter
618   // specifies the number of top frames to be skipped, which doesn't
619   // count against the number of frames to be included.
620   //
621   // For example, if Foo() calls Bar(), which in turn calls
622   // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
623   // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
624   std::string CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_;
625 
626   // Finds and returns a TestCase with the given name.  If one doesn't
627   // exist, creates one and returns it.
628   //
629   // Arguments:
630   //
631   //   test_case_name: name of the test case
632   //   type_param:     the name of the test's type parameter, or NULL if
633   //                   this is not a typed or a type-parameterized test.
634   //   set_up_tc:      pointer to the function that sets up the test case
635   //   tear_down_tc:   pointer to the function that tears down the test case
636   TestCase* GetTestCase(const char* test_case_name,
637                         const char* type_param,
638                         Test::SetUpTestCaseFunc set_up_tc,
639                         Test::TearDownTestCaseFunc tear_down_tc);
640 
641   // Adds a TestInfo to the unit test.
642   //
643   // Arguments:
644   //
645   //   set_up_tc:    pointer to the function that sets up the test case
646   //   tear_down_tc: pointer to the function that tears down the test case
647   //   test_info:    the TestInfo object
AddTestInfo(Test::SetUpTestCaseFunc set_up_tc,Test::TearDownTestCaseFunc tear_down_tc,TestInfo * test_info)648   void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc,
649                    Test::TearDownTestCaseFunc tear_down_tc,
650                    TestInfo* test_info) {
651     // In order to support thread-safe death tests, we need to
652     // remember the original working directory when the test program
653     // was first invoked.  We cannot do this in RUN_ALL_TESTS(), as
654     // the user may have changed the current directory before calling
655     // RUN_ALL_TESTS().  Therefore we capture the current directory in
656     // AddTestInfo(), which is called to register a TEST or TEST_F
657     // before main() is reached.
658     if (original_working_dir_.IsEmpty()) {
659       original_working_dir_.Set(FilePath::GetCurrentDir());
660       GTEST_CHECK_(!original_working_dir_.IsEmpty())
661           << "Failed to get the current working directory.";
662     }
663 
664     GetTestCase(test_info->test_case_name(),
665                 test_info->type_param(),
666                 set_up_tc,
667                 tear_down_tc)->AddTestInfo(test_info);
668   }
669 
670 #if GTEST_HAS_PARAM_TEST
671   // Returns ParameterizedTestCaseRegistry object used to keep track of
672   // value-parameterized tests and instantiate and register them.
parameterized_test_registry()673   internal::ParameterizedTestCaseRegistry& parameterized_test_registry() {
674     return parameterized_test_registry_;
675   }
676 #endif  // GTEST_HAS_PARAM_TEST
677 
678   // Sets the TestCase object for the test that's currently running.
set_current_test_case(TestCase * a_current_test_case)679   void set_current_test_case(TestCase* a_current_test_case) {
680     current_test_case_ = a_current_test_case;
681   }
682 
683   // Sets the TestInfo object for the test that's currently running.  If
684   // current_test_info is NULL, the assertion results will be stored in
685   // ad_hoc_test_result_.
set_current_test_info(TestInfo * a_current_test_info)686   void set_current_test_info(TestInfo* a_current_test_info) {
687     current_test_info_ = a_current_test_info;
688   }
689 
690   // Registers all parameterized tests defined using TEST_P and
691   // INSTANTIATE_TEST_CASE_P, creating regular tests for each test/parameter
692   // combination. This method can be called more then once; it has guards
693   // protecting from registering the tests more then once.  If
694   // value-parameterized tests are disabled, RegisterParameterizedTests is
695   // present but does nothing.
696   void RegisterParameterizedTests();
697 
698   // Runs all tests in this UnitTest object, prints the result, and
699   // returns true if all tests are successful.  If any exception is
700   // thrown during a test, this test is considered to be failed, but
701   // the rest of the tests will still be run.
702   bool RunAllTests();
703 
704   // Clears the results of all tests, except the ad hoc tests.
ClearNonAdHocTestResult()705   void ClearNonAdHocTestResult() {
706     ForEach(test_cases_, TestCase::ClearTestCaseResult);
707   }
708 
709   // Clears the results of ad-hoc test assertions.
ClearAdHocTestResult()710   void ClearAdHocTestResult() {
711     ad_hoc_test_result_.Clear();
712   }
713 
714   // Adds a TestProperty to the current TestResult object when invoked in a
715   // context of a test or a test case, or to the global property set. If the
716   // result already contains a property with the same key, the value will be
717   // updated.
718   void RecordProperty(const TestProperty& test_property);
719 
720   enum ReactionToSharding {
721     HONOR_SHARDING_PROTOCOL,
722     IGNORE_SHARDING_PROTOCOL
723   };
724 
725   // Matches the full name of each test against the user-specified
726   // filter to decide whether the test should run, then records the
727   // result in each TestCase and TestInfo object.
728   // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests
729   // based on sharding variables in the environment.
730   // Returns the number of tests that should run.
731   int FilterTests(ReactionToSharding shard_tests);
732 
733   // Prints the names of the tests matching the user-specified filter flag.
734   void ListTestsMatchingFilter();
735 
current_test_case()736   const TestCase* current_test_case() const { return current_test_case_; }
current_test_info()737   TestInfo* current_test_info() { return current_test_info_; }
current_test_info()738   const TestInfo* current_test_info() const { return current_test_info_; }
739 
740   // Returns the vector of environments that need to be set-up/torn-down
741   // before/after the tests are run.
environments()742   std::vector<Environment*>& environments() { return environments_; }
743 
744   // Getters for the per-thread Google Test trace stack.
gtest_trace_stack()745   std::vector<TraceInfo>& gtest_trace_stack() {
746     return *(gtest_trace_stack_.pointer());
747   }
gtest_trace_stack()748   const std::vector<TraceInfo>& gtest_trace_stack() const {
749     return gtest_trace_stack_.get();
750   }
751 
752 #if GTEST_HAS_DEATH_TEST
InitDeathTestSubprocessControlInfo()753   void InitDeathTestSubprocessControlInfo() {
754     internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());
755   }
756   // Returns a pointer to the parsed --gtest_internal_run_death_test
757   // flag, or NULL if that flag was not specified.
758   // This information is useful only in a death test child process.
759   // Must not be called before a call to InitGoogleTest.
internal_run_death_test_flag()760   const InternalRunDeathTestFlag* internal_run_death_test_flag() const {
761     return internal_run_death_test_flag_.get();
762   }
763 
764   // Returns a pointer to the current death test factory.
death_test_factory()765   internal::DeathTestFactory* death_test_factory() {
766     return death_test_factory_.get();
767   }
768 
769   void SuppressTestEventsIfInSubprocess();
770 
771   friend class ReplaceDeathTestFactory;
772 #endif  // GTEST_HAS_DEATH_TEST
773 
774   // Initializes the event listener performing XML output as specified by
775   // UnitTestOptions. Must not be called before InitGoogleTest.
776   void ConfigureXmlOutput();
777 
778 #if GTEST_CAN_STREAM_RESULTS_
779   // Initializes the event listener for streaming test results to a socket.
780   // Must not be called before InitGoogleTest.
781   void ConfigureStreamingOutput();
782 #endif
783 
784   // Performs initialization dependent upon flag values obtained in
785   // ParseGoogleTestFlagsOnly.  Is called from InitGoogleTest after the call to
786   // ParseGoogleTestFlagsOnly.  In case a user neglects to call InitGoogleTest
787   // this function is also called from RunAllTests.  Since this function can be
788   // called more than once, it has to be idempotent.
789   void PostFlagParsingInit();
790 
791   // Gets the random seed used at the start of the current test iteration.
random_seed()792   int random_seed() const { return random_seed_; }
793 
794   // Gets the random number generator.
random()795   internal::Random* random() { return &random_; }
796 
797   // Shuffles all test cases, and the tests within each test case,
798   // making sure that death tests are still run first.
799   void ShuffleTests();
800 
801   // Restores the test cases and tests to their order before the first shuffle.
802   void UnshuffleTests();
803 
804   // Returns the value of GTEST_FLAG(catch_exceptions) at the moment
805   // UnitTest::Run() starts.
catch_exceptions()806   bool catch_exceptions() const { return catch_exceptions_; }
807 
808  private:
809   friend class ::testing::UnitTest;
810 
811   // Used by UnitTest::Run() to capture the state of
812   // GTEST_FLAG(catch_exceptions) at the moment it starts.
set_catch_exceptions(bool value)813   void set_catch_exceptions(bool value) { catch_exceptions_ = value; }
814 
815   // The UnitTest object that owns this implementation object.
816   UnitTest* const parent_;
817 
818   // The working directory when the first TEST() or TEST_F() was
819   // executed.
820   internal::FilePath original_working_dir_;
821 
822   // The default test part result reporters.
823   DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_;
824   DefaultPerThreadTestPartResultReporter
825       default_per_thread_test_part_result_reporter_;
826 
827   // Points to (but doesn't own) the global test part result reporter.
828   TestPartResultReporterInterface* global_test_part_result_repoter_;
829 
830   // Protects read and write access to global_test_part_result_reporter_.
831   internal::Mutex global_test_part_result_reporter_mutex_;
832 
833   // Points to (but doesn't own) the per-thread test part result reporter.
834   internal::ThreadLocal<TestPartResultReporterInterface*>
835       per_thread_test_part_result_reporter_;
836 
837   // The vector of environments that need to be set-up/torn-down
838   // before/after the tests are run.
839   std::vector<Environment*> environments_;
840 
841   // The vector of TestCases in their original order.  It owns the
842   // elements in the vector.
843   std::vector<TestCase*> test_cases_;
844 
845   // Provides a level of indirection for the test case list to allow
846   // easy shuffling and restoring the test case order.  The i-th
847   // element of this vector is the index of the i-th test case in the
848   // shuffled order.
849   std::vector<int> test_case_indices_;
850 
851 #if GTEST_HAS_PARAM_TEST
852   // ParameterizedTestRegistry object used to register value-parameterized
853   // tests.
854   internal::ParameterizedTestCaseRegistry parameterized_test_registry_;
855 
856   // Indicates whether RegisterParameterizedTests() has been called already.
857   bool parameterized_tests_registered_;
858 #endif  // GTEST_HAS_PARAM_TEST
859 
860   // Index of the last death test case registered.  Initially -1.
861   int last_death_test_case_;
862 
863   // This points to the TestCase for the currently running test.  It
864   // changes as Google Test goes through one test case after another.
865   // When no test is running, this is set to NULL and Google Test
866   // stores assertion results in ad_hoc_test_result_.  Initially NULL.
867   TestCase* current_test_case_;
868 
869   // This points to the TestInfo for the currently running test.  It
870   // changes as Google Test goes through one test after another.  When
871   // no test is running, this is set to NULL and Google Test stores
872   // assertion results in ad_hoc_test_result_.  Initially NULL.
873   TestInfo* current_test_info_;
874 
875   // Normally, a user only writes assertions inside a TEST or TEST_F,
876   // or inside a function called by a TEST or TEST_F.  Since Google
877   // Test keeps track of which test is current running, it can
878   // associate such an assertion with the test it belongs to.
879   //
880   // If an assertion is encountered when no TEST or TEST_F is running,
881   // Google Test attributes the assertion result to an imaginary "ad hoc"
882   // test, and records the result in ad_hoc_test_result_.
883   TestResult ad_hoc_test_result_;
884 
885   // The list of event listeners that can be used to track events inside
886   // Google Test.
887   TestEventListeners listeners_;
888 
889   // The OS stack trace getter.  Will be deleted when the UnitTest
890   // object is destructed.  By default, an OsStackTraceGetter is used,
891   // but the user can set this field to use a custom getter if that is
892   // desired.
893   OsStackTraceGetterInterface* os_stack_trace_getter_;
894 
895   // True iff PostFlagParsingInit() has been called.
896   bool post_flag_parse_init_performed_;
897 
898   // The random number seed used at the beginning of the test run.
899   int random_seed_;
900 
901   // Our random number generator.
902   internal::Random random_;
903 
904   // The time of the test program start, in ms from the start of the
905   // UNIX epoch.
906   TimeInMillis start_timestamp_;
907 
908   // How long the test took to run, in milliseconds.
909   TimeInMillis elapsed_time_;
910 
911 #if GTEST_HAS_DEATH_TEST
912   // The decomposed components of the gtest_internal_run_death_test flag,
913   // parsed when RUN_ALL_TESTS is called.
914   internal::scoped_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;
915   internal::scoped_ptr<internal::DeathTestFactory> death_test_factory_;
916 #endif  // GTEST_HAS_DEATH_TEST
917 
918   // A per-thread stack of traces created by the SCOPED_TRACE() macro.
919   internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_;
920 
921   // The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests()
922   // starts.
923   bool catch_exceptions_;
924 
925   GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl);
926 };  // class UnitTestImpl
927 
928 // Convenience function for accessing the global UnitTest
929 // implementation object.
GetUnitTestImpl()930 inline UnitTestImpl* GetUnitTestImpl() {
931   return UnitTest::GetInstance()->impl();
932 }
933 
934 #if GTEST_USES_SIMPLE_RE
935 
936 // Internal helper functions for implementing the simple regular
937 // expression matcher.
938 GTEST_API_ bool IsInSet(char ch, const char* str);
939 GTEST_API_ bool IsAsciiDigit(char ch);
940 GTEST_API_ bool IsAsciiPunct(char ch);
941 GTEST_API_ bool IsRepeat(char ch);
942 GTEST_API_ bool IsAsciiWhiteSpace(char ch);
943 GTEST_API_ bool IsAsciiWordChar(char ch);
944 GTEST_API_ bool IsValidEscape(char ch);
945 GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch);
946 GTEST_API_ bool ValidateRegex(const char* regex);
947 GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str);
948 GTEST_API_ bool MatchRepetitionAndRegexAtHead(
949     bool escaped, char ch, char repeat, const char* regex, const char* str);
950 GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str);
951 
952 #endif  // GTEST_USES_SIMPLE_RE
953 
954 // Parses the command line for Google Test flags, without initializing
955 // other parts of Google Test.
956 GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv);
957 GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv);
958 
959 #if GTEST_HAS_DEATH_TEST
960 
961 // Returns the message describing the last system error, regardless of the
962 // platform.
963 GTEST_API_ std::string GetLastErrnoDescription();
964 
965 # if GTEST_OS_WINDOWS
966 // Provides leak-safe Windows kernel handle ownership.
967 class AutoHandle {
968  public:
AutoHandle()969   AutoHandle() : handle_(INVALID_HANDLE_VALUE) {}
AutoHandle(HANDLE handle)970   explicit AutoHandle(HANDLE handle) : handle_(handle) {}
971 
~AutoHandle()972   ~AutoHandle() { Reset(); }
973 
Get()974   HANDLE Get() const { return handle_; }
Reset()975   void Reset() { Reset(INVALID_HANDLE_VALUE); }
Reset(HANDLE handle)976   void Reset(HANDLE handle) {
977     if (handle != handle_) {
978       if (handle_ != INVALID_HANDLE_VALUE)
979         ::CloseHandle(handle_);
980       handle_ = handle;
981     }
982   }
983 
984  private:
985   HANDLE handle_;
986 
987   GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle);
988 };
989 # endif  // GTEST_OS_WINDOWS
990 
991 // Attempts to parse a string into a positive integer pointed to by the
992 // number parameter.  Returns true if that is possible.
993 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use
994 // it here.
995 template <typename Integer>
ParseNaturalNumber(const::std::string & str,Integer * number)996 bool ParseNaturalNumber(const ::std::string& str, Integer* number) {
997   // Fail fast if the given string does not begin with a digit;
998   // this bypasses strtoXXX's "optional leading whitespace and plus
999   // or minus sign" semantics, which are undesirable here.
1000   if (str.empty() || !IsDigit(str[0])) {
1001     return false;
1002   }
1003   errno = 0;
1004 
1005   char* end;
1006   // BiggestConvertible is the largest integer type that system-provided
1007   // string-to-number conversion routines can return.
1008 
1009 # if GTEST_OS_WINDOWS && !defined(__GNUC__)
1010 
1011   // MSVC and C++ Builder define __int64 instead of the standard long long.
1012   typedef unsigned __int64 BiggestConvertible;
1013   const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10);
1014 
1015 # else
1016 
1017   typedef unsigned long long BiggestConvertible;  // NOLINT
1018   const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10);
1019 
1020 # endif  // GTEST_OS_WINDOWS && !defined(__GNUC__)
1021 
1022   const bool parse_success = *end == '\0' && errno == 0;
1023 
1024   // TODO(vladl@google.com): Convert this to compile time assertion when it is
1025   // available.
1026   GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed));
1027 
1028   const Integer result = static_cast<Integer>(parsed);
1029   if (parse_success && static_cast<BiggestConvertible>(result) == parsed) {
1030     *number = result;
1031     return true;
1032   }
1033   return false;
1034 }
1035 #endif  // GTEST_HAS_DEATH_TEST
1036 
1037 // TestResult contains some private methods that should be hidden from
1038 // Google Test user but are required for testing. This class allow our tests
1039 // to access them.
1040 //
1041 // This class is supplied only for the purpose of testing Google Test's own
1042 // constructs. Do not use it in user tests, either directly or indirectly.
1043 class TestResultAccessor {
1044  public:
RecordProperty(TestResult * test_result,const std::string & xml_element,const TestProperty & property)1045   static void RecordProperty(TestResult* test_result,
1046                              const std::string& xml_element,
1047                              const TestProperty& property) {
1048     test_result->RecordProperty(xml_element, property);
1049   }
1050 
ClearTestPartResults(TestResult * test_result)1051   static void ClearTestPartResults(TestResult* test_result) {
1052     test_result->ClearTestPartResults();
1053   }
1054 
test_part_results(const TestResult & test_result)1055   static const std::vector<testing::TestPartResult>& test_part_results(
1056       const TestResult& test_result) {
1057     return test_result.test_part_results();
1058   }
1059 };
1060 
1061 #if GTEST_CAN_STREAM_RESULTS_
1062 
1063 // Streams test results to the given port on the given host machine.
1064 class StreamingListener : public EmptyTestEventListener {
1065  public:
1066   // Abstract base class for writing strings to a socket.
1067   class AbstractSocketWriter {
1068    public:
~AbstractSocketWriter()1069     virtual ~AbstractSocketWriter() {}
1070 
1071     // Sends a string to the socket.
1072     virtual void Send(const string& message) = 0;
1073 
1074     // Closes the socket.
CloseConnection()1075     virtual void CloseConnection() {}
1076 
1077     // Sends a string and a newline to the socket.
SendLn(const string & message)1078     void SendLn(const string& message) {
1079       Send(message + "\n");
1080     }
1081   };
1082 
1083   // Concrete class for actually writing strings to a socket.
1084   class SocketWriter : public AbstractSocketWriter {
1085    public:
SocketWriter(const string & host,const string & port)1086     SocketWriter(const string& host, const string& port)
1087         : sockfd_(-1), host_name_(host), port_num_(port) {
1088       MakeConnection();
1089     }
1090 
~SocketWriter()1091     virtual ~SocketWriter() {
1092       if (sockfd_ != -1)
1093         CloseConnection();
1094     }
1095 
1096     // Sends a string to the socket.
Send(const string & message)1097     virtual void Send(const string& message) {
1098       GTEST_CHECK_(sockfd_ != -1)
1099           << "Send() can be called only when there is a connection.";
1100 
1101       const int len = static_cast<int>(message.length());
1102       if (write(sockfd_, message.c_str(), len) != len) {
1103         GTEST_LOG_(WARNING)
1104             << "stream_result_to: failed to stream to "
1105             << host_name_ << ":" << port_num_;
1106       }
1107     }
1108 
1109    private:
1110     // Creates a client socket and connects to the server.
1111     void MakeConnection();
1112 
1113     // Closes the socket.
CloseConnection()1114     void CloseConnection() {
1115       GTEST_CHECK_(sockfd_ != -1)
1116           << "CloseConnection() can be called only when there is a connection.";
1117 
1118       close(sockfd_);
1119       sockfd_ = -1;
1120     }
1121 
1122     int sockfd_;  // socket file descriptor
1123     const string host_name_;
1124     const string port_num_;
1125 
1126     GTEST_DISALLOW_COPY_AND_ASSIGN_(SocketWriter);
1127   };  // class SocketWriter
1128 
1129   // Escapes '=', '&', '%', and '\n' characters in str as "%xx".
1130   static string UrlEncode(const char* str);
1131 
StreamingListener(const string & host,const string & port)1132   StreamingListener(const string& host, const string& port)
1133       : socket_writer_(new SocketWriter(host, port)) { Start(); }
1134 
StreamingListener(AbstractSocketWriter * socket_writer)1135   explicit StreamingListener(AbstractSocketWriter* socket_writer)
1136       : socket_writer_(socket_writer) { Start(); }
1137 
OnTestProgramStart(const UnitTest &)1138   void OnTestProgramStart(const UnitTest& /* unit_test */) {
1139     SendLn("event=TestProgramStart");
1140   }
1141 
OnTestProgramEnd(const UnitTest & unit_test)1142   void OnTestProgramEnd(const UnitTest& unit_test) {
1143     // Note that Google Test current only report elapsed time for each
1144     // test iteration, not for the entire test program.
1145     SendLn("event=TestProgramEnd&passed=" + FormatBool(unit_test.Passed()));
1146 
1147     // Notify the streaming server to stop.
1148     socket_writer_->CloseConnection();
1149   }
1150 
OnTestIterationStart(const UnitTest &,int iteration)1151   void OnTestIterationStart(const UnitTest& /* unit_test */, int iteration) {
1152     SendLn("event=TestIterationStart&iteration=" +
1153            StreamableToString(iteration));
1154   }
1155 
OnTestIterationEnd(const UnitTest & unit_test,int)1156   void OnTestIterationEnd(const UnitTest& unit_test, int /* iteration */) {
1157     SendLn("event=TestIterationEnd&passed=" +
1158            FormatBool(unit_test.Passed()) + "&elapsed_time=" +
1159            StreamableToString(unit_test.elapsed_time()) + "ms");
1160   }
1161 
OnTestCaseStart(const TestCase & test_case)1162   void OnTestCaseStart(const TestCase& test_case) {
1163     SendLn(std::string("event=TestCaseStart&name=") + test_case.name());
1164   }
1165 
OnTestCaseEnd(const TestCase & test_case)1166   void OnTestCaseEnd(const TestCase& test_case) {
1167     SendLn("event=TestCaseEnd&passed=" + FormatBool(test_case.Passed())
1168            + "&elapsed_time=" + StreamableToString(test_case.elapsed_time())
1169            + "ms");
1170   }
1171 
OnTestStart(const TestInfo & test_info)1172   void OnTestStart(const TestInfo& test_info) {
1173     SendLn(std::string("event=TestStart&name=") + test_info.name());
1174   }
1175 
OnTestEnd(const TestInfo & test_info)1176   void OnTestEnd(const TestInfo& test_info) {
1177     SendLn("event=TestEnd&passed=" +
1178            FormatBool((test_info.result())->Passed()) +
1179            "&elapsed_time=" +
1180            StreamableToString((test_info.result())->elapsed_time()) + "ms");
1181   }
1182 
OnTestPartResult(const TestPartResult & test_part_result)1183   void OnTestPartResult(const TestPartResult& test_part_result) {
1184     const char* file_name = test_part_result.file_name();
1185     if (file_name == NULL)
1186       file_name = "";
1187     SendLn("event=TestPartResult&file=" + UrlEncode(file_name) +
1188            "&line=" + StreamableToString(test_part_result.line_number()) +
1189            "&message=" + UrlEncode(test_part_result.message()));
1190   }
1191 
1192  private:
1193   // Sends the given message and a newline to the socket.
SendLn(const string & message)1194   void SendLn(const string& message) { socket_writer_->SendLn(message); }
1195 
1196   // Called at the start of streaming to notify the receiver what
1197   // protocol we are using.
Start()1198   void Start() { SendLn("gtest_streaming_protocol_version=1.0"); }
1199 
FormatBool(bool value)1200   string FormatBool(bool value) { return value ? "1" : "0"; }
1201 
1202   const scoped_ptr<AbstractSocketWriter> socket_writer_;
1203 
1204   GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener);
1205 };  // class StreamingListener
1206 
1207 #endif  // GTEST_CAN_STREAM_RESULTS_
1208 
1209 }  // namespace internal
1210 }  // namespace testing
1211 
1212 #endif  // GTEST_SRC_GTEST_INTERNAL_INL_H_
1213