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