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 to 1 iff the current translation unit is
     41 // part of Google Test's implementation; otherwise it's undefined.
     42 #if !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 #ifndef _WIN32_WCE
     49 # include <errno.h>
     50 #endif  // !_WIN32_WCE
     51 #include <stddef.h>
     52 #include <stdlib.h>  // For strtoll/_strtoul64/malloc/free.
     53 #include <string.h>  // For memmove.
     54 
     55 #include <algorithm>
     56 #include <string>
     57 #include <vector>
     58 
     59 #include "gtest/internal/gtest-port.h"
     60 
     61 #if GTEST_OS_WINDOWS
     62 # include <windows.h>  // NOLINT
     63 #endif  // GTEST_OS_WINDOWS
     64 
     65 #include "gtest/gtest.h"  // NOLINT
     66 #include "gtest/gtest-spi.h"
     67 
     68 namespace testing {
     69 
     70 // Declares the flags.
     71 //
     72 // We don't want the users to modify this flag in the code, but want
     73 // Google Test's own unit tests to be able to access it. Therefore we
     74 // declare it here as opposed to in gtest.h.
     75 GTEST_DECLARE_bool_(death_test_use_fork);
     76 
     77 namespace internal {
     78 
     79 // The value of GetTestTypeId() as seen from within the Google Test
     80 // library.  This is solely for testing GetTestTypeId().
     81 GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest;
     82 
     83 // Names of the flags (needed for parsing Google Test flags).
     84 const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests";
     85 const char kBreakOnFailureFlag[] = "break_on_failure";
     86 const char kCatchExceptionsFlag[] = "catch_exceptions";
     87 const char kColorFlag[] = "color";
     88 const char kFilterFlag[] = "filter";
     89 const char kListTestsFlag[] = "list_tests";
     90 const char kOutputFlag[] = "output";
     91 const char kPrintTimeFlag[] = "print_time";
     92 const char kRandomSeedFlag[] = "random_seed";
     93 const char kRepeatFlag[] = "repeat";
     94 const char kShuffleFlag[] = "shuffle";
     95 const char kStackTraceDepthFlag[] = "stack_trace_depth";
     96 const char kStreamResultToFlag[] = "stream_result_to";
     97 const char kThrowOnFailureFlag[] = "throw_on_failure";
     98 
     99 // A valid random seed must be in [1, kMaxRandomSeed].
    100 const int kMaxRandomSeed = 99999;
    101 
    102 // g_help_flag is true iff the --help flag or an equivalent form is
    103 // specified on the command line.
    104 GTEST_API_ extern bool g_help_flag;
    105 
    106 // Returns the current time in milliseconds.
    107 GTEST_API_ TimeInMillis GetTimeInMillis();
    108 
    109 // Returns true iff Google Test should use colors in the output.
    110 GTEST_API_ bool ShouldUseColor(bool stdout_is_tty);
    111 
    112 // Formats the given time in milliseconds as seconds.
    113 GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms);
    114 
    115 // Parses a string for an Int32 flag, in the form of "--flag=value".
    116 //
    117 // On success, stores the value of the flag in *value, and returns
    118 // true.  On failure, returns false without changing *value.
    119 GTEST_API_ bool ParseInt32Flag(
    120     const char* str, const char* flag, Int32* value);
    121 
    122 // Returns a random seed in range [1, kMaxRandomSeed] based on the
    123 // given --gtest_random_seed flag value.
    124 inline int GetRandomSeedFromFlag(Int32 random_seed_flag) {
    125   const unsigned int raw_seed = (random_seed_flag == 0) ?
    126       static_cast<unsigned int>(GetTimeInMillis()) :
    127       static_cast<unsigned int>(random_seed_flag);
    128 
    129   // Normalizes the actual seed to range [1, kMaxRandomSeed] such that
    130   // it's easy to type.
    131   const int normalized_seed =
    132       static_cast<int>((raw_seed - 1U) %
    133                        static_cast<unsigned int>(kMaxRandomSeed)) + 1;
    134   return normalized_seed;
    135 }
    136 
    137 // Returns the first valid random seed after 'seed'.  The behavior is
    138 // undefined if 'seed' is invalid.  The seed after kMaxRandomSeed is
    139 // considered to be 1.
    140 inline int GetNextRandomSeed(int seed) {
    141   GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed)
    142       << "Invalid random seed " << seed << " - must be in [1, "
    143       << kMaxRandomSeed << "].";
    144   const int next_seed = seed + 1;
    145   return (next_seed > kMaxRandomSeed) ? 1 : next_seed;
    146 }
    147 
    148 // This class saves the values of all Google Test flags in its c'tor, and
    149 // restores them in its d'tor.
    150 class GTestFlagSaver {
    151  public:
    152   // The c'tor.
    153   GTestFlagSaver() {
    154     also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests);
    155     break_on_failure_ = GTEST_FLAG(break_on_failure);
    156     catch_exceptions_ = GTEST_FLAG(catch_exceptions);
    157     color_ = GTEST_FLAG(color);
    158     death_test_style_ = GTEST_FLAG(death_test_style);
    159     death_test_use_fork_ = GTEST_FLAG(death_test_use_fork);
    160     filter_ = GTEST_FLAG(filter);
    161     internal_run_death_test_ = GTEST_FLAG(internal_run_death_test);
    162     list_tests_ = GTEST_FLAG(list_tests);
    163     output_ = GTEST_FLAG(output);
    164     print_time_ = GTEST_FLAG(print_time);
    165     random_seed_ = GTEST_FLAG(random_seed);
    166     repeat_ = GTEST_FLAG(repeat);
    167     shuffle_ = GTEST_FLAG(shuffle);
    168     stack_trace_depth_ = GTEST_FLAG(stack_trace_depth);
    169     stream_result_to_ = GTEST_FLAG(stream_result_to);
    170     throw_on_failure_ = GTEST_FLAG(throw_on_failure);
    171   }
    172 
    173   // The d'tor is not virtual.  DO NOT INHERIT FROM THIS CLASS.
    174   ~GTestFlagSaver() {
    175     GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_;
    176     GTEST_FLAG(break_on_failure) = break_on_failure_;
    177     GTEST_FLAG(catch_exceptions) = catch_exceptions_;
    178     GTEST_FLAG(color) = color_;
    179     GTEST_FLAG(death_test_style) = death_test_style_;
    180     GTEST_FLAG(death_test_use_fork) = death_test_use_fork_;
    181     GTEST_FLAG(filter) = filter_;
    182     GTEST_FLAG(internal_run_death_test) = internal_run_death_test_;
    183     GTEST_FLAG(list_tests) = list_tests_;
    184     GTEST_FLAG(output) = output_;
    185     GTEST_FLAG(print_time) = print_time_;
    186     GTEST_FLAG(random_seed) = random_seed_;
    187     GTEST_FLAG(repeat) = repeat_;
    188     GTEST_FLAG(shuffle) = shuffle_;
    189     GTEST_FLAG(stack_trace_depth) = stack_trace_depth_;
    190     GTEST_FLAG(stream_result_to) = stream_result_to_;
    191     GTEST_FLAG(throw_on_failure) = throw_on_failure_;
    192   }
    193  private:
    194   // Fields for saving the original values of flags.
    195   bool also_run_disabled_tests_;
    196   bool break_on_failure_;
    197   bool catch_exceptions_;
    198   String color_;
    199   String death_test_style_;
    200   bool death_test_use_fork_;
    201   String filter_;
    202   String internal_run_death_test_;
    203   bool list_tests_;
    204   String output_;
    205   bool print_time_;
    206   bool pretty_;
    207   internal::Int32 random_seed_;
    208   internal::Int32 repeat_;
    209   bool shuffle_;
    210   internal::Int32 stack_trace_depth_;
    211   String stream_result_to_;
    212   bool throw_on_failure_;
    213 } GTEST_ATTRIBUTE_UNUSED_;
    214 
    215 // Converts a Unicode code point to a narrow string in UTF-8 encoding.
    216 // code_point parameter is of type UInt32 because wchar_t may not be
    217 // wide enough to contain a code point.
    218 // The output buffer str must containt at least 32 characters.
    219 // The function returns the address of the output buffer.
    220 // If the code_point is not a valid Unicode code point
    221 // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be output
    222 // as '(Invalid Unicode 0xXXXXXXXX)'.
    223 GTEST_API_ char* CodePointToUtf8(UInt32 code_point, char* str);
    224 
    225 // Converts a wide string to a narrow string in UTF-8 encoding.
    226 // The wide string is assumed to have the following encoding:
    227 //   UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
    228 //   UTF-32 if sizeof(wchar_t) == 4 (on Linux)
    229 // Parameter str points to a null-terminated wide string.
    230 // Parameter num_chars may additionally limit the number
    231 // of wchar_t characters processed. -1 is used when the entire string
    232 // should be processed.
    233 // If the string contains code points that are not valid Unicode code points
    234 // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
    235 // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
    236 // and contains invalid UTF-16 surrogate pairs, values in those pairs
    237 // will be encoded as individual Unicode characters from Basic Normal Plane.
    238 GTEST_API_ String WideStringToUtf8(const wchar_t* str, int num_chars);
    239 
    240 // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
    241 // if the variable is present. If a file already exists at this location, this
    242 // function will write over it. If the variable is present, but the file cannot
    243 // be created, prints an error and exits.
    244 void WriteToShardStatusFileIfNeeded();
    245 
    246 // Checks whether sharding is enabled by examining the relevant
    247 // environment variable values. If the variables are present,
    248 // but inconsistent (e.g., shard_index >= total_shards), prints
    249 // an error and exits. If in_subprocess_for_death_test, sharding is
    250 // disabled because it must only be applied to the original test
    251 // process. Otherwise, we could filter out death tests we intended to execute.
    252 GTEST_API_ bool ShouldShard(const char* total_shards_str,
    253                             const char* shard_index_str,
    254                             bool in_subprocess_for_death_test);
    255 
    256 // Parses the environment variable var as an Int32. If it is unset,
    257 // returns default_val. If it is not an Int32, prints an error and
    258 // and aborts.
    259 GTEST_API_ Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val);
    260 
    261 // Given the total number of shards, the shard index, and the test id,
    262 // returns true iff the test should be run on this shard. The test id is
    263 // some arbitrary but unique non-negative integer assigned to each test
    264 // method. Assumes that 0 <= shard_index < total_shards.
    265 GTEST_API_ bool ShouldRunTestOnShard(
    266     int total_shards, int shard_index, int test_id);
    267 
    268 // STL container utilities.
    269 
    270 // Returns the number of elements in the given container that satisfy
    271 // the given predicate.
    272 template <class Container, typename Predicate>
    273 inline int CountIf(const Container& c, Predicate predicate) {
    274   return static_cast<int>(std::count_if(c.begin(), c.end(), predicate));
    275 }
    276 
    277 // Applies a function/functor to each element in the container.
    278 template <class Container, typename Functor>
    279 void ForEach(const Container& c, Functor functor) {
    280   std::for_each(c.begin(), c.end(), functor);
    281 }
    282 
    283 // Returns the i-th element of the vector, or default_value if i is not
    284 // in range [0, v.size()).
    285 template <typename E>
    286 inline E GetElementOr(const std::vector<E>& v, int i, E default_value) {
    287   return (i < 0 || i >= static_cast<int>(v.size())) ? default_value : v[i];
    288 }
    289 
    290 // Performs an in-place shuffle of a range of the vector's elements.
    291 // 'begin' and 'end' are element indices as an STL-style range;
    292 // i.e. [begin, end) are shuffled, where 'end' == size() means to
    293 // shuffle to the end of the vector.
    294 template <typename E>
    295 void ShuffleRange(internal::Random* random, int begin, int end,
    296                   std::vector<E>* v) {
    297   const int size = static_cast<int>(v->size());
    298   GTEST_CHECK_(0 <= begin && begin <= size)
    299       << "Invalid shuffle range start " << begin << ": must be in range [0, "
    300       << size << "].";
    301   GTEST_CHECK_(begin <= end && end <= size)
    302       << "Invalid shuffle range finish " << end << ": must be in range ["
    303       << begin << ", " << size << "].";
    304 
    305   // Fisher-Yates shuffle, from
    306   // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
    307   for (int range_width = end - begin; range_width >= 2; range_width--) {
    308     const int last_in_range = begin + range_width - 1;
    309     const int selected = begin + random->Generate(range_width);
    310     std::swap((*v)[selected], (*v)[last_in_range]);
    311   }
    312 }
    313 
    314 // Performs an in-place shuffle of the vector's elements.
    315 template <typename E>
    316 inline void Shuffle(internal::Random* random, std::vector<E>* v) {
    317   ShuffleRange(random, 0, static_cast<int>(v->size()), v);
    318 }
    319 
    320 // A function for deleting an object.  Handy for being used as a
    321 // functor.
    322 template <typename T>
    323 static void Delete(T* x) {
    324   delete x;
    325 }
    326 
    327 // A predicate that checks the key of a TestProperty against a known key.
    328 //
    329 // TestPropertyKeyIs is copyable.
    330 class TestPropertyKeyIs {
    331  public:
    332   // Constructor.
    333   //
    334   // TestPropertyKeyIs has NO default constructor.
    335   explicit TestPropertyKeyIs(const char* key)
    336       : key_(key) {}
    337 
    338   // Returns true iff the test name of test property matches on key_.
    339   bool operator()(const TestProperty& test_property) const {
    340     return String(test_property.key()).Compare(key_) == 0;
    341   }
    342 
    343  private:
    344   String key_;
    345 };
    346 
    347 // Class UnitTestOptions.
    348 //
    349 // This class contains functions for processing options the user
    350 // specifies when running the tests.  It has only static members.
    351 //
    352 // In most cases, the user can specify an option using either an
    353 // environment variable or a command line flag.  E.g. you can set the
    354 // test filter using either GTEST_FILTER or --gtest_filter.  If both
    355 // the variable and the flag are present, the latter overrides the
    356 // former.
    357 class GTEST_API_ UnitTestOptions {
    358  public:
    359   // Functions for processing the gtest_output flag.
    360 
    361   // Returns the output format, or "" for normal printed output.
    362   static String GetOutputFormat();
    363 
    364   // Returns the absolute path of the requested output file, or the
    365   // default (test_detail.xml in the original working directory) if
    366   // none was explicitly specified.
    367   static String GetAbsolutePathToOutputFile();
    368 
    369   // Functions for processing the gtest_filter flag.
    370 
    371   // Returns true iff the wildcard pattern matches the string.  The
    372   // first ':' or '\0' character in pattern marks the end of it.
    373   //
    374   // This recursive algorithm isn't very efficient, but is clear and
    375   // works well enough for matching test names, which are short.
    376   static bool PatternMatchesString(const char *pattern, const char *str);
    377 
    378   // Returns true iff the user-specified filter matches the test case
    379   // name and the test name.
    380   static bool FilterMatchesTest(const String &test_case_name,
    381                                 const String &test_name);
    382 
    383 #if GTEST_OS_WINDOWS
    384   // Function for supporting the gtest_catch_exception flag.
    385 
    386   // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
    387   // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
    388   // This function is useful as an __except condition.
    389   static int GTestShouldProcessSEH(DWORD exception_code);
    390 #endif  // GTEST_OS_WINDOWS
    391 
    392   // Returns true if "name" matches the ':' separated list of glob-style
    393   // filters in "filter".
    394   static bool MatchesFilter(const String& name, const char* filter);
    395 };
    396 
    397 // Returns the current application's name, removing directory path if that
    398 // is present.  Used by UnitTestOptions::GetOutputFile.
    399 GTEST_API_ FilePath GetCurrentExecutableName();
    400 
    401 // The role interface for getting the OS stack trace as a string.
    402 class OsStackTraceGetterInterface {
    403  public:
    404   OsStackTraceGetterInterface() {}
    405   virtual ~OsStackTraceGetterInterface() {}
    406 
    407   // Returns the current OS stack trace as a String.  Parameters:
    408   //
    409   //   max_depth  - the maximum number of stack frames to be included
    410   //                in the trace.
    411   //   skip_count - the number of top frames to be skipped; doesn't count
    412   //                against max_depth.
    413   virtual String CurrentStackTrace(int max_depth, int skip_count) = 0;
    414 
    415   // UponLeavingGTest() should be called immediately before Google Test calls
    416   // user code. It saves some information about the current stack that
    417   // CurrentStackTrace() will use to find and hide Google Test stack frames.
    418   virtual void UponLeavingGTest() = 0;
    419 
    420  private:
    421   GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface);
    422 };
    423 
    424 // A working implementation of the OsStackTraceGetterInterface interface.
    425 class OsStackTraceGetter : public OsStackTraceGetterInterface {
    426  public:
    427   OsStackTraceGetter() : caller_frame_(NULL) {}
    428   virtual String CurrentStackTrace(int max_depth, int skip_count);
    429   virtual void UponLeavingGTest();
    430 
    431   // This string is inserted in place of stack frames that are part of
    432   // Google Test's implementation.
    433   static const char* const kElidedFramesMarker;
    434 
    435  private:
    436   Mutex mutex_;  // protects all internal state
    437 
    438   // We save the stack frame below the frame that calls user code.
    439   // We do this because the address of the frame immediately below
    440   // the user code changes between the call to UponLeavingGTest()
    441   // and any calls to CurrentStackTrace() from within the user code.
    442   void* caller_frame_;
    443 
    444   GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter);
    445 };
    446 
    447 // Information about a Google Test trace point.
    448 struct TraceInfo {
    449   const char* file;
    450   int line;
    451   String message;
    452 };
    453 
    454 // This is the default global test part result reporter used in UnitTestImpl.
    455 // This class should only be used by UnitTestImpl.
    456 class DefaultGlobalTestPartResultReporter
    457   : public TestPartResultReporterInterface {
    458  public:
    459   explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test);
    460   // Implements the TestPartResultReporterInterface. Reports the test part
    461   // result in the current test.
    462   virtual void ReportTestPartResult(const TestPartResult& result);
    463 
    464  private:
    465   UnitTestImpl* const unit_test_;
    466 
    467   GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter);
    468 };
    469 
    470 // This is the default per thread test part result reporter used in
    471 // UnitTestImpl. This class should only be used by UnitTestImpl.
    472 class DefaultPerThreadTestPartResultReporter
    473     : public TestPartResultReporterInterface {
    474  public:
    475   explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test);
    476   // Implements the TestPartResultReporterInterface. The implementation just
    477   // delegates to the current global test part result reporter of *unit_test_.
    478   virtual void ReportTestPartResult(const TestPartResult& result);
    479 
    480  private:
    481   UnitTestImpl* const unit_test_;
    482 
    483   GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter);
    484 };
    485 
    486 // The private implementation of the UnitTest class.  We don't protect
    487 // the methods under a mutex, as this class is not accessible by a
    488 // user and the UnitTest class that delegates work to this class does
    489 // proper locking.
    490 class GTEST_API_ UnitTestImpl {
    491  public:
    492   explicit UnitTestImpl(UnitTest* parent);
    493   virtual ~UnitTestImpl();
    494 
    495   // There are two different ways to register your own TestPartResultReporter.
    496   // You can register your own repoter to listen either only for test results
    497   // from the current thread or for results from all threads.
    498   // By default, each per-thread test result repoter just passes a new
    499   // TestPartResult to the global test result reporter, which registers the
    500   // test part result for the currently running test.
    501 
    502   // Returns the global test part result reporter.
    503   TestPartResultReporterInterface* GetGlobalTestPartResultReporter();
    504 
    505   // Sets the global test part result reporter.
    506   void SetGlobalTestPartResultReporter(
    507       TestPartResultReporterInterface* reporter);
    508 
    509   // Returns the test part result reporter for the current thread.
    510   TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread();
    511 
    512   // Sets the test part result reporter for the current thread.
    513   void SetTestPartResultReporterForCurrentThread(
    514       TestPartResultReporterInterface* reporter);
    515 
    516   // Gets the number of successful test cases.
    517   int successful_test_case_count() const;
    518 
    519   // Gets the number of failed test cases.
    520   int failed_test_case_count() const;
    521 
    522   // Gets the number of all test cases.
    523   int total_test_case_count() const;
    524 
    525   // Gets the number of all test cases that contain at least one test
    526   // that should run.
    527   int test_case_to_run_count() const;
    528 
    529   // Gets the number of successful tests.
    530   int successful_test_count() const;
    531 
    532   // Gets the number of failed tests.
    533   int failed_test_count() const;
    534 
    535   // Gets the number of disabled tests.
    536   int disabled_test_count() const;
    537 
    538   // Gets the number of all tests.
    539   int total_test_count() const;
    540 
    541   // Gets the number of tests that should run.
    542   int test_to_run_count() const;
    543 
    544   // Gets the elapsed time, in milliseconds.
    545   TimeInMillis elapsed_time() const { return elapsed_time_; }
    546 
    547   // Returns true iff the unit test passed (i.e. all test cases passed).
    548   bool Passed() const { return !Failed(); }
    549 
    550   // Returns true iff the unit test failed (i.e. some test case failed
    551   // or something outside of all tests failed).
    552   bool Failed() const {
    553     return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed();
    554   }
    555 
    556   // Gets the i-th test case among all the test cases. i can range from 0 to
    557   // total_test_case_count() - 1. If i is not in that range, returns NULL.
    558   const TestCase* GetTestCase(int i) const {
    559     const int index = GetElementOr(test_case_indices_, i, -1);
    560     return index < 0 ? NULL : test_cases_[i];
    561   }
    562 
    563   // Gets the i-th test case among all the test cases. i can range from 0 to
    564   // total_test_case_count() - 1. If i is not in that range, returns NULL.
    565   TestCase* GetMutableTestCase(int i) {
    566     const int index = GetElementOr(test_case_indices_, i, -1);
    567     return index < 0 ? NULL : test_cases_[index];
    568   }
    569 
    570   // Provides access to the event listener list.
    571   TestEventListeners* listeners() { return &listeners_; }
    572 
    573   // Returns the TestResult for the test that's currently running, or
    574   // the TestResult for the ad hoc test if no test is running.
    575   TestResult* current_test_result();
    576 
    577   // Returns the TestResult for the ad hoc test.
    578   const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; }
    579 
    580   // Sets the OS stack trace getter.
    581   //
    582   // Does nothing if the input and the current OS stack trace getter
    583   // are the same; otherwise, deletes the old getter and makes the
    584   // input the current getter.
    585   void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter);
    586 
    587   // Returns the current OS stack trace getter if it is not NULL;
    588   // otherwise, creates an OsStackTraceGetter, makes it the current
    589   // getter, and returns it.
    590   OsStackTraceGetterInterface* os_stack_trace_getter();
    591 
    592   // Returns the current OS stack trace as a String.
    593   //
    594   // The maximum number of stack frames to be included is specified by
    595   // the gtest_stack_trace_depth flag.  The skip_count parameter
    596   // specifies the number of top frames to be skipped, which doesn't
    597   // count against the number of frames to be included.
    598   //
    599   // For example, if Foo() calls Bar(), which in turn calls
    600   // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
    601   // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
    602   String CurrentOsStackTraceExceptTop(int skip_count);
    603 
    604   // Finds and returns a TestCase with the given name.  If one doesn't
    605   // exist, creates one and returns it.
    606   //
    607   // Arguments:
    608   //
    609   //   test_case_name: name of the test case
    610   //   type_param:     the name of the test's type parameter, or NULL if
    611   //                   this is not a typed or a type-parameterized test.
    612   //   set_up_tc:      pointer to the function that sets up the test case
    613   //   tear_down_tc:   pointer to the function that tears down the test case
    614   TestCase* GetTestCase(const char* test_case_name,
    615                         const char* type_param,
    616                         Test::SetUpTestCaseFunc set_up_tc,
    617                         Test::TearDownTestCaseFunc tear_down_tc);
    618 
    619   // Adds a TestInfo to the unit test.
    620   //
    621   // Arguments:
    622   //
    623   //   set_up_tc:    pointer to the function that sets up the test case
    624   //   tear_down_tc: pointer to the function that tears down the test case
    625   //   test_info:    the TestInfo object
    626   void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc,
    627                    Test::TearDownTestCaseFunc tear_down_tc,
    628                    TestInfo* test_info) {
    629     // In order to support thread-safe death tests, we need to
    630     // remember the original working directory when the test program
    631     // was first invoked.  We cannot do this in RUN_ALL_TESTS(), as
    632     // the user may have changed the current directory before calling
    633     // RUN_ALL_TESTS().  Therefore we capture the current directory in
    634     // AddTestInfo(), which is called to register a TEST or TEST_F
    635     // before main() is reached.
    636     if (original_working_dir_.IsEmpty()) {
    637       original_working_dir_.Set(FilePath::GetCurrentDir());
    638       GTEST_CHECK_(!original_working_dir_.IsEmpty())
    639           << "Failed to get the current working directory.";
    640     }
    641 
    642     GetTestCase(test_info->test_case_name(),
    643                 test_info->type_param(),
    644                 set_up_tc,
    645                 tear_down_tc)->AddTestInfo(test_info);
    646   }
    647 
    648 #if GTEST_HAS_PARAM_TEST
    649   // Returns ParameterizedTestCaseRegistry object used to keep track of
    650   // value-parameterized tests and instantiate and register them.
    651   internal::ParameterizedTestCaseRegistry& parameterized_test_registry() {
    652     return parameterized_test_registry_;
    653   }
    654 #endif  // GTEST_HAS_PARAM_TEST
    655 
    656   // Sets the TestCase object for the test that's currently running.
    657   void set_current_test_case(TestCase* a_current_test_case) {
    658     current_test_case_ = a_current_test_case;
    659   }
    660 
    661   // Sets the TestInfo object for the test that's currently running.  If
    662   // current_test_info is NULL, the assertion results will be stored in
    663   // ad_hoc_test_result_.
    664   void set_current_test_info(TestInfo* a_current_test_info) {
    665     current_test_info_ = a_current_test_info;
    666   }
    667 
    668   // Registers all parameterized tests defined using TEST_P and
    669   // INSTANTIATE_TEST_CASE_P, creating regular tests for each test/parameter
    670   // combination. This method can be called more then once; it has guards
    671   // protecting from registering the tests more then once.  If
    672   // value-parameterized tests are disabled, RegisterParameterizedTests is
    673   // present but does nothing.
    674   void RegisterParameterizedTests();
    675 
    676   // Runs all tests in this UnitTest object, prints the result, and
    677   // returns true if all tests are successful.  If any exception is
    678   // thrown during a test, this test is considered to be failed, but
    679   // the rest of the tests will still be run.
    680   bool RunAllTests();
    681 
    682   // Clears the results of all tests, except the ad hoc tests.
    683   void ClearNonAdHocTestResult() {
    684     ForEach(test_cases_, TestCase::ClearTestCaseResult);
    685   }
    686 
    687   // Clears the results of ad-hoc test assertions.
    688   void ClearAdHocTestResult() {
    689     ad_hoc_test_result_.Clear();
    690   }
    691 
    692   enum ReactionToSharding {
    693     HONOR_SHARDING_PROTOCOL,
    694     IGNORE_SHARDING_PROTOCOL
    695   };
    696 
    697   // Matches the full name of each test against the user-specified
    698   // filter to decide whether the test should run, then records the
    699   // result in each TestCase and TestInfo object.
    700   // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests
    701   // based on sharding variables in the environment.
    702   // Returns the number of tests that should run.
    703   int FilterTests(ReactionToSharding shard_tests);
    704 
    705   // Prints the names of the tests matching the user-specified filter flag.
    706   void ListTestsMatchingFilter();
    707 
    708   const TestCase* current_test_case() const { return current_test_case_; }
    709   TestInfo* current_test_info() { return current_test_info_; }
    710   const TestInfo* current_test_info() const { return current_test_info_; }
    711 
    712   // Returns the vector of environments that need to be set-up/torn-down
    713   // before/after the tests are run.
    714   std::vector<Environment*>& environments() { return environments_; }
    715 
    716   // Getters for the per-thread Google Test trace stack.
    717   std::vector<TraceInfo>& gtest_trace_stack() {
    718     return *(gtest_trace_stack_.pointer());
    719   }
    720   const std::vector<TraceInfo>& gtest_trace_stack() const {
    721     return gtest_trace_stack_.get();
    722   }
    723 
    724 #if GTEST_HAS_DEATH_TEST
    725   void InitDeathTestSubprocessControlInfo() {
    726     internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());
    727   }
    728   // Returns a pointer to the parsed --gtest_internal_run_death_test
    729   // flag, or NULL if that flag was not specified.
    730   // This information is useful only in a death test child process.
    731   // Must not be called before a call to InitGoogleTest.
    732   const InternalRunDeathTestFlag* internal_run_death_test_flag() const {
    733     return internal_run_death_test_flag_.get();
    734   }
    735 
    736   // Returns a pointer to the current death test factory.
    737   internal::DeathTestFactory* death_test_factory() {
    738     return death_test_factory_.get();
    739   }
    740 
    741   void SuppressTestEventsIfInSubprocess();
    742 
    743   friend class ReplaceDeathTestFactory;
    744 #endif  // GTEST_HAS_DEATH_TEST
    745 
    746   // Initializes the event listener performing XML output as specified by
    747   // UnitTestOptions. Must not be called before InitGoogleTest.
    748   void ConfigureXmlOutput();
    749 
    750 #if GTEST_CAN_STREAM_RESULTS_
    751   // Initializes the event listener for streaming test results to a socket.
    752   // Must not be called before InitGoogleTest.
    753   void ConfigureStreamingOutput();
    754 #endif
    755 
    756   // Performs initialization dependent upon flag values obtained in
    757   // ParseGoogleTestFlagsOnly.  Is called from InitGoogleTest after the call to
    758   // ParseGoogleTestFlagsOnly.  In case a user neglects to call InitGoogleTest
    759   // this function is also called from RunAllTests.  Since this function can be
    760   // called more than once, it has to be idempotent.
    761   void PostFlagParsingInit();
    762 
    763   // Gets the random seed used at the start of the current test iteration.
    764   int random_seed() const { return random_seed_; }
    765 
    766   // Gets the random number generator.
    767   internal::Random* random() { return &random_; }
    768 
    769   // Shuffles all test cases, and the tests within each test case,
    770   // making sure that death tests are still run first.
    771   void ShuffleTests();
    772 
    773   // Restores the test cases and tests to their order before the first shuffle.
    774   void UnshuffleTests();
    775 
    776   // Returns the value of GTEST_FLAG(catch_exceptions) at the moment
    777   // UnitTest::Run() starts.
    778   bool catch_exceptions() const { return catch_exceptions_; }
    779 
    780  private:
    781   friend class ::testing::UnitTest;
    782 
    783   // Used by UnitTest::Run() to capture the state of
    784   // GTEST_FLAG(catch_exceptions) at the moment it starts.
    785   void set_catch_exceptions(bool value) { catch_exceptions_ = value; }
    786 
    787   // The UnitTest object that owns this implementation object.
    788   UnitTest* const parent_;
    789 
    790   // The working directory when the first TEST() or TEST_F() was
    791   // executed.
    792   internal::FilePath original_working_dir_;
    793 
    794   // The default test part result reporters.
    795   DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_;
    796   DefaultPerThreadTestPartResultReporter
    797       default_per_thread_test_part_result_reporter_;
    798 
    799   // Points to (but doesn't own) the global test part result reporter.
    800   TestPartResultReporterInterface* global_test_part_result_repoter_;
    801 
    802   // Protects read and write access to global_test_part_result_reporter_.
    803   internal::Mutex global_test_part_result_reporter_mutex_;
    804 
    805   // Points to (but doesn't own) the per-thread test part result reporter.
    806   internal::ThreadLocal<TestPartResultReporterInterface*>
    807       per_thread_test_part_result_reporter_;
    808 
    809   // The vector of environments that need to be set-up/torn-down
    810   // before/after the tests are run.
    811   std::vector<Environment*> environments_;
    812 
    813   // The vector of TestCases in their original order.  It owns the
    814   // elements in the vector.
    815   std::vector<TestCase*> test_cases_;
    816 
    817   // Provides a level of indirection for the test case list to allow
    818   // easy shuffling and restoring the test case order.  The i-th
    819   // element of this vector is the index of the i-th test case in the
    820   // shuffled order.
    821   std::vector<int> test_case_indices_;
    822 
    823 #if GTEST_HAS_PARAM_TEST
    824   // ParameterizedTestRegistry object used to register value-parameterized
    825   // tests.
    826   internal::ParameterizedTestCaseRegistry parameterized_test_registry_;
    827 
    828   // Indicates whether RegisterParameterizedTests() has been called already.
    829   bool parameterized_tests_registered_;
    830 #endif  // GTEST_HAS_PARAM_TEST
    831 
    832   // Index of the last death test case registered.  Initially -1.
    833   int last_death_test_case_;
    834 
    835   // This points to the TestCase for the currently running test.  It
    836   // changes as Google Test goes through one test case after another.
    837   // When no test is running, this is set to NULL and Google Test
    838   // stores assertion results in ad_hoc_test_result_.  Initially NULL.
    839   TestCase* current_test_case_;
    840 
    841   // This points to the TestInfo for the currently running test.  It
    842   // changes as Google Test goes through one test after another.  When
    843   // no test is running, this is set to NULL and Google Test stores
    844   // assertion results in ad_hoc_test_result_.  Initially NULL.
    845   TestInfo* current_test_info_;
    846 
    847   // Normally, a user only writes assertions inside a TEST or TEST_F,
    848   // or inside a function called by a TEST or TEST_F.  Since Google
    849   // Test keeps track of which test is current running, it can
    850   // associate such an assertion with the test it belongs to.
    851   //
    852   // If an assertion is encountered when no TEST or TEST_F is running,
    853   // Google Test attributes the assertion result to an imaginary "ad hoc"
    854   // test, and records the result in ad_hoc_test_result_.
    855   TestResult ad_hoc_test_result_;
    856 
    857   // The list of event listeners that can be used to track events inside
    858   // Google Test.
    859   TestEventListeners listeners_;
    860 
    861   // The OS stack trace getter.  Will be deleted when the UnitTest
    862   // object is destructed.  By default, an OsStackTraceGetter is used,
    863   // but the user can set this field to use a custom getter if that is
    864   // desired.
    865   OsStackTraceGetterInterface* os_stack_trace_getter_;
    866 
    867   // True iff PostFlagParsingInit() has been called.
    868   bool post_flag_parse_init_performed_;
    869 
    870   // The random number seed used at the beginning of the test run.
    871   int random_seed_;
    872 
    873   // Our random number generator.
    874   internal::Random random_;
    875 
    876   // How long the test took to run, in milliseconds.
    877   TimeInMillis elapsed_time_;
    878 
    879 #if GTEST_HAS_DEATH_TEST
    880   // The decomposed components of the gtest_internal_run_death_test flag,
    881   // parsed when RUN_ALL_TESTS is called.
    882   internal::scoped_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;
    883   internal::scoped_ptr<internal::DeathTestFactory> death_test_factory_;
    884 #endif  // GTEST_HAS_DEATH_TEST
    885 
    886   // A per-thread stack of traces created by the SCOPED_TRACE() macro.
    887   internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_;
    888 
    889   // The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests()
    890   // starts.
    891   bool catch_exceptions_;
    892 
    893   GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl);
    894 };  // class UnitTestImpl
    895 
    896 // Convenience function for accessing the global UnitTest
    897 // implementation object.
    898 inline UnitTestImpl* GetUnitTestImpl() {
    899   return UnitTest::GetInstance()->impl();
    900 }
    901 
    902 #if GTEST_USES_SIMPLE_RE
    903 
    904 // Internal helper functions for implementing the simple regular
    905 // expression matcher.
    906 GTEST_API_ bool IsInSet(char ch, const char* str);
    907 GTEST_API_ bool IsAsciiDigit(char ch);
    908 GTEST_API_ bool IsAsciiPunct(char ch);
    909 GTEST_API_ bool IsRepeat(char ch);
    910 GTEST_API_ bool IsAsciiWhiteSpace(char ch);
    911 GTEST_API_ bool IsAsciiWordChar(char ch);
    912 GTEST_API_ bool IsValidEscape(char ch);
    913 GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch);
    914 GTEST_API_ bool ValidateRegex(const char* regex);
    915 GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str);
    916 GTEST_API_ bool MatchRepetitionAndRegexAtHead(
    917     bool escaped, char ch, char repeat, const char* regex, const char* str);
    918 GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str);
    919 
    920 #endif  // GTEST_USES_SIMPLE_RE
    921 
    922 // Parses the command line for Google Test flags, without initializing
    923 // other parts of Google Test.
    924 GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv);
    925 GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv);
    926 
    927 #if GTEST_HAS_DEATH_TEST
    928 
    929 // Returns the message describing the last system error, regardless of the
    930 // platform.
    931 GTEST_API_ String GetLastErrnoDescription();
    932 
    933 # if GTEST_OS_WINDOWS
    934 // Provides leak-safe Windows kernel handle ownership.
    935 class AutoHandle {
    936  public:
    937   AutoHandle() : handle_(INVALID_HANDLE_VALUE) {}
    938   explicit AutoHandle(HANDLE handle) : handle_(handle) {}
    939 
    940   ~AutoHandle() { Reset(); }
    941 
    942   HANDLE Get() const { return handle_; }
    943   void Reset() { Reset(INVALID_HANDLE_VALUE); }
    944   void Reset(HANDLE handle) {
    945     if (handle != handle_) {
    946       if (handle_ != INVALID_HANDLE_VALUE)
    947         ::CloseHandle(handle_);
    948       handle_ = handle;
    949     }
    950   }
    951 
    952  private:
    953   HANDLE handle_;
    954 
    955   GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle);
    956 };
    957 # endif  // GTEST_OS_WINDOWS
    958 
    959 // Attempts to parse a string into a positive integer pointed to by the
    960 // number parameter.  Returns true if that is possible.
    961 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use
    962 // it here.
    963 template <typename Integer>
    964 bool ParseNaturalNumber(const ::std::string& str, Integer* number) {
    965   // Fail fast if the given string does not begin with a digit;
    966   // this bypasses strtoXXX's "optional leading whitespace and plus
    967   // or minus sign" semantics, which are undesirable here.
    968   if (str.empty() || !IsDigit(str[0])) {
    969     return false;
    970   }
    971   errno = 0;
    972 
    973   char* end;
    974   // BiggestConvertible is the largest integer type that system-provided
    975   // string-to-number conversion routines can return.
    976 
    977 # if GTEST_OS_WINDOWS && !defined(__GNUC__)
    978 
    979   // MSVC and C++ Builder define __int64 instead of the standard long long.
    980   typedef unsigned __int64 BiggestConvertible;
    981   const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10);
    982 
    983 # else
    984 
    985   typedef unsigned long long BiggestConvertible;  // NOLINT
    986   const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10);
    987 
    988 # endif  // GTEST_OS_WINDOWS && !defined(__GNUC__)
    989 
    990   const bool parse_success = *end == '\0' && errno == 0;
    991 
    992   // TODO(vladl (at) google.com): Convert this to compile time assertion when it is
    993   // available.
    994   GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed));
    995 
    996   const Integer result = static_cast<Integer>(parsed);
    997   if (parse_success && static_cast<BiggestConvertible>(result) == parsed) {
    998     *number = result;
    999     return true;
   1000   }
   1001   return false;
   1002 }
   1003 #endif  // GTEST_HAS_DEATH_TEST
   1004 
   1005 // TestResult contains some private methods that should be hidden from
   1006 // Google Test user but are required for testing. This class allow our tests
   1007 // to access them.
   1008 //
   1009 // This class is supplied only for the purpose of testing Google Test's own
   1010 // constructs. Do not use it in user tests, either directly or indirectly.
   1011 class TestResultAccessor {
   1012  public:
   1013   static void RecordProperty(TestResult* test_result,
   1014                              const TestProperty& property) {
   1015     test_result->RecordProperty(property);
   1016   }
   1017 
   1018   static void ClearTestPartResults(TestResult* test_result) {
   1019     test_result->ClearTestPartResults();
   1020   }
   1021 
   1022   static const std::vector<testing::TestPartResult>& test_part_results(
   1023       const TestResult& test_result) {
   1024     return test_result.test_part_results();
   1025   }
   1026 };
   1027 
   1028 }  // namespace internal
   1029 }  // namespace testing
   1030 
   1031 #endif  // GTEST_SRC_GTEST_INTERNAL_INL_H_
   1032