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