Home | History | Annotate | Download | only in src
      1 // Copyright 2005, Google Inc.
      2 // All rights reserved.
      3 //
      4 // Redistribution and use in source and binary forms, with or without
      5 // modification, are permitted provided that the following conditions are
      6 // met:
      7 //
      8 //     * Redistributions of source code must retain the above copyright
      9 // notice, this list of conditions and the following disclaimer.
     10 //     * Redistributions in binary form must reproduce the above
     11 // copyright notice, this list of conditions and the following disclaimer
     12 // in the documentation and/or other materials provided with the
     13 // distribution.
     14 //     * Neither the name of Google Inc. nor the names of its
     15 // contributors may be used to endorse or promote products derived from
     16 // this software without specific prior written permission.
     17 //
     18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
     19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
     20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
     21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
     22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
     23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
     24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
     28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     29 
     30 // Utility functions and classes used by the Google C++ testing framework.
     31 //
     32 // Author: wan (at) google.com (Zhanyong Wan)
     33 //
     34 // This file contains purely Google Test's internal implementation.  Please
     35 // DO NOT #INCLUDE IT IN A USER PROGRAM.
     36 
     37 #ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_
     38 #define GTEST_SRC_GTEST_INTERNAL_INL_H_
     39 
     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
     47 
     48 #include <stddef.h>
     49 
     50 #include <gtest/internal/gtest-port.h>
     51 
     52 #ifdef GTEST_OS_WINDOWS
     53 #include <windows.h>  // NOLINT
     54 #endif  // GTEST_OS_WINDOWS
     55 
     56 #include <ostream>  // NOLINT
     57 #include <gtest/gtest.h>
     58 #include <gtest/gtest-spi.h>
     59 
     60 namespace testing {
     61 
     62 // Declares the flags.
     63 //
     64 // We don't want the users to modify these flags in the code, but want
     65 // Google Test's own unit tests to be able to access them.  Therefore we
     66 // declare them here as opposed to in gtest.h.
     67 GTEST_DECLARE_bool(break_on_failure);
     68 GTEST_DECLARE_bool(catch_exceptions);
     69 GTEST_DECLARE_string(color);
     70 GTEST_DECLARE_string(filter);
     71 GTEST_DECLARE_bool(list_tests);
     72 GTEST_DECLARE_string(output);
     73 GTEST_DECLARE_int32(repeat);
     74 GTEST_DECLARE_int32(stack_trace_depth);
     75 GTEST_DECLARE_bool(show_internal_stack_frames);
     76 
     77 namespace internal {
     78 
     79 // Names of the flags (needed for parsing Google Test flags).
     80 const char kBreakOnFailureFlag[] = "break_on_failure";
     81 const char kCatchExceptionsFlag[] = "catch_exceptions";
     82 const char kFilterFlag[] = "filter";
     83 const char kListTestsFlag[] = "list_tests";
     84 const char kOutputFlag[] = "output";
     85 const char kColorFlag[] = "color";
     86 const char kRepeatFlag[] = "repeat";
     87 
     88 // This class saves the values of all Google Test flags in its c'tor, and
     89 // restores them in its d'tor.
     90 class GTestFlagSaver {
     91  public:
     92   // The c'tor.
     93   GTestFlagSaver() {
     94     break_on_failure_ = GTEST_FLAG(break_on_failure);
     95     catch_exceptions_ = GTEST_FLAG(catch_exceptions);
     96     color_ = GTEST_FLAG(color);
     97     death_test_style_ = GTEST_FLAG(death_test_style);
     98     filter_ = GTEST_FLAG(filter);
     99     internal_run_death_test_ = GTEST_FLAG(internal_run_death_test);
    100     list_tests_ = GTEST_FLAG(list_tests);
    101     output_ = GTEST_FLAG(output);
    102     repeat_ = GTEST_FLAG(repeat);
    103   }
    104 
    105   // The d'tor is not virtual.  DO NOT INHERIT FROM THIS CLASS.
    106   ~GTestFlagSaver() {
    107     GTEST_FLAG(break_on_failure) = break_on_failure_;
    108     GTEST_FLAG(catch_exceptions) = catch_exceptions_;
    109     GTEST_FLAG(color) = color_;
    110     GTEST_FLAG(death_test_style) = death_test_style_;
    111     GTEST_FLAG(filter) = filter_;
    112     GTEST_FLAG(internal_run_death_test) = internal_run_death_test_;
    113     GTEST_FLAG(list_tests) = list_tests_;
    114     GTEST_FLAG(output) = output_;
    115     GTEST_FLAG(repeat) = repeat_;
    116   }
    117  private:
    118   // Fields for saving the original values of flags.
    119   bool break_on_failure_;
    120   bool catch_exceptions_;
    121   String color_;
    122   String death_test_style_;
    123   String filter_;
    124   String internal_run_death_test_;
    125   bool list_tests_;
    126   String output_;
    127   bool pretty_;
    128   internal::Int32 repeat_;
    129 } GTEST_ATTRIBUTE_UNUSED;
    130 
    131 // Converts a Unicode code-point to its UTF-8 encoding.
    132 String ToUtf8String(wchar_t wchar);
    133 
    134 // Returns the number of active threads, or 0 when there is an error.
    135 size_t GetThreadCount();
    136 
    137 // List is a simple singly-linked list container.
    138 //
    139 // We cannot use std::list as Microsoft's implementation of STL has
    140 // problems when exception is disabled.  There is a hack to work
    141 // around this, but we've seen cases where the hack fails to work.
    142 //
    143 // TODO(wan): switch to std::list when we have a reliable fix for the
    144 // STL problem, e.g. when we upgrade to the next version of Visual
    145 // C++, or (more likely) switch to STLport.
    146 //
    147 // The element type must support copy constructor.
    148 
    149 // Forward declare List
    150 template <typename E>  // E is the element type.
    151 class List;
    152 
    153 // ListNode is a node in a singly-linked list.  It consists of an
    154 // element and a pointer to the next node.  The last node in the list
    155 // has a NULL value for its next pointer.
    156 template <typename E>  // E is the element type.
    157 class ListNode {
    158   friend class List<E>;
    159 
    160  private:
    161 
    162   E element_;
    163   ListNode * next_;
    164 
    165   // The c'tor is private s.t. only in the ListNode class and in its
    166   // friend class List we can create a ListNode object.
    167   //
    168   // Creates a node with a given element value.  The next pointer is
    169   // set to NULL.
    170   //
    171   // ListNode does NOT have a default constructor.  Always use this
    172   // constructor (with parameter) to create a ListNode object.
    173   explicit ListNode(const E & element) : element_(element), next_(NULL) {}
    174 
    175   // We disallow copying ListNode
    176   GTEST_DISALLOW_COPY_AND_ASSIGN(ListNode);
    177 
    178  public:
    179 
    180   // Gets the element in this node.
    181   E & element() { return element_; }
    182   const E & element() const { return element_; }
    183 
    184   // Gets the next node in the list.
    185   ListNode * next() { return next_; }
    186   const ListNode * next() const { return next_; }
    187 };
    188 
    189 
    190 // List is a simple singly-linked list container.
    191 template <typename E>  // E is the element type.
    192 class List {
    193  public:
    194 
    195   // Creates an empty list.
    196   List() : head_(NULL), last_(NULL), size_(0) {}
    197 
    198   // D'tor.
    199   virtual ~List();
    200 
    201   // Clears the list.
    202   void Clear() {
    203     if ( size_ > 0 ) {
    204       // 1. Deletes every node.
    205       ListNode<E> * node = head_;
    206       ListNode<E> * next = node->next();
    207       for ( ; ; ) {
    208         delete node;
    209         node = next;
    210         if ( node == NULL ) break;
    211         next = node->next();
    212       }
    213 
    214       // 2. Resets the member variables.
    215       head_ = last_ = NULL;
    216       size_ = 0;
    217     }
    218   }
    219 
    220   // Gets the number of elements.
    221   int size() const { return size_; }
    222 
    223   // Returns true if the list is empty.
    224   bool IsEmpty() const { return size() == 0; }
    225 
    226   // Gets the first element of the list, or NULL if the list is empty.
    227   ListNode<E> * Head() { return head_; }
    228   const ListNode<E> * Head() const { return head_; }
    229 
    230   // Gets the last element of the list, or NULL if the list is empty.
    231   ListNode<E> * Last() { return last_; }
    232   const ListNode<E> * Last() const { return last_; }
    233 
    234   // Adds an element to the end of the list.  A copy of the element is
    235   // created using the copy constructor, and then stored in the list.
    236   // Changes made to the element in the list doesn't affect the source
    237   // object, and vice versa.
    238   void PushBack(const E & element) {
    239     ListNode<E> * new_node = new ListNode<E>(element);
    240 
    241     if ( size_ == 0 ) {
    242       head_ = last_ = new_node;
    243       size_ = 1;
    244     } else {
    245       last_->next_ = new_node;
    246       last_ = new_node;
    247       size_++;
    248     }
    249   }
    250 
    251   // Adds an element to the beginning of this list.
    252   void PushFront(const E& element) {
    253     ListNode<E>* const new_node = new ListNode<E>(element);
    254 
    255     if ( size_ == 0 ) {
    256       head_ = last_ = new_node;
    257       size_ = 1;
    258     } else {
    259       new_node->next_ = head_;
    260       head_ = new_node;
    261       size_++;
    262     }
    263   }
    264 
    265   // Removes an element from the beginning of this list.  If the
    266   // result argument is not NULL, the removed element is stored in the
    267   // memory it points to.  Otherwise the element is thrown away.
    268   // Returns true iff the list wasn't empty before the operation.
    269   bool PopFront(E* result) {
    270     if (size_ == 0) return false;
    271 
    272     if (result != NULL) {
    273       *result = head_->element_;
    274     }
    275 
    276     ListNode<E>* const old_head = head_;
    277     size_--;
    278     if (size_ == 0) {
    279       head_ = last_ = NULL;
    280     } else {
    281       head_ = head_->next_;
    282     }
    283     delete old_head;
    284 
    285     return true;
    286   }
    287 
    288   // Inserts an element after a given node in the list.  It's the
    289   // caller's responsibility to ensure that the given node is in the
    290   // list.  If the given node is NULL, inserts the element at the
    291   // front of the list.
    292   ListNode<E>* InsertAfter(ListNode<E>* node, const E& element) {
    293     if (node == NULL) {
    294       PushFront(element);
    295       return Head();
    296     }
    297 
    298     ListNode<E>* const new_node = new ListNode<E>(element);
    299     new_node->next_ = node->next_;
    300     node->next_ = new_node;
    301     size_++;
    302     if (node == last_) {
    303       last_ = new_node;
    304     }
    305 
    306     return new_node;
    307   }
    308 
    309   // Returns the number of elements that satisfy a given predicate.
    310   // The parameter 'predicate' is a Boolean function or functor that
    311   // accepts a 'const E &', where E is the element type.
    312   template <typename P>  // P is the type of the predicate function/functor
    313   int CountIf(P predicate) const {
    314     int count = 0;
    315     for ( const ListNode<E> * node = Head();
    316           node != NULL;
    317           node = node->next() ) {
    318       if ( predicate(node->element()) ) {
    319         count++;
    320       }
    321     }
    322 
    323     return count;
    324   }
    325 
    326   // Applies a function/functor to each element in the list.  The
    327   // parameter 'functor' is a function/functor that accepts a 'const
    328   // E &', where E is the element type.  This method does not change
    329   // the elements.
    330   template <typename F>  // F is the type of the function/functor
    331   void ForEach(F functor) const {
    332     for ( const ListNode<E> * node = Head();
    333           node != NULL;
    334           node = node->next() ) {
    335       functor(node->element());
    336     }
    337   }
    338 
    339   // Returns the first node whose element satisfies a given predicate,
    340   // or NULL if none is found.  The parameter 'predicate' is a
    341   // function/functor that accepts a 'const E &', where E is the
    342   // element type.  This method does not change the elements.
    343   template <typename P>  // P is the type of the predicate function/functor.
    344   const ListNode<E> * FindIf(P predicate) const {
    345     for ( const ListNode<E> * node = Head();
    346           node != NULL;
    347           node = node->next() ) {
    348       if ( predicate(node->element()) ) {
    349         return node;
    350       }
    351     }
    352 
    353     return NULL;
    354   }
    355 
    356   template <typename P>
    357   ListNode<E> * FindIf(P predicate) {
    358     for ( ListNode<E> * node = Head();
    359           node != NULL;
    360           node = node->next() ) {
    361       if ( predicate(node->element() ) ) {
    362         return node;
    363       }
    364     }
    365 
    366     return NULL;
    367   }
    368 
    369  private:
    370   ListNode<E>* head_;  // The first node of the list.
    371   ListNode<E>* last_;  // The last node of the list.
    372   int size_;           // The number of elements in the list.
    373 
    374   // We disallow copying List.
    375   GTEST_DISALLOW_COPY_AND_ASSIGN(List);
    376 };
    377 
    378 // The virtual destructor of List.
    379 template <typename E>
    380 List<E>::~List() {
    381   Clear();
    382 }
    383 
    384 // A function for deleting an object.  Handy for being used as a
    385 // functor.
    386 template <typename T>
    387 static void Delete(T * x) {
    388   delete x;
    389 }
    390 
    391 // A copyable object representing a user specified test property which can be
    392 // output as a key/value string pair.
    393 //
    394 // Don't inherit from TestProperty as its destructor is not virtual.
    395 class TestProperty {
    396  public:
    397   // C'tor.  TestProperty does NOT have a default constructor.
    398   // Always use this constructor (with parameters) to create a
    399   // TestProperty object.
    400   TestProperty(const char* key, const char* value) :
    401     key_(key), value_(value) {
    402   }
    403 
    404   // Gets the user supplied key.
    405   const char* key() const {
    406     return key_.c_str();
    407   }
    408 
    409   // Gets the user supplied value.
    410   const char* value() const {
    411     return value_.c_str();
    412   }
    413 
    414   // Sets a new value, overriding the one supplied in the constructor.
    415   void SetValue(const char* new_value) {
    416     value_ = new_value;
    417   }
    418 
    419  private:
    420   // The key supplied by the user.
    421   String key_;
    422   // The value supplied by the user.
    423   String value_;
    424 };
    425 
    426 // A predicate that checks the key of a TestProperty against a known key.
    427 //
    428 // TestPropertyKeyIs is copyable.
    429 class TestPropertyKeyIs {
    430  public:
    431   // Constructor.
    432   //
    433   // TestPropertyKeyIs has NO default constructor.
    434   explicit TestPropertyKeyIs(const char* key)
    435       : key_(key) {}
    436 
    437   // Returns true iff the test name of test property matches on key_.
    438   bool operator()(const TestProperty& test_property) const {
    439     return String(test_property.key()).Compare(key_) == 0;
    440   }
    441 
    442  private:
    443   String key_;
    444 };
    445 
    446 // The result of a single Test.  This includes a list of
    447 // TestPartResults, a list of TestProperties, a count of how many
    448 // death tests there are in the Test, and how much time it took to run
    449 // the Test.
    450 //
    451 // TestResult is not copyable.
    452 class TestResult {
    453  public:
    454   // Creates an empty TestResult.
    455   TestResult();
    456 
    457   // D'tor.  Do not inherit from TestResult.
    458   ~TestResult();
    459 
    460   // Gets the list of TestPartResults.
    461   const internal::List<TestPartResult> & test_part_results() const {
    462     return test_part_results_;
    463   }
    464 
    465   // Gets the list of TestProperties.
    466   const internal::List<internal::TestProperty> & test_properties() const {
    467     return test_properties_;
    468   }
    469 
    470   // Gets the number of successful test parts.
    471   int successful_part_count() const;
    472 
    473   // Gets the number of failed test parts.
    474   int failed_part_count() const;
    475 
    476   // Gets the number of all test parts.  This is the sum of the number
    477   // of successful test parts and the number of failed test parts.
    478   int total_part_count() const;
    479 
    480   // Returns true iff the test passed (i.e. no test part failed).
    481   bool Passed() const { return !Failed(); }
    482 
    483   // Returns true iff the test failed.
    484   bool Failed() const { return failed_part_count() > 0; }
    485 
    486   // Returns true iff the test fatally failed.
    487   bool HasFatalFailure() const;
    488 
    489   // Returns the elapsed time, in milliseconds.
    490   TimeInMillis elapsed_time() const { return elapsed_time_; }
    491 
    492   // Sets the elapsed time.
    493   void set_elapsed_time(TimeInMillis elapsed) { elapsed_time_ = elapsed; }
    494 
    495   // Adds a test part result to the list.
    496   void AddTestPartResult(const TestPartResult& test_part_result);
    497 
    498   // Adds a test property to the list. The property is validated and may add
    499   // a non-fatal failure if invalid (e.g., if it conflicts with reserved
    500   // key names). If a property is already recorded for the same key, the
    501   // value will be updated, rather than storing multiple values for the same
    502   // key.
    503   void RecordProperty(const internal::TestProperty& test_property);
    504 
    505   // Adds a failure if the key is a reserved attribute of Google Test
    506   // testcase tags.  Returns true if the property is valid.
    507   // TODO(russr): Validate attribute names are legal and human readable.
    508   static bool ValidateTestProperty(const internal::TestProperty& test_property);
    509 
    510   // Returns the death test count.
    511   int death_test_count() const { return death_test_count_; }
    512 
    513   // Increments the death test count, returning the new count.
    514   int increment_death_test_count() { return ++death_test_count_; }
    515 
    516   // Clears the object.
    517   void Clear();
    518  private:
    519   // Protects mutable state of the property list and of owned properties, whose
    520   // values may be updated.
    521   internal::Mutex test_properites_mutex_;
    522 
    523   // The list of TestPartResults
    524   internal::List<TestPartResult> test_part_results_;
    525   // The list of TestProperties
    526   internal::List<internal::TestProperty> test_properties_;
    527   // Running count of death tests.
    528   int death_test_count_;
    529   // The elapsed time, in milliseconds.
    530   TimeInMillis elapsed_time_;
    531 
    532   // We disallow copying TestResult.
    533   GTEST_DISALLOW_COPY_AND_ASSIGN(TestResult);
    534 };  // class TestResult
    535 
    536 class TestInfoImpl {
    537  public:
    538   TestInfoImpl(TestInfo* parent, const char* test_case_name,
    539                const char* name, TypeId fixture_class_id,
    540                TestMaker maker);
    541   ~TestInfoImpl();
    542 
    543   // Returns true if this test should run.
    544   bool should_run() const { return should_run_; }
    545 
    546   // Sets the should_run member.
    547   void set_should_run(bool should) { should_run_ = should; }
    548 
    549   // Returns true if this test is disabled. Disabled tests are not run.
    550   bool is_disabled() const { return is_disabled_; }
    551 
    552   // Sets the is_disabled member.
    553   void set_is_disabled(bool is) { is_disabled_ = is; }
    554 
    555   // Returns the test case name.
    556   const char* test_case_name() const { return test_case_name_.c_str(); }
    557 
    558   // Returns the test name.
    559   const char* name() const { return name_.c_str(); }
    560 
    561   // Returns the ID of the test fixture class.
    562   TypeId fixture_class_id() const { return fixture_class_id_; }
    563 
    564   // Returns the test result.
    565   internal::TestResult* result() { return &result_; }
    566   const internal::TestResult* result() const { return &result_; }
    567 
    568   // Creates the test object, runs it, records its result, and then
    569   // deletes it.
    570   void Run();
    571 
    572   // Calls the given TestInfo object's Run() method.
    573   static void RunTest(TestInfo * test_info) {
    574     test_info->impl()->Run();
    575   }
    576 
    577   // Clears the test result.
    578   void ClearResult() { result_.Clear(); }
    579 
    580   // Clears the test result in the given TestInfo object.
    581   static void ClearTestResult(TestInfo * test_info) {
    582     test_info->impl()->ClearResult();
    583   }
    584 
    585  private:
    586   // These fields are immutable properties of the test.
    587   TestInfo* const parent_;         // The owner of this object
    588   const String test_case_name_;    // Test case name
    589   const String name_;              // Test name
    590   const TypeId fixture_class_id_;  // ID of the test fixture class
    591   bool should_run_;                // True iff this test should run
    592   bool is_disabled_;               // True iff this test is disabled
    593   const TestMaker maker_;          // The function that creates the test object
    594 
    595   // This field is mutable and needs to be reset before running the
    596   // test for the second time.
    597   internal::TestResult result_;
    598 
    599   GTEST_DISALLOW_COPY_AND_ASSIGN(TestInfoImpl);
    600 };
    601 
    602 }  // namespace internal
    603 
    604 // A test case, which consists of a list of TestInfos.
    605 //
    606 // TestCase is not copyable.
    607 class TestCase {
    608  public:
    609   // Creates a TestCase with the given name.
    610   //
    611   // TestCase does NOT have a default constructor.  Always use this
    612   // constructor to create a TestCase object.
    613   //
    614   // Arguments:
    615   //
    616   //   name:         name of the test case
    617   //   set_up_tc:    pointer to the function that sets up the test case
    618   //   tear_down_tc: pointer to the function that tears down the test case
    619   TestCase(const char* name,
    620            Test::SetUpTestCaseFunc set_up_tc,
    621            Test::TearDownTestCaseFunc tear_down_tc);
    622 
    623   // Destructor of TestCase.
    624   virtual ~TestCase();
    625 
    626   // Gets the name of the TestCase.
    627   const char* name() const { return name_.c_str(); }
    628 
    629   // Returns true if any test in this test case should run.
    630   bool should_run() const { return should_run_; }
    631 
    632   // Sets the should_run member.
    633   void set_should_run(bool should) { should_run_ = should; }
    634 
    635   // Gets the (mutable) list of TestInfos in this TestCase.
    636   internal::List<TestInfo*>& test_info_list() { return *test_info_list_; }
    637 
    638   // Gets the (immutable) list of TestInfos in this TestCase.
    639   const internal::List<TestInfo *> & test_info_list() const {
    640     return *test_info_list_;
    641   }
    642 
    643   // Gets the number of successful tests in this test case.
    644   int successful_test_count() const;
    645 
    646   // Gets the number of failed tests in this test case.
    647   int failed_test_count() const;
    648 
    649   // Gets the number of disabled tests in this test case.
    650   int disabled_test_count() const;
    651 
    652   // Get the number of tests in this test case that should run.
    653   int test_to_run_count() const;
    654 
    655   // Gets the number of all tests in this test case.
    656   int total_test_count() const;
    657 
    658   // Returns true iff the test case passed.
    659   bool Passed() const { return !Failed(); }
    660 
    661   // Returns true iff the test case failed.
    662   bool Failed() const { return failed_test_count() > 0; }
    663 
    664   // Returns the elapsed time, in milliseconds.
    665   internal::TimeInMillis elapsed_time() const { return elapsed_time_; }
    666 
    667   // Adds a TestInfo to this test case.  Will delete the TestInfo upon
    668   // destruction of the TestCase object.
    669   void AddTestInfo(TestInfo * test_info);
    670 
    671   // Finds and returns a TestInfo with the given name.  If one doesn't
    672   // exist, returns NULL.
    673   TestInfo* GetTestInfo(const char* test_name);
    674 
    675   // Clears the results of all tests in this test case.
    676   void ClearResult();
    677 
    678   // Clears the results of all tests in the given test case.
    679   static void ClearTestCaseResult(TestCase* test_case) {
    680     test_case->ClearResult();
    681   }
    682 
    683   // Runs every test in this TestCase.
    684   void Run();
    685 
    686   // Runs every test in the given TestCase.
    687   static void RunTestCase(TestCase * test_case) { test_case->Run(); }
    688 
    689   // Returns true iff test passed.
    690   static bool TestPassed(const TestInfo * test_info) {
    691     const internal::TestInfoImpl* const impl = test_info->impl();
    692     return impl->should_run() && impl->result()->Passed();
    693   }
    694 
    695   // Returns true iff test failed.
    696   static bool TestFailed(const TestInfo * test_info) {
    697     const internal::TestInfoImpl* const impl = test_info->impl();
    698     return impl->should_run() && impl->result()->Failed();
    699   }
    700 
    701   // Returns true iff test is disabled.
    702   static bool TestDisabled(const TestInfo * test_info) {
    703     return test_info->impl()->is_disabled();
    704   }
    705 
    706   // Returns true if the given test should run.
    707   static bool ShouldRunTest(const TestInfo *test_info) {
    708     return test_info->impl()->should_run();
    709   }
    710 
    711  private:
    712   // Name of the test case.
    713   internal::String name_;
    714   // List of TestInfos.
    715   internal::List<TestInfo*>* test_info_list_;
    716   // Pointer to the function that sets up the test case.
    717   Test::SetUpTestCaseFunc set_up_tc_;
    718   // Pointer to the function that tears down the test case.
    719   Test::TearDownTestCaseFunc tear_down_tc_;
    720   // True iff any test in this test case should run.
    721   bool should_run_;
    722   // Elapsed time, in milliseconds.
    723   internal::TimeInMillis elapsed_time_;
    724 
    725   // We disallow copying TestCases.
    726   GTEST_DISALLOW_COPY_AND_ASSIGN(TestCase);
    727 };
    728 
    729 namespace internal {
    730 
    731 // Class UnitTestOptions.
    732 //
    733 // This class contains functions for processing options the user
    734 // specifies when running the tests.  It has only static members.
    735 //
    736 // In most cases, the user can specify an option using either an
    737 // environment variable or a command line flag.  E.g. you can set the
    738 // test filter using either GTEST_FILTER or --gtest_filter.  If both
    739 // the variable and the flag are present, the latter overrides the
    740 // former.
    741 class UnitTestOptions {
    742  public:
    743   // Functions for processing the gtest_output flag.
    744 
    745   // Returns the output format, or "" for normal printed output.
    746   static String GetOutputFormat();
    747 
    748   // Returns the name of the requested output file, or the default if none
    749   // was explicitly specified.
    750   static String GetOutputFile();
    751 
    752   // Functions for processing the gtest_filter flag.
    753 
    754   // Returns true iff the wildcard pattern matches the string.  The
    755   // first ':' or '\0' character in pattern marks the end of it.
    756   //
    757   // This recursive algorithm isn't very efficient, but is clear and
    758   // works well enough for matching test names, which are short.
    759   static bool PatternMatchesString(const char *pattern, const char *str);
    760 
    761   // Returns true iff the user-specified filter matches the test case
    762   // name and the test name.
    763   static bool FilterMatchesTest(const String &test_case_name,
    764                                 const String &test_name);
    765 
    766 #ifdef GTEST_OS_WINDOWS
    767   // Function for supporting the gtest_catch_exception flag.
    768 
    769   // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
    770   // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
    771   // This function is useful as an __except condition.
    772   static int GTestShouldProcessSEH(DWORD exception_code);
    773 #endif  // GTEST_OS_WINDOWS
    774  private:
    775   // Returns true if "name" matches the ':' separated list of glob-style
    776   // filters in "filter".
    777   static bool MatchesFilter(const String& name, const char* filter);
    778 };
    779 
    780 // Returns the current application's name, removing directory path if that
    781 // is present.  Used by UnitTestOptions::GetOutputFile.
    782 FilePath GetCurrentExecutableName();
    783 
    784 // The role interface for getting the OS stack trace as a string.
    785 class OsStackTraceGetterInterface {
    786  public:
    787   OsStackTraceGetterInterface() {}
    788   virtual ~OsStackTraceGetterInterface() {}
    789 
    790   // Returns the current OS stack trace as a String.  Parameters:
    791   //
    792   //   max_depth  - the maximum number of stack frames to be included
    793   //                in the trace.
    794   //   skip_count - the number of top frames to be skipped; doesn't count
    795   //                against max_depth.
    796   virtual String CurrentStackTrace(int max_depth, int skip_count) = 0;
    797 
    798   // UponLeavingGTest() should be called immediately before Google Test calls
    799   // user code. It saves some information about the current stack that
    800   // CurrentStackTrace() will use to find and hide Google Test stack frames.
    801   virtual void UponLeavingGTest() = 0;
    802 
    803  private:
    804   GTEST_DISALLOW_COPY_AND_ASSIGN(OsStackTraceGetterInterface);
    805 };
    806 
    807 // A working implemenation of the OsStackTraceGetterInterface interface.
    808 class OsStackTraceGetter : public OsStackTraceGetterInterface {
    809  public:
    810   OsStackTraceGetter() {}
    811   virtual String CurrentStackTrace(int max_depth, int skip_count);
    812   virtual void UponLeavingGTest();
    813 
    814   // This string is inserted in place of stack frames that are part of
    815   // Google Test's implementation.
    816   static const char* const kElidedFramesMarker;
    817 
    818  private:
    819   Mutex mutex_;  // protects all internal state
    820 
    821   // We save the stack frame below the frame that calls user code.
    822   // We do this because the address of the frame immediately below
    823   // the user code changes between the call to UponLeavingGTest()
    824   // and any calls to CurrentStackTrace() from within the user code.
    825   void* caller_frame_;
    826 
    827   GTEST_DISALLOW_COPY_AND_ASSIGN(OsStackTraceGetter);
    828 };
    829 
    830 // Information about a Google Test trace point.
    831 struct TraceInfo {
    832   const char* file;
    833   int line;
    834   String message;
    835 };
    836 
    837 // The private implementation of the UnitTest class.  We don't protect
    838 // the methods under a mutex, as this class is not accessible by a
    839 // user and the UnitTest class that delegates work to this class does
    840 // proper locking.
    841 class UnitTestImpl : public TestPartResultReporterInterface {
    842  public:
    843   explicit UnitTestImpl(UnitTest* parent);
    844   virtual ~UnitTestImpl();
    845 
    846   // Reports a test part result.  This method is from the
    847   // TestPartResultReporterInterface interface.
    848   virtual void ReportTestPartResult(const TestPartResult& result);
    849 
    850   // Returns the current test part result reporter.
    851   TestPartResultReporterInterface* test_part_result_reporter();
    852 
    853   // Sets the current test part result reporter.
    854   void set_test_part_result_reporter(TestPartResultReporterInterface* reporter);
    855 
    856   // Gets the number of successful test cases.
    857   int successful_test_case_count() const;
    858 
    859   // Gets the number of failed test cases.
    860   int failed_test_case_count() const;
    861 
    862   // Gets the number of all test cases.
    863   int total_test_case_count() const;
    864 
    865   // Gets the number of all test cases that contain at least one test
    866   // that should run.
    867   int test_case_to_run_count() const;
    868 
    869   // Gets the number of successful tests.
    870   int successful_test_count() const;
    871 
    872   // Gets the number of failed tests.
    873   int failed_test_count() const;
    874 
    875   // Gets the number of disabled tests.
    876   int disabled_test_count() const;
    877 
    878   // Gets the number of all tests.
    879   int total_test_count() const;
    880 
    881   // Gets the number of tests that should run.
    882   int test_to_run_count() const;
    883 
    884   // Gets the elapsed time, in milliseconds.
    885   TimeInMillis elapsed_time() const { return elapsed_time_; }
    886 
    887   // Returns true iff the unit test passed (i.e. all test cases passed).
    888   bool Passed() const { return !Failed(); }
    889 
    890   // Returns true iff the unit test failed (i.e. some test case failed
    891   // or something outside of all tests failed).
    892   bool Failed() const {
    893     return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed();
    894   }
    895 
    896   // Returns the TestResult for the test that's currently running, or
    897   // the TestResult for the ad hoc test if no test is running.
    898   internal::TestResult* current_test_result();
    899 
    900   // Returns the TestResult for the ad hoc test.
    901   const internal::TestResult* ad_hoc_test_result() const {
    902     return &ad_hoc_test_result_;
    903   }
    904 
    905   // Sets the unit test result printer.
    906   //
    907   // Does nothing if the input and the current printer object are the
    908   // same; otherwise, deletes the old printer object and makes the
    909   // input the current printer.
    910   void set_result_printer(UnitTestEventListenerInterface * result_printer);
    911 
    912   // Returns the current unit test result printer if it is not NULL;
    913   // otherwise, creates an appropriate result printer, makes it the
    914   // current printer, and returns it.
    915   UnitTestEventListenerInterface* result_printer();
    916 
    917   // Sets the OS stack trace getter.
    918   //
    919   // Does nothing if the input and the current OS stack trace getter
    920   // are the same; otherwise, deletes the old getter and makes the
    921   // input the current getter.
    922   void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter);
    923 
    924   // Returns the current OS stack trace getter if it is not NULL;
    925   // otherwise, creates an OsStackTraceGetter, makes it the current
    926   // getter, and returns it.
    927   OsStackTraceGetterInterface* os_stack_trace_getter();
    928 
    929   // Returns the current OS stack trace as a String.
    930   //
    931   // The maximum number of stack frames to be included is specified by
    932   // the gtest_stack_trace_depth flag.  The skip_count parameter
    933   // specifies the number of top frames to be skipped, which doesn't
    934   // count against the number of frames to be included.
    935   //
    936   // For example, if Foo() calls Bar(), which in turn calls
    937   // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
    938   // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
    939   String CurrentOsStackTraceExceptTop(int skip_count);
    940 
    941   // Finds and returns a TestCase with the given name.  If one doesn't
    942   // exist, creates one and returns it.
    943   //
    944   // Arguments:
    945   //
    946   //   test_case_name: name of the test case
    947   //   set_up_tc:      pointer to the function that sets up the test case
    948   //   tear_down_tc:   pointer to the function that tears down the test case
    949   TestCase* GetTestCase(const char* test_case_name,
    950                         Test::SetUpTestCaseFunc set_up_tc,
    951                         Test::TearDownTestCaseFunc tear_down_tc);
    952 
    953   // Adds a TestInfo to the unit test.
    954   //
    955   // Arguments:
    956   //
    957   //   set_up_tc:    pointer to the function that sets up the test case
    958   //   tear_down_tc: pointer to the function that tears down the test case
    959   //   test_info:    the TestInfo object
    960   void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc,
    961                    Test::TearDownTestCaseFunc tear_down_tc,
    962                    TestInfo * test_info) {
    963     GetTestCase(test_info->test_case_name(),
    964                 set_up_tc,
    965                 tear_down_tc)->AddTestInfo(test_info);
    966   }
    967 
    968   // Sets the TestCase object for the test that's currently running.
    969   void set_current_test_case(TestCase* current_test_case) {
    970     current_test_case_ = current_test_case;
    971   }
    972 
    973   // Sets the TestInfo object for the test that's currently running.  If
    974   // current_test_info is NULL, the assertion results will be stored in
    975   // ad_hoc_test_result_.
    976   void set_current_test_info(TestInfo* current_test_info) {
    977     current_test_info_ = current_test_info;
    978   }
    979 
    980   // Runs all tests in this UnitTest object, prints the result, and
    981   // returns 0 if all tests are successful, or 1 otherwise.  If any
    982   // exception is thrown during a test on Windows, this test is
    983   // considered to be failed, but the rest of the tests will still be
    984   // run.  (We disable exceptions on Linux and Mac OS X, so the issue
    985   // doesn't apply there.)
    986   int RunAllTests();
    987 
    988   // Clears the results of all tests, including the ad hoc test.
    989   void ClearResult() {
    990     test_cases_.ForEach(TestCase::ClearTestCaseResult);
    991     ad_hoc_test_result_.Clear();
    992   }
    993 
    994   // Matches the full name of each test against the user-specified
    995   // filter to decide whether the test should run, then records the
    996   // result in each TestCase and TestInfo object.
    997   // Returns the number of tests that should run.
    998   int FilterTests();
    999 
   1000   // Lists all the tests by name.
   1001   void ListAllTests();
   1002 
   1003   const TestCase* current_test_case() const { return current_test_case_; }
   1004   TestInfo* current_test_info() { return current_test_info_; }
   1005   const TestInfo* current_test_info() const { return current_test_info_; }
   1006 
   1007   // Returns the list of environments that need to be set-up/torn-down
   1008   // before/after the tests are run.
   1009   internal::List<Environment*>* environments() { return &environments_; }
   1010   internal::List<Environment*>* environments_in_reverse_order() {
   1011     return &environments_in_reverse_order_;
   1012   }
   1013 
   1014   internal::List<TestCase*>* test_cases() { return &test_cases_; }
   1015   const internal::List<TestCase*>* test_cases() const { return &test_cases_; }
   1016 
   1017   // Getters for the per-thread Google Test trace stack.
   1018   internal::List<TraceInfo>* gtest_trace_stack() {
   1019     return gtest_trace_stack_.pointer();
   1020   }
   1021   const internal::List<TraceInfo>* gtest_trace_stack() const {
   1022     return gtest_trace_stack_.pointer();
   1023   }
   1024 
   1025 #ifdef GTEST_HAS_DEATH_TEST
   1026   // Returns a pointer to the parsed --gtest_internal_run_death_test
   1027   // flag, or NULL if that flag was not specified.
   1028   // This information is useful only in a death test child process.
   1029   const InternalRunDeathTestFlag* internal_run_death_test_flag() const {
   1030     return internal_run_death_test_flag_.get();
   1031   }
   1032 
   1033   // Returns a pointer to the current death test factory.
   1034   internal::DeathTestFactory* death_test_factory() {
   1035     return death_test_factory_.get();
   1036   }
   1037 
   1038   friend class ReplaceDeathTestFactory;
   1039 #endif  // GTEST_HAS_DEATH_TEST
   1040 
   1041  private:
   1042   // The UnitTest object that owns this implementation object.
   1043   UnitTest* const parent_;
   1044 
   1045   // Points to (but doesn't own) the test part result reporter.
   1046   TestPartResultReporterInterface* test_part_result_reporter_;
   1047 
   1048   // The list of environments that need to be set-up/torn-down
   1049   // before/after the tests are run.  environments_in_reverse_order_
   1050   // simply mirrors environments_ in reverse order.
   1051   internal::List<Environment*> environments_;
   1052   internal::List<Environment*> environments_in_reverse_order_;
   1053 
   1054   internal::List<TestCase*> test_cases_;  // The list of TestCases.
   1055 
   1056   // Points to the last death test case registered.  Initially NULL.
   1057   internal::ListNode<TestCase*>* last_death_test_case_;
   1058 
   1059   // This points to the TestCase for the currently running test.  It
   1060   // changes as Google Test goes through one test case after another.
   1061   // When no test is running, this is set to NULL and Google Test
   1062   // stores assertion results in ad_hoc_test_result_.  Initally NULL.
   1063   TestCase* current_test_case_;
   1064 
   1065   // This points to the TestInfo for the currently running test.  It
   1066   // changes as Google Test goes through one test after another.  When
   1067   // no test is running, this is set to NULL and Google Test stores
   1068   // assertion results in ad_hoc_test_result_.  Initially NULL.
   1069   TestInfo* current_test_info_;
   1070 
   1071   // Normally, a user only writes assertions inside a TEST or TEST_F,
   1072   // or inside a function called by a TEST or TEST_F.  Since Google
   1073   // Test keeps track of which test is current running, it can
   1074   // associate such an assertion with the test it belongs to.
   1075   //
   1076   // If an assertion is encountered when no TEST or TEST_F is running,
   1077   // Google Test attributes the assertion result to an imaginary "ad hoc"
   1078   // test, and records the result in ad_hoc_test_result_.
   1079   internal::TestResult ad_hoc_test_result_;
   1080 
   1081   // The unit test result printer.  Will be deleted when the UnitTest
   1082   // object is destructed.  By default, a plain text printer is used,
   1083   // but the user can set this field to use a custom printer if that
   1084   // is desired.
   1085   UnitTestEventListenerInterface* result_printer_;
   1086 
   1087   // The OS stack trace getter.  Will be deleted when the UnitTest
   1088   // object is destructed.  By default, an OsStackTraceGetter is used,
   1089   // but the user can set this field to use a custom getter if that is
   1090   // desired.
   1091   OsStackTraceGetterInterface* os_stack_trace_getter_;
   1092 
   1093   // How long the test took to run, in milliseconds.
   1094   TimeInMillis elapsed_time_;
   1095 
   1096 #ifdef GTEST_HAS_DEATH_TEST
   1097   // The decomposed components of the gtest_internal_run_death_test flag,
   1098   // parsed when RUN_ALL_TESTS is called.
   1099   internal::scoped_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;
   1100   internal::scoped_ptr<internal::DeathTestFactory> death_test_factory_;
   1101 #endif  // GTEST_HAS_DEATH_TEST
   1102 
   1103   // A per-thread stack of traces created by the SCOPED_TRACE() macro.
   1104   internal::ThreadLocal<internal::List<TraceInfo> > gtest_trace_stack_;
   1105 
   1106   GTEST_DISALLOW_COPY_AND_ASSIGN(UnitTestImpl);
   1107 };  // class UnitTestImpl
   1108 
   1109 // Convenience function for accessing the global UnitTest
   1110 // implementation object.
   1111 inline UnitTestImpl* GetUnitTestImpl() {
   1112   return UnitTest::GetInstance()->impl();
   1113 }
   1114 
   1115 }  // namespace internal
   1116 }  // namespace testing
   1117 
   1118 #endif  // GTEST_SRC_GTEST_INTERNAL_INL_H_
   1119