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.
48 #include "gtest/internal/gtest-port.h"
50 #if GTEST_CAN_STREAM_RESULTS_
51 # include <arpa/inet.h> // NOLINT
52 # include <netdb.h> // NOLINT
56 # include <windows.h> // NOLINT
57 #endif // GTEST_OS_WINDOWS
59 #include "gtest/gtest.h"
60 #include "gtest/gtest-spi.h"
62 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
63 /* class A needs to have dll-interface to be used by clients of class B */)
67 // Declares the flags.
69 // We don't want the users to modify this flag in the code, but want
70 // Google Test's own unit tests to be able to access it. Therefore we
71 // declare it here as opposed to in gtest.h.
72 GTEST_DECLARE_bool_(death_test_use_fork);
76 // The value of GetTestTypeId() as seen from within the Google Test
77 // library. This is solely for testing GetTestTypeId().
78 GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest;
80 // Names of the flags (needed for parsing Google Test flags).
81 const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests";
82 const char kBreakOnFailureFlag[] = "break_on_failure";
83 const char kCatchExceptionsFlag[] = "catch_exceptions";
84 const char kColorFlag[] = "color";
85 const char kFilterFlag[] = "filter";
86 const char kListTestsFlag[] = "list_tests";
87 const char kOutputFlag[] = "output";
88 const char kPrintTimeFlag[] = "print_time";
89 const char kPrintUTF8Flag[] = "print_utf8";
90 const char kRandomSeedFlag[] = "random_seed";
91 const char kRepeatFlag[] = "repeat";
92 const char kShuffleFlag[] = "shuffle";
93 const char kStackTraceDepthFlag[] = "stack_trace_depth";
94 const char kStreamResultToFlag[] = "stream_result_to";
95 const char kThrowOnFailureFlag[] = "throw_on_failure";
96 const char kFlagfileFlag[] = "flagfile";
98 // A valid random seed must be in [1, kMaxRandomSeed].
99 const int kMaxRandomSeed = 99999;
101 // g_help_flag is true iff the --help flag or an equivalent form is
102 // specified on the command line.
103 GTEST_API_ extern bool g_help_flag;
105 // Returns the current time in milliseconds.
106 GTEST_API_ TimeInMillis GetTimeInMillis();
108 // Returns true iff Google Test should use colors in the output.
109 GTEST_API_ bool ShouldUseColor(bool stdout_is_tty);
111 // Formats the given time in milliseconds as seconds.
112 GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms);
114 // Converts the given time in milliseconds to a date string in the ISO 8601
115 // format, without the timezone information. N.B.: due to the use the
116 // non-reentrant localtime() function, this function is not thread safe. Do
117 // not use it in any code that can be called from multiple threads.
118 GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms);
120 // Parses a string for an Int32 flag, in the form of "--flag=value".
122 // On success, stores the value of the flag in *value, and returns
123 // true. On failure, returns false without changing *value.
124 GTEST_API_ bool ParseInt32Flag(
125 const char* str, const char* flag, Int32* value);
127 // Returns a random seed in range [1, kMaxRandomSeed] based on the
128 // given --gtest_random_seed flag value.
129 inline int GetRandomSeedFromFlag(Int32 random_seed_flag) {
130 const unsigned int raw_seed = (random_seed_flag == 0) ?
131 static_cast<unsigned int>(GetTimeInMillis()) :
132 static_cast<unsigned int>(random_seed_flag);
134 // Normalizes the actual seed to range [1, kMaxRandomSeed] such that
135 // it's easy to type.
136 const int normalized_seed =
137 static_cast<int>((raw_seed - 1U) %
138 static_cast<unsigned int>(kMaxRandomSeed)) + 1;
139 return normalized_seed;
142 // Returns the first valid random seed after 'seed'. The behavior is
143 // undefined if 'seed' is invalid. The seed after kMaxRandomSeed is
144 // considered to be 1.
145 inline int GetNextRandomSeed(int seed) {
146 GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed)
147 << "Invalid random seed " << seed << " - must be in [1, "
148 << kMaxRandomSeed << "].";
149 const int next_seed = seed + 1;
150 return (next_seed > kMaxRandomSeed) ? 1 : next_seed;
153 // This class saves the values of all Google Test flags in its c'tor, and
154 // restores them in its d'tor.
155 class GTestFlagSaver {
159 also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests);
160 break_on_failure_ = GTEST_FLAG(break_on_failure);
161 catch_exceptions_ = GTEST_FLAG(catch_exceptions);
162 color_ = GTEST_FLAG(color);
163 death_test_style_ = GTEST_FLAG(death_test_style);
164 death_test_use_fork_ = GTEST_FLAG(death_test_use_fork);
165 filter_ = GTEST_FLAG(filter);
166 internal_run_death_test_ = GTEST_FLAG(internal_run_death_test);
167 list_tests_ = GTEST_FLAG(list_tests);
168 output_ = GTEST_FLAG(output);
169 print_time_ = GTEST_FLAG(print_time);
170 print_utf8_ = GTEST_FLAG(print_utf8);
171 random_seed_ = GTEST_FLAG(random_seed);
172 repeat_ = GTEST_FLAG(repeat);
173 shuffle_ = GTEST_FLAG(shuffle);
174 stack_trace_depth_ = GTEST_FLAG(stack_trace_depth);
175 stream_result_to_ = GTEST_FLAG(stream_result_to);
176 throw_on_failure_ = GTEST_FLAG(throw_on_failure);
179 // The d'tor is not virtual. DO NOT INHERIT FROM THIS CLASS.
181 GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_;
182 GTEST_FLAG(break_on_failure) = break_on_failure_;
183 GTEST_FLAG(catch_exceptions) = catch_exceptions_;
184 GTEST_FLAG(color) = color_;
185 GTEST_FLAG(death_test_style) = death_test_style_;
186 GTEST_FLAG(death_test_use_fork) = death_test_use_fork_;
187 GTEST_FLAG(filter) = filter_;
188 GTEST_FLAG(internal_run_death_test) = internal_run_death_test_;
189 GTEST_FLAG(list_tests) = list_tests_;
190 GTEST_FLAG(output) = output_;
191 GTEST_FLAG(print_time) = print_time_;
192 GTEST_FLAG(print_utf8) = print_utf8_;
193 GTEST_FLAG(random_seed) = random_seed_;
194 GTEST_FLAG(repeat) = repeat_;
195 GTEST_FLAG(shuffle) = shuffle_;
196 GTEST_FLAG(stack_trace_depth) = stack_trace_depth_;
197 GTEST_FLAG(stream_result_to) = stream_result_to_;
198 GTEST_FLAG(throw_on_failure) = throw_on_failure_;
202 // Fields for saving the original values of flags.
203 bool also_run_disabled_tests_;
204 bool break_on_failure_;
205 bool catch_exceptions_;
207 std::string death_test_style_;
208 bool death_test_use_fork_;
210 std::string internal_run_death_test_;
215 internal::Int32 random_seed_;
216 internal::Int32 repeat_;
218 internal::Int32 stack_trace_depth_;
219 std::string stream_result_to_;
220 bool throw_on_failure_;
221 } GTEST_ATTRIBUTE_UNUSED_;
223 // Converts a Unicode code point to a narrow string in UTF-8 encoding.
224 // code_point parameter is of type UInt32 because wchar_t may not be
225 // wide enough to contain a code point.
226 // If the code_point is not a valid Unicode code point
227 // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
228 // to "(Invalid Unicode 0xXXXXXXXX)".
229 GTEST_API_ std::string CodePointToUtf8(UInt32 code_point);
231 // Converts a wide string to a narrow string in UTF-8 encoding.
232 // The wide string is assumed to have the following encoding:
233 // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
234 // UTF-32 if sizeof(wchar_t) == 4 (on Linux)
235 // Parameter str points to a null-terminated wide string.
236 // Parameter num_chars may additionally limit the number
237 // of wchar_t characters processed. -1 is used when the entire string
238 // should be processed.
239 // If the string contains code points that are not valid Unicode code points
240 // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
241 // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
242 // and contains invalid UTF-16 surrogate pairs, values in those pairs
243 // will be encoded as individual Unicode characters from Basic Normal Plane.
244 GTEST_API_ std::string WideStringToUtf8(const wchar_t* str, int num_chars);
246 // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
247 // if the variable is present. If a file already exists at this location, this
248 // function will write over it. If the variable is present, but the file cannot
249 // be created, prints an error and exits.
250 void WriteToShardStatusFileIfNeeded();
252 // Checks whether sharding is enabled by examining the relevant
253 // environment variable values. If the variables are present,
254 // but inconsistent (e.g., shard_index >= total_shards), prints
255 // an error and exits. If in_subprocess_for_death_test, sharding is
256 // disabled because it must only be applied to the original test
257 // process. Otherwise, we could filter out death tests we intended to execute.
258 GTEST_API_ bool ShouldShard(const char* total_shards_str,
259 const char* shard_index_str,
260 bool in_subprocess_for_death_test);
262 // Parses the environment variable var as an Int32. If it is unset,
263 // returns default_val. If it is not an Int32, prints an error and
265 GTEST_API_ Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val);
267 // Given the total number of shards, the shard index, and the test id,
268 // returns true iff the test should be run on this shard. The test id is
269 // some arbitrary but unique non-negative integer assigned to each test
270 // method. Assumes that 0 <= shard_index < total_shards.
271 GTEST_API_ bool ShouldRunTestOnShard(
272 int total_shards, int shard_index, int test_id);
274 // STL container utilities.
276 // Returns the number of elements in the given container that satisfy
277 // the given predicate.
278 template <class Container, typename Predicate>
279 inline int CountIf(const Container& c, Predicate predicate) {
280 // Implemented as an explicit loop since std::count_if() in libCstd on
281 // Solaris has a non-standard signature.
283 for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) {
290 // Applies a function/functor to each element in the container.
291 template <class Container, typename Functor>
292 void ForEach(const Container& c, Functor functor) {
293 std::for_each(c.begin(), c.end(), functor);
296 // Returns the i-th element of the vector, or default_value if i is not
297 // in range [0, v.size()).
298 template <typename E>
299 inline E GetElementOr(const std::vector<E>& v, int i, E default_value) {
300 return (i < 0 || i >= static_cast<int>(v.size())) ? default_value : v[i];
303 // Performs an in-place shuffle of a range of the vector's elements.
304 // 'begin' and 'end' are element indices as an STL-style range;
305 // i.e. [begin, end) are shuffled, where 'end' == size() means to
306 // shuffle to the end of the vector.
307 template <typename E>
308 void ShuffleRange(internal::Random* random, int begin, int end,
310 const int size = static_cast<int>(v->size());
311 GTEST_CHECK_(0 <= begin && begin <= size)
312 << "Invalid shuffle range start " << begin << ": must be in range [0, "
314 GTEST_CHECK_(begin <= end && end <= size)
315 << "Invalid shuffle range finish " << end << ": must be in range ["
316 << begin << ", " << size << "].";
318 // Fisher-Yates shuffle, from
319 // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
320 for (int range_width = end - begin; range_width >= 2; range_width--) {
321 const int last_in_range = begin + range_width - 1;
322 const int selected = begin + random->Generate(range_width);
323 std::swap((*v)[selected], (*v)[last_in_range]);
327 // Performs an in-place shuffle of the vector's elements.
328 template <typename E>
329 inline void Shuffle(internal::Random* random, std::vector<E>* v) {
330 ShuffleRange(random, 0, static_cast<int>(v->size()), v);
333 // A function for deleting an object. Handy for being used as a
335 template <typename T>
336 static void Delete(T* x) {
340 // A predicate that checks the key of a TestProperty against a known key.
342 // TestPropertyKeyIs is copyable.
343 class TestPropertyKeyIs {
347 // TestPropertyKeyIs has NO default constructor.
348 explicit TestPropertyKeyIs(const std::string& key) : key_(key) {}
350 // Returns true iff the test name of test property matches on key_.
351 bool operator()(const TestProperty& test_property) const {
352 return test_property.key() == key_;
359 // Class UnitTestOptions.
361 // This class contains functions for processing options the user
362 // specifies when running the tests. It has only static members.
364 // In most cases, the user can specify an option using either an
365 // environment variable or a command line flag. E.g. you can set the
366 // test filter using either GTEST_FILTER or --gtest_filter. If both
367 // the variable and the flag are present, the latter overrides the
369 class GTEST_API_ UnitTestOptions {
371 // Functions for processing the gtest_output flag.
373 // Returns the output format, or "" for normal printed output.
374 static std::string GetOutputFormat();
376 // Returns the absolute path of the requested output file, or the
377 // default (test_detail.xml in the original working directory) if
378 // none was explicitly specified.
379 static std::string GetAbsolutePathToOutputFile();
381 // Functions for processing the gtest_filter flag.
383 // Returns true iff the wildcard pattern matches the string. The
384 // first ':' or '\0' character in pattern marks the end of it.
386 // This recursive algorithm isn't very efficient, but is clear and
387 // works well enough for matching test names, which are short.
388 static bool PatternMatchesString(const char *pattern, const char *str);
390 // Returns true iff the user-specified filter matches the test case
391 // name and the test name.
392 static bool FilterMatchesTest(const std::string &test_case_name,
393 const std::string &test_name);
396 // Function for supporting the gtest_catch_exception flag.
398 // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
399 // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
400 // This function is useful as an __except condition.
401 static int GTestShouldProcessSEH(DWORD exception_code);
402 #endif // GTEST_OS_WINDOWS
404 // Returns true if "name" matches the ':' separated list of glob-style
405 // filters in "filter".
406 static bool MatchesFilter(const std::string& name, const char* filter);
409 // Returns the current application's name, removing directory path if that
410 // is present. Used by UnitTestOptions::GetOutputFile.
411 GTEST_API_ FilePath GetCurrentExecutableName();
413 // The role interface for getting the OS stack trace as a string.
414 class OsStackTraceGetterInterface {
416 OsStackTraceGetterInterface() {}
417 virtual ~OsStackTraceGetterInterface() {}
419 // Returns the current OS stack trace as an std::string. Parameters:
421 // max_depth - the maximum number of stack frames to be included
423 // skip_count - the number of top frames to be skipped; doesn't count
424 // against max_depth.
425 virtual std::string CurrentStackTrace(int max_depth, int skip_count) = 0;
427 // UponLeavingGTest() should be called immediately before Google Test calls
428 // user code. It saves some information about the current stack that
429 // CurrentStackTrace() will use to find and hide Google Test stack frames.
430 virtual void UponLeavingGTest() = 0;
432 // This string is inserted in place of stack frames that are part of
433 // Google Test's implementation.
434 static const char* const kElidedFramesMarker;
437 GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface);
440 // A working implementation of the OsStackTraceGetterInterface interface.
441 class OsStackTraceGetter : public OsStackTraceGetterInterface {
443 OsStackTraceGetter() {}
445 virtual std::string CurrentStackTrace(int max_depth, int skip_count);
446 virtual void UponLeavingGTest();
450 Mutex mutex_; // Protects all internal state.
452 // We save the stack frame below the frame that calls user code.
453 // We do this because the address of the frame immediately below
454 // the user code changes between the call to UponLeavingGTest()
455 // and any calls to the stack trace code from within the user code.
456 void* caller_frame_ = nullptr;
457 #endif // GTEST_HAS_ABSL
459 GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter);
462 // Information about a Google Test trace point.
469 // This is the default global test part result reporter used in UnitTestImpl.
470 // This class should only be used by UnitTestImpl.
471 class DefaultGlobalTestPartResultReporter
472 : public TestPartResultReporterInterface {
474 explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test);
475 // Implements the TestPartResultReporterInterface. Reports the test part
476 // result in the current test.
477 virtual void ReportTestPartResult(const TestPartResult& result);
480 UnitTestImpl* const unit_test_;
482 GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter);
485 // This is the default per thread test part result reporter used in
486 // UnitTestImpl. This class should only be used by UnitTestImpl.
487 class DefaultPerThreadTestPartResultReporter
488 : public TestPartResultReporterInterface {
490 explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test);
491 // Implements the TestPartResultReporterInterface. The implementation just
492 // delegates to the current global test part result reporter of *unit_test_.
493 virtual void ReportTestPartResult(const TestPartResult& result);
496 UnitTestImpl* const unit_test_;
498 GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter);
501 // The private implementation of the UnitTest class. We don't protect
502 // the methods under a mutex, as this class is not accessible by a
503 // user and the UnitTest class that delegates work to this class does
505 class GTEST_API_ UnitTestImpl {
507 explicit UnitTestImpl(UnitTest* parent);
508 virtual ~UnitTestImpl();
510 // There are two different ways to register your own TestPartResultReporter.
511 // You can register your own repoter to listen either only for test results
512 // from the current thread or for results from all threads.
513 // By default, each per-thread test result repoter just passes a new
514 // TestPartResult to the global test result reporter, which registers the
515 // test part result for the currently running test.
517 // Returns the global test part result reporter.
518 TestPartResultReporterInterface* GetGlobalTestPartResultReporter();
520 // Sets the global test part result reporter.
521 void SetGlobalTestPartResultReporter(
522 TestPartResultReporterInterface* reporter);
524 // Returns the test part result reporter for the current thread.
525 TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread();
527 // Sets the test part result reporter for the current thread.
528 void SetTestPartResultReporterForCurrentThread(
529 TestPartResultReporterInterface* reporter);
531 // Gets the number of successful test cases.
532 int successful_test_case_count() const;
534 // Gets the number of failed test cases.
535 int failed_test_case_count() const;
537 // Gets the number of all test cases.
538 int total_test_case_count() const;
540 // Gets the number of all test cases that contain at least one test
542 int test_case_to_run_count() const;
544 // Gets the number of successful tests.
545 int successful_test_count() const;
547 // Gets the number of skipped tests.
548 int skipped_test_count() const;
550 // Gets the number of failed tests.
551 int failed_test_count() const;
553 // Gets the number of disabled tests that will be reported in the XML report.
554 int reportable_disabled_test_count() const;
556 // Gets the number of disabled tests.
557 int disabled_test_count() const;
559 // Gets the number of tests to be printed in the XML report.
560 int reportable_test_count() const;
562 // Gets the number of all tests.
563 int total_test_count() const;
565 // Gets the number of tests that should run.
566 int test_to_run_count() const;
568 // Gets the time of the test program start, in ms from the start of the
570 TimeInMillis start_timestamp() const { return start_timestamp_; }
572 // Gets the elapsed time, in milliseconds.
573 TimeInMillis elapsed_time() const { return elapsed_time_; }
575 // Returns true iff the unit test passed (i.e. all test cases passed).
576 bool Passed() const { return !Failed(); }
578 // Returns true iff the unit test failed (i.e. some test case failed
579 // or something outside of all tests failed).
580 bool Failed() const {
581 return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed();
584 // Gets the i-th test case among all the test cases. i can range from 0 to
585 // total_test_case_count() - 1. If i is not in that range, returns NULL.
586 const TestCase* GetTestCase(int i) const {
587 const int index = GetElementOr(test_case_indices_, i, -1);
588 return index < 0 ? NULL : test_cases_[i];
591 // Gets the i-th test case among all the test cases. i can range from 0 to
592 // total_test_case_count() - 1. If i is not in that range, returns NULL.
593 TestCase* GetMutableTestCase(int i) {
594 const int index = GetElementOr(test_case_indices_, i, -1);
595 return index < 0 ? NULL : test_cases_[index];
598 // Provides access to the event listener list.
599 TestEventListeners* listeners() { return &listeners_; }
601 // Returns the TestResult for the test that's currently running, or
602 // the TestResult for the ad hoc test if no test is running.
603 TestResult* current_test_result();
605 // Returns the TestResult for the ad hoc test.
606 const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; }
608 // Sets the OS stack trace getter.
610 // Does nothing if the input and the current OS stack trace getter
611 // are the same; otherwise, deletes the old getter and makes the
612 // input the current getter.
613 void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter);
615 // Returns the current OS stack trace getter if it is not NULL;
616 // otherwise, creates an OsStackTraceGetter, makes it the current
617 // getter, and returns it.
618 OsStackTraceGetterInterface* os_stack_trace_getter();
620 // Returns the current OS stack trace as an std::string.
622 // The maximum number of stack frames to be included is specified by
623 // the gtest_stack_trace_depth flag. The skip_count parameter
624 // specifies the number of top frames to be skipped, which doesn't
625 // count against the number of frames to be included.
627 // For example, if Foo() calls Bar(), which in turn calls
628 // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
629 // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
630 std::string CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_;
632 // Finds and returns a TestCase with the given name. If one doesn't
633 // exist, creates one and returns it.
637 // test_case_name: name of the test case
638 // type_param: the name of the test's type parameter, or NULL if
639 // this is not a typed or a type-parameterized test.
640 // set_up_tc: pointer to the function that sets up the test case
641 // tear_down_tc: pointer to the function that tears down the test case
642 TestCase* GetTestCase(const char* test_case_name,
643 const char* type_param,
644 Test::SetUpTestCaseFunc set_up_tc,
645 Test::TearDownTestCaseFunc tear_down_tc);
647 // Adds a TestInfo to the unit test.
651 // set_up_tc: pointer to the function that sets up the test case
652 // tear_down_tc: pointer to the function that tears down the test case
653 // test_info: the TestInfo object
654 void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc,
655 Test::TearDownTestCaseFunc tear_down_tc,
656 TestInfo* test_info) {
657 // In order to support thread-safe death tests, we need to
658 // remember the original working directory when the test program
659 // was first invoked. We cannot do this in RUN_ALL_TESTS(), as
660 // the user may have changed the current directory before calling
661 // RUN_ALL_TESTS(). Therefore we capture the current directory in
662 // AddTestInfo(), which is called to register a TEST or TEST_F
663 // before main() is reached.
664 if (original_working_dir_.IsEmpty()) {
665 original_working_dir_.Set(FilePath::GetCurrentDir());
666 GTEST_CHECK_(!original_working_dir_.IsEmpty())
667 << "Failed to get the current working directory.";
670 GetTestCase(test_info->test_case_name(),
671 test_info->type_param(),
673 tear_down_tc)->AddTestInfo(test_info);
676 // Returns ParameterizedTestCaseRegistry object used to keep track of
677 // value-parameterized tests and instantiate and register them.
678 internal::ParameterizedTestCaseRegistry& parameterized_test_registry() {
679 return parameterized_test_registry_;
682 // Sets the TestCase object for the test that's currently running.
683 void set_current_test_case(TestCase* a_current_test_case) {
684 current_test_case_ = a_current_test_case;
687 // Sets the TestInfo object for the test that's currently running. If
688 // current_test_info is NULL, the assertion results will be stored in
689 // ad_hoc_test_result_.
690 void set_current_test_info(TestInfo* a_current_test_info) {
691 current_test_info_ = a_current_test_info;
694 // Registers all parameterized tests defined using TEST_P and
695 // INSTANTIATE_TEST_CASE_P, creating regular tests for each test/parameter
696 // combination. This method can be called more then once; it has guards
697 // protecting from registering the tests more then once. If
698 // value-parameterized tests are disabled, RegisterParameterizedTests is
699 // present but does nothing.
700 void RegisterParameterizedTests();
702 // Runs all tests in this UnitTest object, prints the result, and
703 // returns true if all tests are successful. If any exception is
704 // thrown during a test, this test is considered to be failed, but
705 // the rest of the tests will still be run.
708 // Clears the results of all tests, except the ad hoc tests.
709 void ClearNonAdHocTestResult() {
710 ForEach(test_cases_, TestCase::ClearTestCaseResult);
713 // Clears the results of ad-hoc test assertions.
714 void ClearAdHocTestResult() {
715 ad_hoc_test_result_.Clear();
718 // Adds a TestProperty to the current TestResult object when invoked in a
719 // context of a test or a test case, or to the global property set. If the
720 // result already contains a property with the same key, the value will be
722 void RecordProperty(const TestProperty& test_property);
724 enum ReactionToSharding {
725 HONOR_SHARDING_PROTOCOL,
726 IGNORE_SHARDING_PROTOCOL
729 // Matches the full name of each test against the user-specified
730 // filter to decide whether the test should run, then records the
731 // result in each TestCase and TestInfo object.
732 // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests
733 // based on sharding variables in the environment.
734 // Returns the number of tests that should run.
735 int FilterTests(ReactionToSharding shard_tests);
737 // Prints the names of the tests matching the user-specified filter flag.
738 void ListTestsMatchingFilter();
740 const TestCase* current_test_case() const { return current_test_case_; }
741 TestInfo* current_test_info() { return current_test_info_; }
742 const TestInfo* current_test_info() const { return current_test_info_; }
744 // Returns the vector of environments that need to be set-up/torn-down
745 // before/after the tests are run.
746 std::vector<Environment*>& environments() { return environments_; }
748 // Getters for the per-thread Google Test trace stack.
749 std::vector<TraceInfo>& gtest_trace_stack() {
750 return *(gtest_trace_stack_.pointer());
752 const std::vector<TraceInfo>& gtest_trace_stack() const {
753 return gtest_trace_stack_.get();
756 #if GTEST_HAS_DEATH_TEST
757 void InitDeathTestSubprocessControlInfo() {
758 internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());
760 // Returns a pointer to the parsed --gtest_internal_run_death_test
761 // flag, or NULL if that flag was not specified.
762 // This information is useful only in a death test child process.
763 // Must not be called before a call to InitGoogleTest.
764 const InternalRunDeathTestFlag* internal_run_death_test_flag() const {
765 return internal_run_death_test_flag_.get();
768 // Returns a pointer to the current death test factory.
769 internal::DeathTestFactory* death_test_factory() {
770 return death_test_factory_.get();
773 void SuppressTestEventsIfInSubprocess();
775 friend class ReplaceDeathTestFactory;
776 #endif // GTEST_HAS_DEATH_TEST
778 // Initializes the event listener performing XML output as specified by
779 // UnitTestOptions. Must not be called before InitGoogleTest.
780 void ConfigureXmlOutput();
782 #if GTEST_CAN_STREAM_RESULTS_
783 // Initializes the event listener for streaming test results to a socket.
784 // Must not be called before InitGoogleTest.
785 void ConfigureStreamingOutput();
788 // Performs initialization dependent upon flag values obtained in
789 // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
790 // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
791 // this function is also called from RunAllTests. Since this function can be
792 // called more than once, it has to be idempotent.
793 void PostFlagParsingInit();
795 // Gets the random seed used at the start of the current test iteration.
796 int random_seed() const { return random_seed_; }
798 // Gets the random number generator.
799 internal::Random* random() { return &random_; }
801 // Shuffles all test cases, and the tests within each test case,
802 // making sure that death tests are still run first.
805 // Restores the test cases and tests to their order before the first shuffle.
806 void UnshuffleTests();
808 // Returns the value of GTEST_FLAG(catch_exceptions) at the moment
809 // UnitTest::Run() starts.
810 bool catch_exceptions() const { return catch_exceptions_; }
813 friend class ::testing::UnitTest;
815 // Used by UnitTest::Run() to capture the state of
816 // GTEST_FLAG(catch_exceptions) at the moment it starts.
817 void set_catch_exceptions(bool value) { catch_exceptions_ = value; }
819 // The UnitTest object that owns this implementation object.
820 UnitTest* const parent_;
822 // The working directory when the first TEST() or TEST_F() was
824 internal::FilePath original_working_dir_;
826 // The default test part result reporters.
827 DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_;
828 DefaultPerThreadTestPartResultReporter
829 default_per_thread_test_part_result_reporter_;
831 // Points to (but doesn't own) the global test part result reporter.
832 TestPartResultReporterInterface* global_test_part_result_repoter_;
834 // Protects read and write access to global_test_part_result_reporter_.
835 internal::Mutex global_test_part_result_reporter_mutex_;
837 // Points to (but doesn't own) the per-thread test part result reporter.
838 internal::ThreadLocal<TestPartResultReporterInterface*>
839 per_thread_test_part_result_reporter_;
841 // The vector of environments that need to be set-up/torn-down
842 // before/after the tests are run.
843 std::vector<Environment*> environments_;
845 // The vector of TestCases in their original order. It owns the
846 // elements in the vector.
847 std::vector<TestCase*> test_cases_;
849 // Provides a level of indirection for the test case list to allow
850 // easy shuffling and restoring the test case order. The i-th
851 // element of this vector is the index of the i-th test case in the
853 std::vector<int> test_case_indices_;
855 // ParameterizedTestRegistry object used to register value-parameterized
857 internal::ParameterizedTestCaseRegistry parameterized_test_registry_;
859 // Indicates whether RegisterParameterizedTests() has been called already.
860 bool parameterized_tests_registered_;
862 // Index of the last death test case registered. Initially -1.
863 int last_death_test_case_;
865 // This points to the TestCase for the currently running test. It
866 // changes as Google Test goes through one test case after another.
867 // When no test is running, this is set to NULL and Google Test
868 // stores assertion results in ad_hoc_test_result_. Initially NULL.
869 TestCase* current_test_case_;
871 // This points to the TestInfo for the currently running test. It
872 // changes as Google Test goes through one test after another. When
873 // no test is running, this is set to NULL and Google Test stores
874 // assertion results in ad_hoc_test_result_. Initially NULL.
875 TestInfo* current_test_info_;
877 // Normally, a user only writes assertions inside a TEST or TEST_F,
878 // or inside a function called by a TEST or TEST_F. Since Google
879 // Test keeps track of which test is current running, it can
880 // associate such an assertion with the test it belongs to.
882 // If an assertion is encountered when no TEST or TEST_F is running,
883 // Google Test attributes the assertion result to an imaginary "ad hoc"
884 // test, and records the result in ad_hoc_test_result_.
885 TestResult ad_hoc_test_result_;
887 // The list of event listeners that can be used to track events inside
889 TestEventListeners listeners_;
891 // The OS stack trace getter. Will be deleted when the UnitTest
892 // object is destructed. By default, an OsStackTraceGetter is used,
893 // but the user can set this field to use a custom getter if that is
895 OsStackTraceGetterInterface* os_stack_trace_getter_;
897 // True iff PostFlagParsingInit() has been called.
898 bool post_flag_parse_init_performed_;
900 // The random number seed used at the beginning of the test run.
903 // Our random number generator.
904 internal::Random random_;
906 // The time of the test program start, in ms from the start of the
908 TimeInMillis start_timestamp_;
910 // How long the test took to run, in milliseconds.
911 TimeInMillis elapsed_time_;
913 #if GTEST_HAS_DEATH_TEST
914 // The decomposed components of the gtest_internal_run_death_test flag,
915 // parsed when RUN_ALL_TESTS is called.
916 internal::scoped_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;
917 internal::scoped_ptr<internal::DeathTestFactory> death_test_factory_;
918 #endif // GTEST_HAS_DEATH_TEST
920 // A per-thread stack of traces created by the SCOPED_TRACE() macro.
921 internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_;
923 // The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests()
925 bool catch_exceptions_;
927 GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl);
928 }; // class UnitTestImpl
930 // Convenience function for accessing the global UnitTest
931 // implementation object.
932 inline UnitTestImpl* GetUnitTestImpl() {
933 return UnitTest::GetInstance()->impl();
936 #if GTEST_USES_SIMPLE_RE
938 // Internal helper functions for implementing the simple regular
939 // expression matcher.
940 GTEST_API_ bool IsInSet(char ch, const char* str);
941 GTEST_API_ bool IsAsciiDigit(char ch);
942 GTEST_API_ bool IsAsciiPunct(char ch);
943 GTEST_API_ bool IsRepeat(char ch);
944 GTEST_API_ bool IsAsciiWhiteSpace(char ch);
945 GTEST_API_ bool IsAsciiWordChar(char ch);
946 GTEST_API_ bool IsValidEscape(char ch);
947 GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch);
948 GTEST_API_ bool ValidateRegex(const char* regex);
949 GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str);
950 GTEST_API_ bool MatchRepetitionAndRegexAtHead(
951 bool escaped, char ch, char repeat, const char* regex, const char* str);
952 GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str);
954 #endif // GTEST_USES_SIMPLE_RE
956 // Parses the command line for Google Test flags, without initializing
957 // other parts of Google Test.
958 GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv);
959 GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv);
961 #if GTEST_HAS_DEATH_TEST
963 // Returns the message describing the last system error, regardless of the
965 GTEST_API_ std::string GetLastErrnoDescription();
967 // Attempts to parse a string into a positive integer pointed to by the
968 // number parameter. Returns true if that is possible.
969 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use
971 template <typename Integer>
972 bool ParseNaturalNumber(const ::std::string& str, Integer* number) {
973 // Fail fast if the given string does not begin with a digit;
974 // this bypasses strtoXXX's "optional leading whitespace and plus
975 // or minus sign" semantics, which are undesirable here.
976 if (str.empty() || !IsDigit(str[0])) {
982 // BiggestConvertible is the largest integer type that system-provided
983 // string-to-number conversion routines can return.
985 # if GTEST_OS_WINDOWS && !defined(__GNUC__)
987 // MSVC and C++ Builder define __int64 instead of the standard long long.
988 typedef unsigned __int64 BiggestConvertible;
989 const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10);
993 typedef unsigned long long BiggestConvertible; // NOLINT
994 const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10);
996 # endif // GTEST_OS_WINDOWS && !defined(__GNUC__)
998 const bool parse_success = *end == '\0' && errno == 0;
1000 // FIXME: Convert this to compile time assertion when it is
1002 GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed));
1004 const Integer result = static_cast<Integer>(parsed);
1005 if (parse_success && static_cast<BiggestConvertible>(result) == parsed) {
1011 #endif // GTEST_HAS_DEATH_TEST
1013 // TestResult contains some private methods that should be hidden from
1014 // Google Test user but are required for testing. This class allow our tests
1017 // This class is supplied only for the purpose of testing Google Test's own
1018 // constructs. Do not use it in user tests, either directly or indirectly.
1019 class TestResultAccessor {
1021 static void RecordProperty(TestResult* test_result,
1022 const std::string& xml_element,
1023 const TestProperty& property) {
1024 test_result->RecordProperty(xml_element, property);
1027 static void ClearTestPartResults(TestResult* test_result) {
1028 test_result->ClearTestPartResults();
1031 static const std::vector<testing::TestPartResult>& test_part_results(
1032 const TestResult& test_result) {
1033 return test_result.test_part_results();
1037 #if GTEST_CAN_STREAM_RESULTS_
1039 // Streams test results to the given port on the given host machine.
1040 class StreamingListener : public EmptyTestEventListener {
1042 // Abstract base class for writing strings to a socket.
1043 class AbstractSocketWriter {
1045 virtual ~AbstractSocketWriter() {}
1047 // Sends a string to the socket.
1048 virtual void Send(const std::string& message) = 0;
1050 // Closes the socket.
1051 virtual void CloseConnection() {}
1053 // Sends a string and a newline to the socket.
1054 void SendLn(const std::string& message) { Send(message + "\n"); }
1057 // Concrete class for actually writing strings to a socket.
1058 class SocketWriter : public AbstractSocketWriter {
1060 SocketWriter(const std::string& host, const std::string& port)
1061 : sockfd_(-1), host_name_(host), port_num_(port) {
1065 virtual ~SocketWriter() {
1070 // Sends a string to the socket.
1071 virtual void Send(const std::string& message) {
1072 GTEST_CHECK_(sockfd_ != -1)
1073 << "Send() can be called only when there is a connection.";
1075 const int len = static_cast<int>(message.length());
1076 if (write(sockfd_, message.c_str(), len) != len) {
1078 << "stream_result_to: failed to stream to "
1079 << host_name_ << ":" << port_num_;
1084 // Creates a client socket and connects to the server.
1085 void MakeConnection();
1087 // Closes the socket.
1088 void CloseConnection() {
1089 GTEST_CHECK_(sockfd_ != -1)
1090 << "CloseConnection() can be called only when there is a connection.";
1096 int sockfd_; // socket file descriptor
1097 const std::string host_name_;
1098 const std::string port_num_;
1100 GTEST_DISALLOW_COPY_AND_ASSIGN_(SocketWriter);
1101 }; // class SocketWriter
1103 // Escapes '=', '&', '%', and '\n' characters in str as "%xx".
1104 static std::string UrlEncode(const char* str);
1106 StreamingListener(const std::string& host, const std::string& port)
1107 : socket_writer_(new SocketWriter(host, port)) {
1111 explicit StreamingListener(AbstractSocketWriter* socket_writer)
1112 : socket_writer_(socket_writer) { Start(); }
1114 void OnTestProgramStart(const UnitTest& /* unit_test */) {
1115 SendLn("event=TestProgramStart");
1118 void OnTestProgramEnd(const UnitTest& unit_test) {
1119 // Note that Google Test current only report elapsed time for each
1120 // test iteration, not for the entire test program.
1121 SendLn("event=TestProgramEnd&passed=" + FormatBool(unit_test.Passed()));
1123 // Notify the streaming server to stop.
1124 socket_writer_->CloseConnection();
1127 void OnTestIterationStart(const UnitTest& /* unit_test */, int iteration) {
1128 SendLn("event=TestIterationStart&iteration=" +
1129 StreamableToString(iteration));
1132 void OnTestIterationEnd(const UnitTest& unit_test, int /* iteration */) {
1133 SendLn("event=TestIterationEnd&passed=" +
1134 FormatBool(unit_test.Passed()) + "&elapsed_time=" +
1135 StreamableToString(unit_test.elapsed_time()) + "ms");
1138 void OnTestCaseStart(const TestCase& test_case) {
1139 SendLn(std::string("event=TestCaseStart&name=") + test_case.name());
1142 void OnTestCaseEnd(const TestCase& test_case) {
1143 SendLn("event=TestCaseEnd&passed=" + FormatBool(test_case.Passed())
1144 + "&elapsed_time=" + StreamableToString(test_case.elapsed_time())
1148 void OnTestStart(const TestInfo& test_info) {
1149 SendLn(std::string("event=TestStart&name=") + test_info.name());
1152 void OnTestEnd(const TestInfo& test_info) {
1153 SendLn("event=TestEnd&passed=" +
1154 FormatBool((test_info.result())->Passed()) +
1156 StreamableToString((test_info.result())->elapsed_time()) + "ms");
1159 void OnTestPartResult(const TestPartResult& test_part_result) {
1160 const char* file_name = test_part_result.file_name();
1161 if (file_name == NULL)
1163 SendLn("event=TestPartResult&file=" + UrlEncode(file_name) +
1164 "&line=" + StreamableToString(test_part_result.line_number()) +
1165 "&message=" + UrlEncode(test_part_result.message()));
1169 // Sends the given message and a newline to the socket.
1170 void SendLn(const std::string& message) { socket_writer_->SendLn(message); }
1172 // Called at the start of streaming to notify the receiver what
1173 // protocol we are using.
1174 void Start() { SendLn("gtest_streaming_protocol_version=1.0"); }
1176 std::string FormatBool(bool value) { return value ? "1" : "0"; }
1178 const scoped_ptr<AbstractSocketWriter> socket_writer_;
1180 GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener);
1181 }; // class StreamingListener
1183 #endif // GTEST_CAN_STREAM_RESULTS_
1185 } // namespace internal
1186 } // namespace testing
1188 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
1190 #endif // GTEST_SRC_GTEST_INTERNAL_INL_H_