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