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