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