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.
32 // Author: wan@google.com (Zhanyong Wan)
34 // This file contains purely Google Test's internal implementation. Please
35 // DO NOT #INCLUDE IT IN A USER PROGRAM.
37 #ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_
38 #define GTEST_SRC_GTEST_INTERNAL_INL_H_
40 // GTEST_IMPLEMENTATION is defined iff the current translation unit is
41 // part of Google Test's implementation.
42 #ifndef GTEST_IMPLEMENTATION
43 // A user is trying to include this from his code - just say no.
44 #error "gtest-internal-inl.h is part of Google Test's internal implementation."
45 #error "It must not be included except by Google Test itself."
46 #endif // GTEST_IMPLEMENTATION
50 #include <gtest/internal/gtest-port.h>
52 #ifdef GTEST_OS_WINDOWS
53 #include <windows.h> // NOLINT
54 #endif // GTEST_OS_WINDOWS
56 #include <gtest/gtest.h>
57 #include <gtest/gtest-spi.h>
61 // Declares the flags.
63 // We don't want the users to modify these flags in the code, but want
64 // Google Test's own unit tests to be able to access them. Therefore we
65 // declare them here as opposed to in gtest.h.
66 GTEST_DECLARE_bool_(break_on_failure);
67 GTEST_DECLARE_bool_(catch_exceptions);
68 GTEST_DECLARE_string_(color);
69 GTEST_DECLARE_string_(filter);
70 GTEST_DECLARE_bool_(list_tests);
71 GTEST_DECLARE_string_(output);
72 GTEST_DECLARE_bool_(print_time);
73 GTEST_DECLARE_int32_(repeat);
74 GTEST_DECLARE_int32_(stack_trace_depth);
75 GTEST_DECLARE_bool_(show_internal_stack_frames);
79 // The value of GetTestTypeId() as seen from within the Google Test
80 // library. This is solely for testing GetTestTypeId().
81 extern const TypeId kTestTypeIdInGoogleTest;
83 // Names of the flags (needed for parsing Google Test flags).
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 kRepeatFlag[] = "repeat";
93 // This class saves the values of all Google Test flags in its c'tor, and
94 // restores them in its d'tor.
95 class GTestFlagSaver {
99 break_on_failure_ = GTEST_FLAG(break_on_failure);
100 catch_exceptions_ = GTEST_FLAG(catch_exceptions);
101 color_ = GTEST_FLAG(color);
102 death_test_style_ = GTEST_FLAG(death_test_style);
103 filter_ = GTEST_FLAG(filter);
104 internal_run_death_test_ = GTEST_FLAG(internal_run_death_test);
105 list_tests_ = GTEST_FLAG(list_tests);
106 output_ = GTEST_FLAG(output);
107 print_time_ = GTEST_FLAG(print_time);
108 repeat_ = GTEST_FLAG(repeat);
111 // The d'tor is not virtual. DO NOT INHERIT FROM THIS CLASS.
113 GTEST_FLAG(break_on_failure) = break_on_failure_;
114 GTEST_FLAG(catch_exceptions) = catch_exceptions_;
115 GTEST_FLAG(color) = color_;
116 GTEST_FLAG(death_test_style) = death_test_style_;
117 GTEST_FLAG(filter) = filter_;
118 GTEST_FLAG(internal_run_death_test) = internal_run_death_test_;
119 GTEST_FLAG(list_tests) = list_tests_;
120 GTEST_FLAG(output) = output_;
121 GTEST_FLAG(print_time) = print_time_;
122 GTEST_FLAG(repeat) = repeat_;
125 // Fields for saving the original values of flags.
126 bool break_on_failure_;
127 bool catch_exceptions_;
129 String death_test_style_;
131 String internal_run_death_test_;
136 internal::Int32 repeat_;
137 } GTEST_ATTRIBUTE_UNUSED_;
139 // Converts a Unicode code point to a narrow string in UTF-8 encoding.
140 // code_point parameter is of type UInt32 because wchar_t may not be
141 // wide enough to contain a code point.
142 // The output buffer str must containt at least 32 characters.
143 // The function returns the address of the output buffer.
144 // If the code_point is not a valid Unicode code point
145 // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be output
146 // as '(Invalid Unicode 0xXXXXXXXX)'.
147 char* CodePointToUtf8(UInt32 code_point, char* str);
149 // Converts a wide string to a narrow string in UTF-8 encoding.
150 // The wide string is assumed to have the following encoding:
151 // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
152 // UTF-32 if sizeof(wchar_t) == 4 (on Linux)
153 // Parameter str points to a null-terminated wide string.
154 // Parameter num_chars may additionally limit the number
155 // of wchar_t characters processed. -1 is used when the entire string
156 // should be processed.
157 // If the string contains code points that are not valid Unicode code points
158 // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
159 // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
160 // and contains invalid UTF-16 surrogate pairs, values in those pairs
161 // will be encoded as individual Unicode characters from Basic Normal Plane.
162 String WideStringToUtf8(const wchar_t* str, int num_chars);
164 // Returns the number of active threads, or 0 when there is an error.
165 size_t GetThreadCount();
167 // List is a simple singly-linked list container.
169 // We cannot use std::list as Microsoft's implementation of STL has
170 // problems when exception is disabled. There is a hack to work
171 // around this, but we've seen cases where the hack fails to work.
173 // TODO(wan): switch to std::list when we have a reliable fix for the
174 // STL problem, e.g. when we upgrade to the next version of Visual
175 // C++, or (more likely) switch to STLport.
177 // The element type must support copy constructor.
179 // Forward declare List
180 template <typename E> // E is the element type.
183 // ListNode is a node in a singly-linked list. It consists of an
184 // element and a pointer to the next node. The last node in the list
185 // has a NULL value for its next pointer.
186 template <typename E> // E is the element type.
188 friend class List<E>;
195 // The c'tor is private s.t. only in the ListNode class and in its
196 // friend class List we can create a ListNode object.
198 // Creates a node with a given element value. The next pointer is
201 // ListNode does NOT have a default constructor. Always use this
202 // constructor (with parameter) to create a ListNode object.
203 explicit ListNode(const E & element) : element_(element), next_(NULL) {}
205 // We disallow copying ListNode
206 GTEST_DISALLOW_COPY_AND_ASSIGN_(ListNode);
210 // Gets the element in this node.
211 E & element() { return element_; }
212 const E & element() const { return element_; }
214 // Gets the next node in the list.
215 ListNode * next() { return next_; }
216 const ListNode * next() const { return next_; }
220 // List is a simple singly-linked list container.
221 template <typename E> // E is the element type.
225 // Creates an empty list.
226 List() : head_(NULL), last_(NULL), size_(0) {}
234 // 1. Deletes every node.
235 ListNode<E> * node = head_;
236 ListNode<E> * next = node->next();
240 if ( node == NULL ) break;
244 // 2. Resets the member variables.
245 head_ = last_ = NULL;
250 // Gets the number of elements.
251 int size() const { return size_; }
253 // Returns true if the list is empty.
254 bool IsEmpty() const { return size() == 0; }
256 // Gets the first element of the list, or NULL if the list is empty.
257 ListNode<E> * Head() { return head_; }
258 const ListNode<E> * Head() const { return head_; }
260 // Gets the last element of the list, or NULL if the list is empty.
261 ListNode<E> * Last() { return last_; }
262 const ListNode<E> * Last() const { return last_; }
264 // Adds an element to the end of the list. A copy of the element is
265 // created using the copy constructor, and then stored in the list.
266 // Changes made to the element in the list doesn't affect the source
267 // object, and vice versa.
268 void PushBack(const E & element) {
269 ListNode<E> * new_node = new ListNode<E>(element);
272 head_ = last_ = new_node;
275 last_->next_ = new_node;
281 // Adds an element to the beginning of this list.
282 void PushFront(const E& element) {
283 ListNode<E>* const new_node = new ListNode<E>(element);
286 head_ = last_ = new_node;
289 new_node->next_ = head_;
295 // Removes an element from the beginning of this list. If the
296 // result argument is not NULL, the removed element is stored in the
297 // memory it points to. Otherwise the element is thrown away.
298 // Returns true iff the list wasn't empty before the operation.
299 bool PopFront(E* result) {
300 if (size_ == 0) return false;
302 if (result != NULL) {
303 *result = head_->element_;
306 ListNode<E>* const old_head = head_;
309 head_ = last_ = NULL;
311 head_ = head_->next_;
318 // Inserts an element after a given node in the list. It's the
319 // caller's responsibility to ensure that the given node is in the
320 // list. If the given node is NULL, inserts the element at the
321 // front of the list.
322 ListNode<E>* InsertAfter(ListNode<E>* node, const E& element) {
328 ListNode<E>* const new_node = new ListNode<E>(element);
329 new_node->next_ = node->next_;
330 node->next_ = new_node;
339 // Returns the number of elements that satisfy a given predicate.
340 // The parameter 'predicate' is a Boolean function or functor that
341 // accepts a 'const E &', where E is the element type.
342 template <typename P> // P is the type of the predicate function/functor
343 int CountIf(P predicate) const {
345 for ( const ListNode<E> * node = Head();
347 node = node->next() ) {
348 if ( predicate(node->element()) ) {
356 // Applies a function/functor to each element in the list. The
357 // parameter 'functor' is a function/functor that accepts a 'const
358 // E &', where E is the element type. This method does not change
360 template <typename F> // F is the type of the function/functor
361 void ForEach(F functor) const {
362 for ( const ListNode<E> * node = Head();
364 node = node->next() ) {
365 functor(node->element());
369 // Returns the first node whose element satisfies a given predicate,
370 // or NULL if none is found. The parameter 'predicate' is a
371 // function/functor that accepts a 'const E &', where E is the
372 // element type. This method does not change the elements.
373 template <typename P> // P is the type of the predicate function/functor.
374 const ListNode<E> * FindIf(P predicate) const {
375 for ( const ListNode<E> * node = Head();
377 node = node->next() ) {
378 if ( predicate(node->element()) ) {
386 template <typename P>
387 ListNode<E> * FindIf(P predicate) {
388 for ( ListNode<E> * node = Head();
390 node = node->next() ) {
391 if ( predicate(node->element() ) ) {
400 ListNode<E>* head_; // The first node of the list.
401 ListNode<E>* last_; // The last node of the list.
402 int size_; // The number of elements in the list.
404 // We disallow copying List.
405 GTEST_DISALLOW_COPY_AND_ASSIGN_(List);
408 // The virtual destructor of List.
409 template <typename E>
414 // A function for deleting an object. Handy for being used as a
416 template <typename T>
417 static void Delete(T * x) {
421 // A copyable object representing a user specified test property which can be
422 // output as a key/value string pair.
424 // Don't inherit from TestProperty as its destructor is not virtual.
427 // C'tor. TestProperty does NOT have a default constructor.
428 // Always use this constructor (with parameters) to create a
429 // TestProperty object.
430 TestProperty(const char* key, const char* value) :
431 key_(key), value_(value) {
434 // Gets the user supplied key.
435 const char* key() const {
439 // Gets the user supplied value.
440 const char* value() const {
441 return value_.c_str();
444 // Sets a new value, overriding the one supplied in the constructor.
445 void SetValue(const char* new_value) {
450 // The key supplied by the user.
452 // The value supplied by the user.
456 // A predicate that checks the key of a TestProperty against a known key.
458 // TestPropertyKeyIs is copyable.
459 class TestPropertyKeyIs {
463 // TestPropertyKeyIs has NO default constructor.
464 explicit TestPropertyKeyIs(const char* key)
467 // Returns true iff the test name of test property matches on key_.
468 bool operator()(const TestProperty& test_property) const {
469 return String(test_property.key()).Compare(key_) == 0;
476 // The result of a single Test. This includes a list of
477 // TestPartResults, a list of TestProperties, a count of how many
478 // death tests there are in the Test, and how much time it took to run
481 // TestResult is not copyable.
484 // Creates an empty TestResult.
487 // D'tor. Do not inherit from TestResult.
490 // Gets the list of TestPartResults.
491 const internal::List<TestPartResult> & test_part_results() const {
492 return test_part_results_;
495 // Gets the list of TestProperties.
496 const internal::List<internal::TestProperty> & test_properties() const {
497 return test_properties_;
500 // Gets the number of successful test parts.
501 int successful_part_count() const;
503 // Gets the number of failed test parts.
504 int failed_part_count() const;
506 // Gets the number of all test parts. This is the sum of the number
507 // of successful test parts and the number of failed test parts.
508 int total_part_count() const;
510 // Returns true iff the test passed (i.e. no test part failed).
511 bool Passed() const { return !Failed(); }
513 // Returns true iff the test failed.
514 bool Failed() const { return failed_part_count() > 0; }
516 // Returns true iff the test fatally failed.
517 bool HasFatalFailure() const;
519 // Returns the elapsed time, in milliseconds.
520 TimeInMillis elapsed_time() const { return elapsed_time_; }
522 // Sets the elapsed time.
523 void set_elapsed_time(TimeInMillis elapsed) { elapsed_time_ = elapsed; }
525 // Adds a test part result to the list.
526 void AddTestPartResult(const TestPartResult& test_part_result);
528 // Adds a test property to the list. The property is validated and may add
529 // a non-fatal failure if invalid (e.g., if it conflicts with reserved
530 // key names). If a property is already recorded for the same key, the
531 // value will be updated, rather than storing multiple values for the same
533 void RecordProperty(const internal::TestProperty& test_property);
535 // Adds a failure if the key is a reserved attribute of Google Test
536 // testcase tags. Returns true if the property is valid.
537 // TODO(russr): Validate attribute names are legal and human readable.
538 static bool ValidateTestProperty(const internal::TestProperty& test_property);
540 // Returns the death test count.
541 int death_test_count() const { return death_test_count_; }
543 // Increments the death test count, returning the new count.
544 int increment_death_test_count() { return ++death_test_count_; }
546 // Clears the object.
549 // Protects mutable state of the property list and of owned properties, whose
550 // values may be updated.
551 internal::Mutex test_properites_mutex_;
553 // The list of TestPartResults
554 internal::List<TestPartResult> test_part_results_;
555 // The list of TestProperties
556 internal::List<internal::TestProperty> test_properties_;
557 // Running count of death tests.
558 int death_test_count_;
559 // The elapsed time, in milliseconds.
560 TimeInMillis elapsed_time_;
562 // We disallow copying TestResult.
563 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestResult);
564 }; // class TestResult
568 TestInfoImpl(TestInfo* parent, const char* test_case_name,
569 const char* name, const char* test_case_comment,
570 const char* comment, TypeId fixture_class_id,
571 internal::TestFactoryBase* factory);
574 // Returns true if this test should run.
575 bool should_run() const { return should_run_; }
577 // Sets the should_run member.
578 void set_should_run(bool should) { should_run_ = should; }
580 // Returns true if this test is disabled. Disabled tests are not run.
581 bool is_disabled() const { return is_disabled_; }
583 // Sets the is_disabled member.
584 void set_is_disabled(bool is) { is_disabled_ = is; }
586 // Returns the test case name.
587 const char* test_case_name() const { return test_case_name_.c_str(); }
589 // Returns the test name.
590 const char* name() const { return name_.c_str(); }
592 // Returns the test case comment.
593 const char* test_case_comment() const { return test_case_comment_.c_str(); }
595 // Returns the test comment.
596 const char* comment() const { return comment_.c_str(); }
598 // Returns the ID of the test fixture class.
599 TypeId fixture_class_id() const { return fixture_class_id_; }
601 // Returns the test result.
602 internal::TestResult* result() { return &result_; }
603 const internal::TestResult* result() const { return &result_; }
605 // Creates the test object, runs it, records its result, and then
609 // Calls the given TestInfo object's Run() method.
610 static void RunTest(TestInfo * test_info) {
611 test_info->impl()->Run();
614 // Clears the test result.
615 void ClearResult() { result_.Clear(); }
617 // Clears the test result in the given TestInfo object.
618 static void ClearTestResult(TestInfo * test_info) {
619 test_info->impl()->ClearResult();
623 // These fields are immutable properties of the test.
624 TestInfo* const parent_; // The owner of this object
625 const String test_case_name_; // Test case name
626 const String name_; // Test name
627 const String test_case_comment_; // Test case comment
628 const String comment_; // Test comment
629 const TypeId fixture_class_id_; // ID of the test fixture class
630 bool should_run_; // True iff this test should run
631 bool is_disabled_; // True iff this test is disabled
632 internal::TestFactoryBase* const factory_; // The factory that creates
635 // This field is mutable and needs to be reset before running the
636 // test for the second time.
637 internal::TestResult result_;
639 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestInfoImpl);
642 } // namespace internal
644 // A test case, which consists of a list of TestInfos.
646 // TestCase is not copyable.
649 // Creates a TestCase with the given name.
651 // TestCase does NOT have a default constructor. Always use this
652 // constructor to create a TestCase object.
656 // name: name of the test case
657 // set_up_tc: pointer to the function that sets up the test case
658 // tear_down_tc: pointer to the function that tears down the test case
659 TestCase(const char* name, const char* comment,
660 Test::SetUpTestCaseFunc set_up_tc,
661 Test::TearDownTestCaseFunc tear_down_tc);
663 // Destructor of TestCase.
666 // Gets the name of the TestCase.
667 const char* name() const { return name_.c_str(); }
669 // Returns the test case comment.
670 const char* comment() const { return comment_.c_str(); }
672 // Returns true if any test in this test case should run.
673 bool should_run() const { return should_run_; }
675 // Sets the should_run member.
676 void set_should_run(bool should) { should_run_ = should; }
678 // Gets the (mutable) list of TestInfos in this TestCase.
679 internal::List<TestInfo*>& test_info_list() { return *test_info_list_; }
681 // Gets the (immutable) list of TestInfos in this TestCase.
682 const internal::List<TestInfo *> & test_info_list() const {
683 return *test_info_list_;
686 // Gets the number of successful tests in this test case.
687 int successful_test_count() const;
689 // Gets the number of failed tests in this test case.
690 int failed_test_count() const;
692 // Gets the number of disabled tests in this test case.
693 int disabled_test_count() const;
695 // Get the number of tests in this test case that should run.
696 int test_to_run_count() const;
698 // Gets the number of all tests in this test case.
699 int total_test_count() const;
701 // Returns true iff the test case passed.
702 bool Passed() const { return !Failed(); }
704 // Returns true iff the test case failed.
705 bool Failed() const { return failed_test_count() > 0; }
707 // Returns the elapsed time, in milliseconds.
708 internal::TimeInMillis elapsed_time() const { return elapsed_time_; }
710 // Adds a TestInfo to this test case. Will delete the TestInfo upon
711 // destruction of the TestCase object.
712 void AddTestInfo(TestInfo * test_info);
714 // Finds and returns a TestInfo with the given name. If one doesn't
715 // exist, returns NULL.
716 TestInfo* GetTestInfo(const char* test_name);
718 // Clears the results of all tests in this test case.
721 // Clears the results of all tests in the given test case.
722 static void ClearTestCaseResult(TestCase* test_case) {
723 test_case->ClearResult();
726 // Runs every test in this TestCase.
729 // Runs every test in the given TestCase.
730 static void RunTestCase(TestCase * test_case) { test_case->Run(); }
732 // Returns true iff test passed.
733 static bool TestPassed(const TestInfo * test_info) {
734 const internal::TestInfoImpl* const impl = test_info->impl();
735 return impl->should_run() && impl->result()->Passed();
738 // Returns true iff test failed.
739 static bool TestFailed(const TestInfo * test_info) {
740 const internal::TestInfoImpl* const impl = test_info->impl();
741 return impl->should_run() && impl->result()->Failed();
744 // Returns true iff test is disabled.
745 static bool TestDisabled(const TestInfo * test_info) {
746 return test_info->impl()->is_disabled();
749 // Returns true if the given test should run.
750 static bool ShouldRunTest(const TestInfo *test_info) {
751 return test_info->impl()->should_run();
755 // Name of the test case.
756 internal::String name_;
757 // Comment on the test case.
758 internal::String comment_;
759 // List of TestInfos.
760 internal::List<TestInfo*>* test_info_list_;
761 // Pointer to the function that sets up the test case.
762 Test::SetUpTestCaseFunc set_up_tc_;
763 // Pointer to the function that tears down the test case.
764 Test::TearDownTestCaseFunc tear_down_tc_;
765 // True iff any test in this test case should run.
767 // Elapsed time, in milliseconds.
768 internal::TimeInMillis elapsed_time_;
770 // We disallow copying TestCases.
771 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestCase);
776 // Class UnitTestOptions.
778 // This class contains functions for processing options the user
779 // specifies when running the tests. It has only static members.
781 // In most cases, the user can specify an option using either an
782 // environment variable or a command line flag. E.g. you can set the
783 // test filter using either GTEST_FILTER or --gtest_filter. If both
784 // the variable and the flag are present, the latter overrides the
786 class UnitTestOptions {
788 // Functions for processing the gtest_output flag.
790 // Returns the output format, or "" for normal printed output.
791 static String GetOutputFormat();
793 // Returns the name of the requested output file, or the default if none
794 // was explicitly specified.
795 static String GetOutputFile();
797 // Functions for processing the gtest_filter flag.
799 // Returns true iff the wildcard pattern matches the string. The
800 // first ':' or '\0' character in pattern marks the end of it.
802 // This recursive algorithm isn't very efficient, but is clear and
803 // works well enough for matching test names, which are short.
804 static bool PatternMatchesString(const char *pattern, const char *str);
806 // Returns true iff the user-specified filter matches the test case
807 // name and the test name.
808 static bool FilterMatchesTest(const String &test_case_name,
809 const String &test_name);
811 #ifdef GTEST_OS_WINDOWS
812 // Function for supporting the gtest_catch_exception flag.
814 // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
815 // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
816 // This function is useful as an __except condition.
817 static int GTestShouldProcessSEH(DWORD exception_code);
818 #endif // GTEST_OS_WINDOWS
820 // Returns true if "name" matches the ':' separated list of glob-style
821 // filters in "filter".
822 static bool MatchesFilter(const String& name, const char* filter);
825 // Returns the current application's name, removing directory path if that
826 // is present. Used by UnitTestOptions::GetOutputFile.
827 FilePath GetCurrentExecutableName();
829 // The role interface for getting the OS stack trace as a string.
830 class OsStackTraceGetterInterface {
832 OsStackTraceGetterInterface() {}
833 virtual ~OsStackTraceGetterInterface() {}
835 // Returns the current OS stack trace as a String. Parameters:
837 // max_depth - the maximum number of stack frames to be included
839 // skip_count - the number of top frames to be skipped; doesn't count
840 // against max_depth.
841 virtual String CurrentStackTrace(int max_depth, int skip_count) = 0;
843 // UponLeavingGTest() should be called immediately before Google Test calls
844 // user code. It saves some information about the current stack that
845 // CurrentStackTrace() will use to find and hide Google Test stack frames.
846 virtual void UponLeavingGTest() = 0;
849 GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface);
852 // A working implementation of the OsStackTraceGetterInterface interface.
853 class OsStackTraceGetter : public OsStackTraceGetterInterface {
855 OsStackTraceGetter() {}
856 virtual String CurrentStackTrace(int max_depth, int skip_count);
857 virtual void UponLeavingGTest();
859 // This string is inserted in place of stack frames that are part of
860 // Google Test's implementation.
861 static const char* const kElidedFramesMarker;
864 Mutex mutex_; // protects all internal state
866 // We save the stack frame below the frame that calls user code.
867 // We do this because the address of the frame immediately below
868 // the user code changes between the call to UponLeavingGTest()
869 // and any calls to CurrentStackTrace() from within the user code.
872 GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter);
875 // Information about a Google Test trace point.
882 // This is the default global test part result reporter used in UnitTestImpl.
883 // This class should only be used by UnitTestImpl.
884 class DefaultGlobalTestPartResultReporter
885 : public TestPartResultReporterInterface {
887 explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test);
888 // Implements the TestPartResultReporterInterface. Reports the test part
889 // result in the current test.
890 virtual void ReportTestPartResult(const TestPartResult& result);
893 UnitTestImpl* const unit_test_;
896 // This is the default per thread test part result reporter used in
897 // UnitTestImpl. This class should only be used by UnitTestImpl.
898 class DefaultPerThreadTestPartResultReporter
899 : public TestPartResultReporterInterface {
901 explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test);
902 // Implements the TestPartResultReporterInterface. The implementation just
903 // delegates to the current global test part result reporter of *unit_test_.
904 virtual void ReportTestPartResult(const TestPartResult& result);
907 UnitTestImpl* const unit_test_;
910 // The private implementation of the UnitTest class. We don't protect
911 // the methods under a mutex, as this class is not accessible by a
912 // user and the UnitTest class that delegates work to this class does
916 explicit UnitTestImpl(UnitTest* parent);
917 virtual ~UnitTestImpl();
919 // There are two different ways to register your own TestPartResultReporter.
920 // You can register your own repoter to listen either only for test results
921 // from the current thread or for results from all threads.
922 // By default, each per-thread test result repoter just passes a new
923 // TestPartResult to the global test result reporter, which registers the
924 // test part result for the currently running test.
926 // Returns the global test part result reporter.
927 TestPartResultReporterInterface* GetGlobalTestPartResultReporter();
929 // Sets the global test part result reporter.
930 void SetGlobalTestPartResultReporter(
931 TestPartResultReporterInterface* reporter);
933 // Returns the test part result reporter for the current thread.
934 TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread();
936 // Sets the test part result reporter for the current thread.
937 void SetTestPartResultReporterForCurrentThread(
938 TestPartResultReporterInterface* reporter);
940 // Gets the number of successful test cases.
941 int successful_test_case_count() const;
943 // Gets the number of failed test cases.
944 int failed_test_case_count() const;
946 // Gets the number of all test cases.
947 int total_test_case_count() const;
949 // Gets the number of all test cases that contain at least one test
951 int test_case_to_run_count() const;
953 // Gets the number of successful tests.
954 int successful_test_count() const;
956 // Gets the number of failed tests.
957 int failed_test_count() const;
959 // Gets the number of disabled tests.
960 int disabled_test_count() const;
962 // Gets the number of all tests.
963 int total_test_count() const;
965 // Gets the number of tests that should run.
966 int test_to_run_count() const;
968 // Gets the elapsed time, in milliseconds.
969 TimeInMillis elapsed_time() const { return elapsed_time_; }
971 // Returns true iff the unit test passed (i.e. all test cases passed).
972 bool Passed() const { return !Failed(); }
974 // Returns true iff the unit test failed (i.e. some test case failed
975 // or something outside of all tests failed).
976 bool Failed() const {
977 return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed();
980 // Returns the TestResult for the test that's currently running, or
981 // the TestResult for the ad hoc test if no test is running.
982 internal::TestResult* current_test_result();
984 // Returns the TestResult for the ad hoc test.
985 const internal::TestResult* ad_hoc_test_result() const {
986 return &ad_hoc_test_result_;
989 // Sets the unit test result printer.
991 // Does nothing if the input and the current printer object are the
992 // same; otherwise, deletes the old printer object and makes the
993 // input the current printer.
994 void set_result_printer(UnitTestEventListenerInterface * result_printer);
996 // Returns the current unit test result printer if it is not NULL;
997 // otherwise, creates an appropriate result printer, makes it the
998 // current printer, and returns it.
999 UnitTestEventListenerInterface* result_printer();
1001 // Sets the OS stack trace getter.
1003 // Does nothing if the input and the current OS stack trace getter
1004 // are the same; otherwise, deletes the old getter and makes the
1005 // input the current getter.
1006 void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter);
1008 // Returns the current OS stack trace getter if it is not NULL;
1009 // otherwise, creates an OsStackTraceGetter, makes it the current
1010 // getter, and returns it.
1011 OsStackTraceGetterInterface* os_stack_trace_getter();
1013 // Returns the current OS stack trace as a String.
1015 // The maximum number of stack frames to be included is specified by
1016 // the gtest_stack_trace_depth flag. The skip_count parameter
1017 // specifies the number of top frames to be skipped, which doesn't
1018 // count against the number of frames to be included.
1020 // For example, if Foo() calls Bar(), which in turn calls
1021 // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
1022 // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
1023 String CurrentOsStackTraceExceptTop(int skip_count);
1025 // Finds and returns a TestCase with the given name. If one doesn't
1026 // exist, creates one and returns it.
1030 // test_case_name: name of the test case
1031 // set_up_tc: pointer to the function that sets up the test case
1032 // tear_down_tc: pointer to the function that tears down the test case
1033 TestCase* GetTestCase(const char* test_case_name,
1034 const char* comment,
1035 Test::SetUpTestCaseFunc set_up_tc,
1036 Test::TearDownTestCaseFunc tear_down_tc);
1038 // Adds a TestInfo to the unit test.
1042 // set_up_tc: pointer to the function that sets up the test case
1043 // tear_down_tc: pointer to the function that tears down the test case
1044 // test_info: the TestInfo object
1045 void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc,
1046 Test::TearDownTestCaseFunc tear_down_tc,
1047 TestInfo * test_info) {
1048 // In order to support thread-safe death tests, we need to
1049 // remember the original working directory when the test program
1050 // was first invoked. We cannot do this in RUN_ALL_TESTS(), as
1051 // the user may have changed the current directory before calling
1052 // RUN_ALL_TESTS(). Therefore we capture the current directory in
1053 // AddTestInfo(), which is called to register a TEST or TEST_F
1054 // before main() is reached.
1055 if (original_working_dir_.IsEmpty()) {
1056 original_working_dir_.Set(FilePath::GetCurrentDir());
1057 if (original_working_dir_.IsEmpty()) {
1058 printf("%s\n", "Failed to get the current working directory.");
1063 GetTestCase(test_info->test_case_name(),
1064 test_info->test_case_comment(),
1066 tear_down_tc)->AddTestInfo(test_info);
1069 #ifdef GTEST_HAS_PARAM_TEST
1070 // Returns ParameterizedTestCaseRegistry object used to keep track of
1071 // value-parameterized tests and instantiate and register them.
1072 internal::ParameterizedTestCaseRegistry& parameterized_test_registry() {
1073 return parameterized_test_registry_;
1075 #endif // GTEST_HAS_PARAM_TEST
1077 // Sets the TestCase object for the test that's currently running.
1078 void set_current_test_case(TestCase* current_test_case) {
1079 current_test_case_ = current_test_case;
1082 // Sets the TestInfo object for the test that's currently running. If
1083 // current_test_info is NULL, the assertion results will be stored in
1084 // ad_hoc_test_result_.
1085 void set_current_test_info(TestInfo* current_test_info) {
1086 current_test_info_ = current_test_info;
1089 // Registers all parameterized tests defined using TEST_P and
1090 // INSTANTIATE_TEST_P, creating regular tests for each test/parameter
1091 // combination. This method can be called more then once; it has
1092 // guards protecting from registering the tests more then once.
1093 // If value-parameterized tests are disabled, RegisterParameterizedTests
1094 // is present but does nothing.
1095 void RegisterParameterizedTests();
1097 // Runs all tests in this UnitTest object, prints the result, and
1098 // returns 0 if all tests are successful, or 1 otherwise. If any
1099 // exception is thrown during a test on Windows, this test is
1100 // considered to be failed, but the rest of the tests will still be
1101 // run. (We disable exceptions on Linux and Mac OS X, so the issue
1102 // doesn't apply there.)
1105 // Clears the results of all tests, including the ad hoc test.
1106 void ClearResult() {
1107 test_cases_.ForEach(TestCase::ClearTestCaseResult);
1108 ad_hoc_test_result_.Clear();
1111 // Matches the full name of each test against the user-specified
1112 // filter to decide whether the test should run, then records the
1113 // result in each TestCase and TestInfo object.
1114 // Returns the number of tests that should run.
1117 // Lists all the tests by name.
1118 void ListAllTests();
1120 const TestCase* current_test_case() const { return current_test_case_; }
1121 TestInfo* current_test_info() { return current_test_info_; }
1122 const TestInfo* current_test_info() const { return current_test_info_; }
1124 // Returns the list of environments that need to be set-up/torn-down
1125 // before/after the tests are run.
1126 internal::List<Environment*>* environments() { return &environments_; }
1127 internal::List<Environment*>* environments_in_reverse_order() {
1128 return &environments_in_reverse_order_;
1131 internal::List<TestCase*>* test_cases() { return &test_cases_; }
1132 const internal::List<TestCase*>* test_cases() const { return &test_cases_; }
1134 // Getters for the per-thread Google Test trace stack.
1135 internal::List<TraceInfo>* gtest_trace_stack() {
1136 return gtest_trace_stack_.pointer();
1138 const internal::List<TraceInfo>* gtest_trace_stack() const {
1139 return gtest_trace_stack_.pointer();
1142 #ifdef GTEST_HAS_DEATH_TEST
1143 // Returns a pointer to the parsed --gtest_internal_run_death_test
1144 // flag, or NULL if that flag was not specified.
1145 // This information is useful only in a death test child process.
1146 const InternalRunDeathTestFlag* internal_run_death_test_flag() const {
1147 return internal_run_death_test_flag_.get();
1150 // Returns a pointer to the current death test factory.
1151 internal::DeathTestFactory* death_test_factory() {
1152 return death_test_factory_.get();
1155 friend class ReplaceDeathTestFactory;
1156 #endif // GTEST_HAS_DEATH_TEST
1159 friend class ::testing::UnitTest;
1161 // The UnitTest object that owns this implementation object.
1162 UnitTest* const parent_;
1164 // The working directory when the first TEST() or TEST_F() was
1166 internal::FilePath original_working_dir_;
1168 // The default test part result reporters.
1169 DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_;
1170 DefaultPerThreadTestPartResultReporter
1171 default_per_thread_test_part_result_reporter_;
1173 // Points to (but doesn't own) the global test part result reporter.
1174 TestPartResultReporterInterface* global_test_part_result_repoter_;
1176 // Protects read and write access to global_test_part_result_reporter_.
1177 internal::Mutex global_test_part_result_reporter_mutex_;
1179 // Points to (but doesn't own) the per-thread test part result reporter.
1180 internal::ThreadLocal<TestPartResultReporterInterface*>
1181 per_thread_test_part_result_reporter_;
1183 // The list of environments that need to be set-up/torn-down
1184 // before/after the tests are run. environments_in_reverse_order_
1185 // simply mirrors environments_ in reverse order.
1186 internal::List<Environment*> environments_;
1187 internal::List<Environment*> environments_in_reverse_order_;
1189 internal::List<TestCase*> test_cases_; // The list of TestCases.
1191 #ifdef GTEST_HAS_PARAM_TEST
1192 // ParameterizedTestRegistry object used to register value-parameterized
1194 internal::ParameterizedTestCaseRegistry parameterized_test_registry_;
1196 // Indicates whether RegisterParameterizedTests() has been called already.
1197 bool parameterized_tests_registered_;
1198 #endif // GTEST_HAS_PARAM_TEST
1200 // Points to the last death test case registered. Initially NULL.
1201 internal::ListNode<TestCase*>* last_death_test_case_;
1203 // This points to the TestCase for the currently running test. It
1204 // changes as Google Test goes through one test case after another.
1205 // When no test is running, this is set to NULL and Google Test
1206 // stores assertion results in ad_hoc_test_result_. Initally NULL.
1207 TestCase* current_test_case_;
1209 // This points to the TestInfo for the currently running test. It
1210 // changes as Google Test goes through one test after another. When
1211 // no test is running, this is set to NULL and Google Test stores
1212 // assertion results in ad_hoc_test_result_. Initially NULL.
1213 TestInfo* current_test_info_;
1215 // Normally, a user only writes assertions inside a TEST or TEST_F,
1216 // or inside a function called by a TEST or TEST_F. Since Google
1217 // Test keeps track of which test is current running, it can
1218 // associate such an assertion with the test it belongs to.
1220 // If an assertion is encountered when no TEST or TEST_F is running,
1221 // Google Test attributes the assertion result to an imaginary "ad hoc"
1222 // test, and records the result in ad_hoc_test_result_.
1223 internal::TestResult ad_hoc_test_result_;
1225 // The unit test result printer. Will be deleted when the UnitTest
1226 // object is destructed. By default, a plain text printer is used,
1227 // but the user can set this field to use a custom printer if that
1229 UnitTestEventListenerInterface* result_printer_;
1231 // The OS stack trace getter. Will be deleted when the UnitTest
1232 // object is destructed. By default, an OsStackTraceGetter is used,
1233 // but the user can set this field to use a custom getter if that is
1235 OsStackTraceGetterInterface* os_stack_trace_getter_;
1237 // How long the test took to run, in milliseconds.
1238 TimeInMillis elapsed_time_;
1240 #ifdef GTEST_HAS_DEATH_TEST
1241 // The decomposed components of the gtest_internal_run_death_test flag,
1242 // parsed when RUN_ALL_TESTS is called.
1243 internal::scoped_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;
1244 internal::scoped_ptr<internal::DeathTestFactory> death_test_factory_;
1245 #endif // GTEST_HAS_DEATH_TEST
1247 // A per-thread stack of traces created by the SCOPED_TRACE() macro.
1248 internal::ThreadLocal<internal::List<TraceInfo> > gtest_trace_stack_;
1250 GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl);
1251 }; // class UnitTestImpl
1253 // Convenience function for accessing the global UnitTest
1254 // implementation object.
1255 inline UnitTestImpl* GetUnitTestImpl() {
1256 return UnitTest::GetInstance()->impl();
1259 // Parses the command line for Google Test flags, without initializing
1260 // other parts of Google Test.
1261 void ParseGoogleTestFlagsOnly(int* argc, char** argv);
1262 void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv);
1264 } // namespace internal
1265 } // namespace testing
1267 #endif // GTEST_SRC_GTEST_INTERNAL_INL_H_