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