gtest-internal-inl.h
Go to the documentation of this file.
00001 // Copyright 2005, Google Inc.
00002 // All rights reserved.
00003 //
00004 // Redistribution and use in source and binary forms, with or without
00005 // modification, are permitted provided that the following conditions are
00006 // met:
00007 //
00008 //     * Redistributions of source code must retain the above copyright
00009 // notice, this list of conditions and the following disclaimer.
00010 //     * Redistributions in binary form must reproduce the above
00011 // copyright notice, this list of conditions and the following disclaimer
00012 // in the documentation and/or other materials provided with the
00013 // distribution.
00014 //     * Neither the name of Google Inc. nor the names of its
00015 // contributors may be used to endorse or promote products derived from
00016 // this software without specific prior written permission.
00017 //
00018 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
00019 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
00020 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
00021 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
00022 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
00023 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
00024 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
00025 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
00026 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
00027 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
00028 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
00029 
00030 // Utility functions and classes used by the Google C++ testing framework.
00031 //
00032 // Author: wan@google.com (Zhanyong Wan)
00033 //
00034 // This file contains purely Google Test's internal implementation.  Please
00035 // DO NOT #INCLUDE IT IN A USER PROGRAM.
00036 
00037 #ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_
00038 #define GTEST_SRC_GTEST_INTERNAL_INL_H_
00039 
00040 // GTEST_IMPLEMENTATION_ is defined to 1 iff the current translation unit is
00041 // part of Google Test's implementation; otherwise it's undefined.
00042 #if !GTEST_IMPLEMENTATION_
00043 // A user is trying to include this from his code - just say no.
00044 # error "gtest-internal-inl.h is part of Google Test's internal implementation."
00045 # error "It must not be included except by Google Test itself."
00046 #endif  // GTEST_IMPLEMENTATION_
00047 
00048 #ifndef _WIN32_WCE
00049 # include <errno.h>
00050 #endif  // !_WIN32_WCE
00051 #include <stddef.h>
00052 #include <stdlib.h>  // For strtoll/_strtoul64/malloc/free.
00053 #include <string.h>  // For memmove.
00054 
00055 #include <algorithm>
00056 #include <string>
00057 #include <vector>
00058 
00059 #include "gtest/internal/gtest-port.h"
00060 
00061 #if GTEST_OS_WINDOWS
00062 # include <windows.h>  // NOLINT
00063 #endif  // GTEST_OS_WINDOWS
00064 
00065 #include "gtest/gtest.h"  // NOLINT
00066 #include "gtest/gtest-spi.h"
00067 
00068 namespace testing {
00069 
00070 // Declares the flags.
00071 //
00072 // We don't want the users to modify this flag in the code, but want
00073 // Google Test's own unit tests to be able to access it. Therefore we
00074 // declare it here as opposed to in gtest.h.
00075 GTEST_DECLARE_bool_(death_test_use_fork);
00076 
00077 namespace internal {
00078 
00079 // The value of GetTestTypeId() as seen from within the Google Test
00080 // library.  This is solely for testing GetTestTypeId().
00081 GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest;
00082 
00083 // Names of the flags (needed for parsing Google Test flags).
00084 const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests";
00085 const char kBreakOnFailureFlag[] = "break_on_failure";
00086 const char kCatchExceptionsFlag[] = "catch_exceptions";
00087 const char kColorFlag[] = "color";
00088 const char kFilterFlag[] = "filter";
00089 const char kListTestsFlag[] = "list_tests";
00090 const char kOutputFlag[] = "output";
00091 const char kPrintTimeFlag[] = "print_time";
00092 const char kRandomSeedFlag[] = "random_seed";
00093 const char kRepeatFlag[] = "repeat";
00094 const char kShuffleFlag[] = "shuffle";
00095 const char kStackTraceDepthFlag[] = "stack_trace_depth";
00096 const char kStreamResultToFlag[] = "stream_result_to";
00097 const char kThrowOnFailureFlag[] = "throw_on_failure";
00098 
00099 // A valid random seed must be in [1, kMaxRandomSeed].
00100 const int kMaxRandomSeed = 99999;
00101 
00102 // g_help_flag is true iff the --help flag or an equivalent form is
00103 // specified on the command line.
00104 GTEST_API_ extern bool g_help_flag;
00105 
00106 // Returns the current time in milliseconds.
00107 GTEST_API_ TimeInMillis GetTimeInMillis();
00108 
00109 // Returns true iff Google Test should use colors in the output.
00110 GTEST_API_ bool ShouldUseColor(bool stdout_is_tty);
00111 
00112 // Formats the given time in milliseconds as seconds.
00113 GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms);
00114 
00115 // Parses a string for an Int32 flag, in the form of "--flag=value".
00116 //
00117 // On success, stores the value of the flag in *value, and returns
00118 // true.  On failure, returns false without changing *value.
00119 GTEST_API_ bool ParseInt32Flag(
00120     const char* str, const char* flag, Int32* value);
00121 
00122 // Returns a random seed in range [1, kMaxRandomSeed] based on the
00123 // given --gtest_random_seed flag value.
00124 inline int GetRandomSeedFromFlag(Int32 random_seed_flag) {
00125   const unsigned int raw_seed = (random_seed_flag == 0) ?
00126       static_cast<unsigned int>(GetTimeInMillis()) :
00127       static_cast<unsigned int>(random_seed_flag);
00128 
00129   // Normalizes the actual seed to range [1, kMaxRandomSeed] such that
00130   // it's easy to type.
00131   const int normalized_seed =
00132       static_cast<int>((raw_seed - 1U) %
00133                        static_cast<unsigned int>(kMaxRandomSeed)) + 1;
00134   return normalized_seed;
00135 }
00136 
00137 // Returns the first valid random seed after 'seed'.  The behavior is
00138 // undefined if 'seed' is invalid.  The seed after kMaxRandomSeed is
00139 // considered to be 1.
00140 inline int GetNextRandomSeed(int seed) {
00141   GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed)
00142       << "Invalid random seed " << seed << " - must be in [1, "
00143       << kMaxRandomSeed << "].";
00144   const int next_seed = seed + 1;
00145   return (next_seed > kMaxRandomSeed) ? 1 : next_seed;
00146 }
00147 
00148 // This class saves the values of all Google Test flags in its c'tor, and
00149 // restores them in its d'tor.
00150 class GTestFlagSaver {
00151  public:
00152   // The c'tor.
00153   GTestFlagSaver() {
00154     also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests);
00155     break_on_failure_ = GTEST_FLAG(break_on_failure);
00156     catch_exceptions_ = GTEST_FLAG(catch_exceptions);
00157     color_ = GTEST_FLAG(color);
00158     death_test_style_ = GTEST_FLAG(death_test_style);
00159     death_test_use_fork_ = GTEST_FLAG(death_test_use_fork);
00160     filter_ = GTEST_FLAG(filter);
00161     internal_run_death_test_ = GTEST_FLAG(internal_run_death_test);
00162     list_tests_ = GTEST_FLAG(list_tests);
00163     output_ = GTEST_FLAG(output);
00164     print_time_ = GTEST_FLAG(print_time);
00165     random_seed_ = GTEST_FLAG(random_seed);
00166     repeat_ = GTEST_FLAG(repeat);
00167     shuffle_ = GTEST_FLAG(shuffle);
00168     stack_trace_depth_ = GTEST_FLAG(stack_trace_depth);
00169     stream_result_to_ = GTEST_FLAG(stream_result_to);
00170     throw_on_failure_ = GTEST_FLAG(throw_on_failure);
00171   }
00172 
00173   // The d'tor is not virtual.  DO NOT INHERIT FROM THIS CLASS.
00174   ~GTestFlagSaver() {
00175     GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_;
00176     GTEST_FLAG(break_on_failure) = break_on_failure_;
00177     GTEST_FLAG(catch_exceptions) = catch_exceptions_;
00178     GTEST_FLAG(color) = color_;
00179     GTEST_FLAG(death_test_style) = death_test_style_;
00180     GTEST_FLAG(death_test_use_fork) = death_test_use_fork_;
00181     GTEST_FLAG(filter) = filter_;
00182     GTEST_FLAG(internal_run_death_test) = internal_run_death_test_;
00183     GTEST_FLAG(list_tests) = list_tests_;
00184     GTEST_FLAG(output) = output_;
00185     GTEST_FLAG(print_time) = print_time_;
00186     GTEST_FLAG(random_seed) = random_seed_;
00187     GTEST_FLAG(repeat) = repeat_;
00188     GTEST_FLAG(shuffle) = shuffle_;
00189     GTEST_FLAG(stack_trace_depth) = stack_trace_depth_;
00190     GTEST_FLAG(stream_result_to) = stream_result_to_;
00191     GTEST_FLAG(throw_on_failure) = throw_on_failure_;
00192   }
00193  private:
00194   // Fields for saving the original values of flags.
00195   bool also_run_disabled_tests_;
00196   bool break_on_failure_;
00197   bool catch_exceptions_;
00198   String color_;
00199   String death_test_style_;
00200   bool death_test_use_fork_;
00201   String filter_;
00202   String internal_run_death_test_;
00203   bool list_tests_;
00204   String output_;
00205   bool print_time_;
00206   bool pretty_;
00207   internal::Int32 random_seed_;
00208   internal::Int32 repeat_;
00209   bool shuffle_;
00210   internal::Int32 stack_trace_depth_;
00211   String stream_result_to_;
00212   bool throw_on_failure_;
00213 } GTEST_ATTRIBUTE_UNUSED_;
00214 
00215 // Converts a Unicode code point to a narrow string in UTF-8 encoding.
00216 // code_point parameter is of type UInt32 because wchar_t may not be
00217 // wide enough to contain a code point.
00218 // The output buffer str must containt at least 32 characters.
00219 // The function returns the address of the output buffer.
00220 // If the code_point is not a valid Unicode code point
00221 // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be output
00222 // as '(Invalid Unicode 0xXXXXXXXX)'.
00223 GTEST_API_ char* CodePointToUtf8(UInt32 code_point, char* str);
00224 
00225 // Converts a wide string to a narrow string in UTF-8 encoding.
00226 // The wide string is assumed to have the following encoding:
00227 //   UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
00228 //   UTF-32 if sizeof(wchar_t) == 4 (on Linux)
00229 // Parameter str points to a null-terminated wide string.
00230 // Parameter num_chars may additionally limit the number
00231 // of wchar_t characters processed. -1 is used when the entire string
00232 // should be processed.
00233 // If the string contains code points that are not valid Unicode code points
00234 // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
00235 // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
00236 // and contains invalid UTF-16 surrogate pairs, values in those pairs
00237 // will be encoded as individual Unicode characters from Basic Normal Plane.
00238 GTEST_API_ String WideStringToUtf8(const wchar_t* str, int num_chars);
00239 
00240 // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
00241 // if the variable is present. If a file already exists at this location, this
00242 // function will write over it. If the variable is present, but the file cannot
00243 // be created, prints an error and exits.
00244 void WriteToShardStatusFileIfNeeded();
00245 
00246 // Checks whether sharding is enabled by examining the relevant
00247 // environment variable values. If the variables are present,
00248 // but inconsistent (e.g., shard_index >= total_shards), prints
00249 // an error and exits. If in_subprocess_for_death_test, sharding is
00250 // disabled because it must only be applied to the original test
00251 // process. Otherwise, we could filter out death tests we intended to execute.
00252 GTEST_API_ bool ShouldShard(const char* total_shards_str,
00253                             const char* shard_index_str,
00254                             bool in_subprocess_for_death_test);
00255 
00256 // Parses the environment variable var as an Int32. If it is unset,
00257 // returns default_val. If it is not an Int32, prints an error and
00258 // and aborts.
00259 GTEST_API_ Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val);
00260 
00261 // Given the total number of shards, the shard index, and the test id,
00262 // returns true iff the test should be run on this shard. The test id is
00263 // some arbitrary but unique non-negative integer assigned to each test
00264 // method. Assumes that 0 <= shard_index < total_shards.
00265 GTEST_API_ bool ShouldRunTestOnShard(
00266     int total_shards, int shard_index, int test_id);
00267 
00268 // STL container utilities.
00269 
00270 // Returns the number of elements in the given container that satisfy
00271 // the given predicate.
00272 template <class Container, typename Predicate>
00273 inline int CountIf(const Container& c, Predicate predicate) {
00274   // Implemented as an explicit loop since std::count_if() in libCstd on
00275   // Solaris has a non-standard signature.
00276   int count = 0;
00277   for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) {
00278     if (predicate(*it))
00279       ++count;
00280   }
00281   return count;
00282 }
00283 
00284 // Applies a function/functor to each element in the container.
00285 template <class Container, typename Functor>
00286 void ForEach(const Container& c, Functor functor) {
00287   std::for_each(c.begin(), c.end(), functor);
00288 }
00289 
00290 // Returns the i-th element of the vector, or default_value if i is not
00291 // in range [0, v.size()).
00292 template <typename E>
00293 inline E GetElementOr(const std::vector<E>& v, int i, E default_value) {
00294   return (i < 0 || i >= static_cast<int>(v.size())) ? default_value : v[i];
00295 }
00296 
00297 // Performs an in-place shuffle of a range of the vector's elements.
00298 // 'begin' and 'end' are element indices as an STL-style range;
00299 // i.e. [begin, end) are shuffled, where 'end' == size() means to
00300 // shuffle to the end of the vector.
00301 template <typename E>
00302 void ShuffleRange(internal::Random* random, int begin, int end,
00303                   std::vector<E>* v) {
00304   const int size = static_cast<int>(v->size());
00305   GTEST_CHECK_(0 <= begin && begin <= size)
00306       << "Invalid shuffle range start " << begin << ": must be in range [0, "
00307       << size << "].";
00308   GTEST_CHECK_(begin <= end && end <= size)
00309       << "Invalid shuffle range finish " << end << ": must be in range ["
00310       << begin << ", " << size << "].";
00311 
00312   // Fisher-Yates shuffle, from
00313   // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
00314   for (int range_width = end - begin; range_width >= 2; range_width--) {
00315     const int last_in_range = begin + range_width - 1;
00316     const int selected = begin + random->Generate(range_width);
00317     std::swap((*v)[selected], (*v)[last_in_range]);
00318   }
00319 }
00320 
00321 // Performs an in-place shuffle of the vector's elements.
00322 template <typename E>
00323 inline void Shuffle(internal::Random* random, std::vector<E>* v) {
00324   ShuffleRange(random, 0, static_cast<int>(v->size()), v);
00325 }
00326 
00327 // A function for deleting an object.  Handy for being used as a
00328 // functor.
00329 template <typename T>
00330 static void Delete(T* x) {
00331   delete x;
00332 }
00333 
00334 // A predicate that checks the key of a TestProperty against a known key.
00335 //
00336 // TestPropertyKeyIs is copyable.
00337 class TestPropertyKeyIs {
00338  public:
00339   // Constructor.
00340   //
00341   // TestPropertyKeyIs has NO default constructor.
00342   explicit TestPropertyKeyIs(const char* key)
00343       : key_(key) {}
00344 
00345   // Returns true iff the test name of test property matches on key_.
00346   bool operator()(const TestProperty& test_property) const {
00347     return String(test_property.key()).Compare(key_) == 0;
00348   }
00349 
00350  private:
00351   String key_;
00352 };
00353 
00354 // Class UnitTestOptions.
00355 //
00356 // This class contains functions for processing options the user
00357 // specifies when running the tests.  It has only static members.
00358 //
00359 // In most cases, the user can specify an option using either an
00360 // environment variable or a command line flag.  E.g. you can set the
00361 // test filter using either GTEST_FILTER or --gtest_filter.  If both
00362 // the variable and the flag are present, the latter overrides the
00363 // former.
00364 class GTEST_API_ UnitTestOptions {
00365  public:
00366   // Functions for processing the gtest_output flag.
00367 
00368   // Returns the output format, or "" for normal printed output.
00369   static String GetOutputFormat();
00370 
00371   // Returns the absolute path of the requested output file, or the
00372   // default (test_detail.xml in the original working directory) if
00373   // none was explicitly specified.
00374   static String GetAbsolutePathToOutputFile();
00375 
00376   // Functions for processing the gtest_filter flag.
00377 
00378   // Returns true iff the wildcard pattern matches the string.  The
00379   // first ':' or '\0' character in pattern marks the end of it.
00380   //
00381   // This recursive algorithm isn't very efficient, but is clear and
00382   // works well enough for matching test names, which are short.
00383   static bool PatternMatchesString(const char *pattern, const char *str);
00384 
00385   // Returns true iff the user-specified filter matches the test case
00386   // name and the test name.
00387   static bool FilterMatchesTest(const String &test_case_name,
00388                                 const String &test_name);
00389 
00390 #if GTEST_OS_WINDOWS
00391   // Function for supporting the gtest_catch_exception flag.
00392 
00393   // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
00394   // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
00395   // This function is useful as an __except condition.
00396   static int GTestShouldProcessSEH(DWORD exception_code);
00397 #endif  // GTEST_OS_WINDOWS
00398 
00399   // Returns true if "name" matches the ':' separated list of glob-style
00400   // filters in "filter".
00401   static bool MatchesFilter(const String& name, const char* filter);
00402 };
00403 
00404 // Returns the current application's name, removing directory path if that
00405 // is present.  Used by UnitTestOptions::GetOutputFile.
00406 GTEST_API_ FilePath GetCurrentExecutableName();
00407 
00408 // The role interface for getting the OS stack trace as a string.
00409 class OsStackTraceGetterInterface {
00410  public:
00411   OsStackTraceGetterInterface() {}
00412   virtual ~OsStackTraceGetterInterface() {}
00413 
00414   // Returns the current OS stack trace as a String.  Parameters:
00415   //
00416   //   max_depth  - the maximum number of stack frames to be included
00417   //                in the trace.
00418   //   skip_count - the number of top frames to be skipped; doesn't count
00419   //                against max_depth.
00420   virtual String CurrentStackTrace(int max_depth, int skip_count) = 0;
00421 
00422   // UponLeavingGTest() should be called immediately before Google Test calls
00423   // user code. It saves some information about the current stack that
00424   // CurrentStackTrace() will use to find and hide Google Test stack frames.
00425   virtual void UponLeavingGTest() = 0;
00426 
00427  private:
00428   GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface);
00429 };
00430 
00431 // A working implementation of the OsStackTraceGetterInterface interface.
00432 class OsStackTraceGetter : public OsStackTraceGetterInterface {
00433  public:
00434   OsStackTraceGetter() : caller_frame_(NULL) {}
00435   virtual String CurrentStackTrace(int max_depth, int skip_count);
00436   virtual void UponLeavingGTest();
00437 
00438   // This string is inserted in place of stack frames that are part of
00439   // Google Test's implementation.
00440   static const char* const kElidedFramesMarker;
00441 
00442  private:
00443   Mutex mutex_;  // protects all internal state
00444 
00445   // We save the stack frame below the frame that calls user code.
00446   // We do this because the address of the frame immediately below
00447   // the user code changes between the call to UponLeavingGTest()
00448   // and any calls to CurrentStackTrace() from within the user code.
00449   void* caller_frame_;
00450 
00451   GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter);
00452 };
00453 
00454 // Information about a Google Test trace point.
00455 struct TraceInfo {
00456   const char* file;
00457   int line;
00458   String message;
00459 };
00460 
00461 // This is the default global test part result reporter used in UnitTestImpl.
00462 // This class should only be used by UnitTestImpl.
00463 class DefaultGlobalTestPartResultReporter
00464   : public TestPartResultReporterInterface {
00465  public:
00466   explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test);
00467   // Implements the TestPartResultReporterInterface. Reports the test part
00468   // result in the current test.
00469   virtual void ReportTestPartResult(const TestPartResult& result);
00470 
00471  private:
00472   UnitTestImpl* const unit_test_;
00473 
00474   GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter);
00475 };
00476 
00477 // This is the default per thread test part result reporter used in
00478 // UnitTestImpl. This class should only be used by UnitTestImpl.
00479 class DefaultPerThreadTestPartResultReporter
00480     : public TestPartResultReporterInterface {
00481  public:
00482   explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test);
00483   // Implements the TestPartResultReporterInterface. The implementation just
00484   // delegates to the current global test part result reporter of *unit_test_.
00485   virtual void ReportTestPartResult(const TestPartResult& result);
00486 
00487  private:
00488   UnitTestImpl* const unit_test_;
00489 
00490   GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter);
00491 };
00492 
00493 // The private implementation of the UnitTest class.  We don't protect
00494 // the methods under a mutex, as this class is not accessible by a
00495 // user and the UnitTest class that delegates work to this class does
00496 // proper locking.
00497 class GTEST_API_ UnitTestImpl {
00498  public:
00499   explicit UnitTestImpl(UnitTest* parent);
00500   virtual ~UnitTestImpl();
00501 
00502   // There are two different ways to register your own TestPartResultReporter.
00503   // You can register your own repoter to listen either only for test results
00504   // from the current thread or for results from all threads.
00505   // By default, each per-thread test result repoter just passes a new
00506   // TestPartResult to the global test result reporter, which registers the
00507   // test part result for the currently running test.
00508 
00509   // Returns the global test part result reporter.
00510   TestPartResultReporterInterface* GetGlobalTestPartResultReporter();
00511 
00512   // Sets the global test part result reporter.
00513   void SetGlobalTestPartResultReporter(
00514       TestPartResultReporterInterface* reporter);
00515 
00516   // Returns the test part result reporter for the current thread.
00517   TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread();
00518 
00519   // Sets the test part result reporter for the current thread.
00520   void SetTestPartResultReporterForCurrentThread(
00521       TestPartResultReporterInterface* reporter);
00522 
00523   // Gets the number of successful test cases.
00524   int successful_test_case_count() const;
00525 
00526   // Gets the number of failed test cases.
00527   int failed_test_case_count() const;
00528 
00529   // Gets the number of all test cases.
00530   int total_test_case_count() const;
00531 
00532   // Gets the number of all test cases that contain at least one test
00533   // that should run.
00534   int test_case_to_run_count() const;
00535 
00536   // Gets the number of successful tests.
00537   int successful_test_count() const;
00538 
00539   // Gets the number of failed tests.
00540   int failed_test_count() const;
00541 
00542   // Gets the number of disabled tests.
00543   int disabled_test_count() const;
00544 
00545   // Gets the number of all tests.
00546   int total_test_count() const;
00547 
00548   // Gets the number of tests that should run.
00549   int test_to_run_count() const;
00550 
00551   // Gets the elapsed time, in milliseconds.
00552   TimeInMillis elapsed_time() const { return elapsed_time_; }
00553 
00554   // Returns true iff the unit test passed (i.e. all test cases passed).
00555   bool Passed() const { return !Failed(); }
00556 
00557   // Returns true iff the unit test failed (i.e. some test case failed
00558   // or something outside of all tests failed).
00559   bool Failed() const {
00560     return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed();
00561   }
00562 
00563   // Gets the i-th test case among all the test cases. i can range from 0 to
00564   // total_test_case_count() - 1. If i is not in that range, returns NULL.
00565   const TestCase* GetTestCase(int i) const {
00566     const int index = GetElementOr(test_case_indices_, i, -1);
00567     return index < 0 ? NULL : test_cases_[i];
00568   }
00569 
00570   // Gets the i-th test case among all the test cases. i can range from 0 to
00571   // total_test_case_count() - 1. If i is not in that range, returns NULL.
00572   TestCase* GetMutableTestCase(int i) {
00573     const int index = GetElementOr(test_case_indices_, i, -1);
00574     return index < 0 ? NULL : test_cases_[index];
00575   }
00576 
00577   // Provides access to the event listener list.
00578   TestEventListeners* listeners() { return &listeners_; }
00579 
00580   // Returns the TestResult for the test that's currently running, or
00581   // the TestResult for the ad hoc test if no test is running.
00582   TestResult* current_test_result();
00583 
00584   // Returns the TestResult for the ad hoc test.
00585   const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; }
00586 
00587   // Sets the OS stack trace getter.
00588   //
00589   // Does nothing if the input and the current OS stack trace getter
00590   // are the same; otherwise, deletes the old getter and makes the
00591   // input the current getter.
00592   void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter);
00593 
00594   // Returns the current OS stack trace getter if it is not NULL;
00595   // otherwise, creates an OsStackTraceGetter, makes it the current
00596   // getter, and returns it.
00597   OsStackTraceGetterInterface* os_stack_trace_getter();
00598 
00599   // Returns the current OS stack trace as a String.
00600   //
00601   // The maximum number of stack frames to be included is specified by
00602   // the gtest_stack_trace_depth flag.  The skip_count parameter
00603   // specifies the number of top frames to be skipped, which doesn't
00604   // count against the number of frames to be included.
00605   //
00606   // For example, if Foo() calls Bar(), which in turn calls
00607   // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
00608   // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
00609   String CurrentOsStackTraceExceptTop(int skip_count);
00610 
00611   // Finds and returns a TestCase with the given name.  If one doesn't
00612   // exist, creates one and returns it.
00613   //
00614   // Arguments:
00615   //
00616   //   test_case_name: name of the test case
00617   //   type_param:     the name of the test's type parameter, or NULL if
00618   //                   this is not a typed or a type-parameterized test.
00619   //   set_up_tc:      pointer to the function that sets up the test case
00620   //   tear_down_tc:   pointer to the function that tears down the test case
00621   TestCase* GetTestCase(const char* test_case_name,
00622                         const char* type_param,
00623                         Test::SetUpTestCaseFunc set_up_tc,
00624                         Test::TearDownTestCaseFunc tear_down_tc);
00625 
00626   // Adds a TestInfo to the unit test.
00627   //
00628   // Arguments:
00629   //
00630   //   set_up_tc:    pointer to the function that sets up the test case
00631   //   tear_down_tc: pointer to the function that tears down the test case
00632   //   test_info:    the TestInfo object
00633   void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc,
00634                    Test::TearDownTestCaseFunc tear_down_tc,
00635                    TestInfo* test_info) {
00636     // In order to support thread-safe death tests, we need to
00637     // remember the original working directory when the test program
00638     // was first invoked.  We cannot do this in RUN_ALL_TESTS(), as
00639     // the user may have changed the current directory before calling
00640     // RUN_ALL_TESTS().  Therefore we capture the current directory in
00641     // AddTestInfo(), which is called to register a TEST or TEST_F
00642     // before main() is reached.
00643     if (original_working_dir_.IsEmpty()) {
00644       original_working_dir_.Set(FilePath::GetCurrentDir());
00645       GTEST_CHECK_(!original_working_dir_.IsEmpty())
00646           << "Failed to get the current working directory.";
00647     }
00648 
00649     GetTestCase(test_info->test_case_name(),
00650                 test_info->type_param(),
00651                 set_up_tc,
00652                 tear_down_tc)->AddTestInfo(test_info);
00653   }
00654 
00655 #if GTEST_HAS_PARAM_TEST
00656   // Returns ParameterizedTestCaseRegistry object used to keep track of
00657   // value-parameterized tests and instantiate and register them.
00658   internal::ParameterizedTestCaseRegistry& parameterized_test_registry() {
00659     return parameterized_test_registry_;
00660   }
00661 #endif  // GTEST_HAS_PARAM_TEST
00662 
00663   // Sets the TestCase object for the test that's currently running.
00664   void set_current_test_case(TestCase* a_current_test_case) {
00665     current_test_case_ = a_current_test_case;
00666   }
00667 
00668   // Sets the TestInfo object for the test that's currently running.  If
00669   // current_test_info is NULL, the assertion results will be stored in
00670   // ad_hoc_test_result_.
00671   void set_current_test_info(TestInfo* a_current_test_info) {
00672     current_test_info_ = a_current_test_info;
00673   }
00674 
00675   // Registers all parameterized tests defined using TEST_P and
00676   // INSTANTIATE_TEST_CASE_P, creating regular tests for each test/parameter
00677   // combination. This method can be called more then once; it has guards
00678   // protecting from registering the tests more then once.  If
00679   // value-parameterized tests are disabled, RegisterParameterizedTests is
00680   // present but does nothing.
00681   void RegisterParameterizedTests();
00682 
00683   // Runs all tests in this UnitTest object, prints the result, and
00684   // returns true if all tests are successful.  If any exception is
00685   // thrown during a test, this test is considered to be failed, but
00686   // the rest of the tests will still be run.
00687   bool RunAllTests();
00688 
00689   // Clears the results of all tests, except the ad hoc tests.
00690   void ClearNonAdHocTestResult() {
00691     ForEach(test_cases_, TestCase::ClearTestCaseResult);
00692   }
00693 
00694   // Clears the results of ad-hoc test assertions.
00695   void ClearAdHocTestResult() {
00696     ad_hoc_test_result_.Clear();
00697   }
00698 
00699   enum ReactionToSharding {
00700     HONOR_SHARDING_PROTOCOL,
00701     IGNORE_SHARDING_PROTOCOL
00702   };
00703 
00704   // Matches the full name of each test against the user-specified
00705   // filter to decide whether the test should run, then records the
00706   // result in each TestCase and TestInfo object.
00707   // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests
00708   // based on sharding variables in the environment.
00709   // Returns the number of tests that should run.
00710   int FilterTests(ReactionToSharding shard_tests);
00711 
00712   // Prints the names of the tests matching the user-specified filter flag.
00713   void ListTestsMatchingFilter();
00714 
00715   const TestCase* current_test_case() const { return current_test_case_; }
00716   TestInfo* current_test_info() { return current_test_info_; }
00717   const TestInfo* current_test_info() const { return current_test_info_; }
00718 
00719   // Returns the vector of environments that need to be set-up/torn-down
00720   // before/after the tests are run.
00721   std::vector<Environment*>& environments() { return environments_; }
00722 
00723   // Getters for the per-thread Google Test trace stack.
00724   std::vector<TraceInfo>& gtest_trace_stack() {
00725     return *(gtest_trace_stack_.pointer());
00726   }
00727   const std::vector<TraceInfo>& gtest_trace_stack() const {
00728     return gtest_trace_stack_.get();
00729   }
00730 
00731 #if GTEST_HAS_DEATH_TEST
00732   void InitDeathTestSubprocessControlInfo() {
00733     internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());
00734   }
00735   // Returns a pointer to the parsed --gtest_internal_run_death_test
00736   // flag, or NULL if that flag was not specified.
00737   // This information is useful only in a death test child process.
00738   // Must not be called before a call to InitGoogleTest.
00739   const InternalRunDeathTestFlag* internal_run_death_test_flag() const {
00740     return internal_run_death_test_flag_.get();
00741   }
00742 
00743   // Returns a pointer to the current death test factory.
00744   internal::DeathTestFactory* death_test_factory() {
00745     return death_test_factory_.get();
00746   }
00747 
00748   void SuppressTestEventsIfInSubprocess();
00749 
00750   friend class ReplaceDeathTestFactory;
00751 #endif  // GTEST_HAS_DEATH_TEST
00752 
00753   // Initializes the event listener performing XML output as specified by
00754   // UnitTestOptions. Must not be called before InitGoogleTest.
00755   void ConfigureXmlOutput();
00756 
00757 #if GTEST_CAN_STREAM_RESULTS_
00758   // Initializes the event listener for streaming test results to a socket.
00759   // Must not be called before InitGoogleTest.
00760   void ConfigureStreamingOutput();
00761 #endif
00762 
00763   // Performs initialization dependent upon flag values obtained in
00764   // ParseGoogleTestFlagsOnly.  Is called from InitGoogleTest after the call to
00765   // ParseGoogleTestFlagsOnly.  In case a user neglects to call InitGoogleTest
00766   // this function is also called from RunAllTests.  Since this function can be
00767   // called more than once, it has to be idempotent.
00768   void PostFlagParsingInit();
00769 
00770   // Gets the random seed used at the start of the current test iteration.
00771   int random_seed() const { return random_seed_; }
00772 
00773   // Gets the random number generator.
00774   internal::Random* random() { return &random_; }
00775 
00776   // Shuffles all test cases, and the tests within each test case,
00777   // making sure that death tests are still run first.
00778   void ShuffleTests();
00779 
00780   // Restores the test cases and tests to their order before the first shuffle.
00781   void UnshuffleTests();
00782 
00783   // Returns the value of GTEST_FLAG(catch_exceptions) at the moment
00784   // UnitTest::Run() starts.
00785   bool catch_exceptions() const { return catch_exceptions_; }
00786 
00787  private:
00788   friend class ::testing::UnitTest;
00789 
00790   // Used by UnitTest::Run() to capture the state of
00791   // GTEST_FLAG(catch_exceptions) at the moment it starts.
00792   void set_catch_exceptions(bool value) { catch_exceptions_ = value; }
00793 
00794   // The UnitTest object that owns this implementation object.
00795   UnitTest* const parent_;
00796 
00797   // The working directory when the first TEST() or TEST_F() was
00798   // executed.
00799   internal::FilePath original_working_dir_;
00800 
00801   // The default test part result reporters.
00802   DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_;
00803   DefaultPerThreadTestPartResultReporter
00804       default_per_thread_test_part_result_reporter_;
00805 
00806   // Points to (but doesn't own) the global test part result reporter.
00807   TestPartResultReporterInterface* global_test_part_result_repoter_;
00808 
00809   // Protects read and write access to global_test_part_result_reporter_.
00810   internal::Mutex global_test_part_result_reporter_mutex_;
00811 
00812   // Points to (but doesn't own) the per-thread test part result reporter.
00813   internal::ThreadLocal<TestPartResultReporterInterface*>
00814       per_thread_test_part_result_reporter_;
00815 
00816   // The vector of environments that need to be set-up/torn-down
00817   // before/after the tests are run.
00818   std::vector<Environment*> environments_;
00819 
00820   // The vector of TestCases in their original order.  It owns the
00821   // elements in the vector.
00822   std::vector<TestCase*> test_cases_;
00823 
00824   // Provides a level of indirection for the test case list to allow
00825   // easy shuffling and restoring the test case order.  The i-th
00826   // element of this vector is the index of the i-th test case in the
00827   // shuffled order.
00828   std::vector<int> test_case_indices_;
00829 
00830 #if GTEST_HAS_PARAM_TEST
00831   // ParameterizedTestRegistry object used to register value-parameterized
00832   // tests.
00833   internal::ParameterizedTestCaseRegistry parameterized_test_registry_;
00834 
00835   // Indicates whether RegisterParameterizedTests() has been called already.
00836   bool parameterized_tests_registered_;
00837 #endif  // GTEST_HAS_PARAM_TEST
00838 
00839   // Index of the last death test case registered.  Initially -1.
00840   int last_death_test_case_;
00841 
00842   // This points to the TestCase for the currently running test.  It
00843   // changes as Google Test goes through one test case after another.
00844   // When no test is running, this is set to NULL and Google Test
00845   // stores assertion results in ad_hoc_test_result_.  Initially NULL.
00846   TestCase* current_test_case_;
00847 
00848   // This points to the TestInfo for the currently running test.  It
00849   // changes as Google Test goes through one test after another.  When
00850   // no test is running, this is set to NULL and Google Test stores
00851   // assertion results in ad_hoc_test_result_.  Initially NULL.
00852   TestInfo* current_test_info_;
00853 
00854   // Normally, a user only writes assertions inside a TEST or TEST_F,
00855   // or inside a function called by a TEST or TEST_F.  Since Google
00856   // Test keeps track of which test is current running, it can
00857   // associate such an assertion with the test it belongs to.
00858   //
00859   // If an assertion is encountered when no TEST or TEST_F is running,
00860   // Google Test attributes the assertion result to an imaginary "ad hoc"
00861   // test, and records the result in ad_hoc_test_result_.
00862   TestResult ad_hoc_test_result_;
00863 
00864   // The list of event listeners that can be used to track events inside
00865   // Google Test.
00866   TestEventListeners listeners_;
00867 
00868   // The OS stack trace getter.  Will be deleted when the UnitTest
00869   // object is destructed.  By default, an OsStackTraceGetter is used,
00870   // but the user can set this field to use a custom getter if that is
00871   // desired.
00872   OsStackTraceGetterInterface* os_stack_trace_getter_;
00873 
00874   // True iff PostFlagParsingInit() has been called.
00875   bool post_flag_parse_init_performed_;
00876 
00877   // The random number seed used at the beginning of the test run.
00878   int random_seed_;
00879 
00880   // Our random number generator.
00881   internal::Random random_;
00882 
00883   // How long the test took to run, in milliseconds.
00884   TimeInMillis elapsed_time_;
00885 
00886 #if GTEST_HAS_DEATH_TEST
00887   // The decomposed components of the gtest_internal_run_death_test flag,
00888   // parsed when RUN_ALL_TESTS is called.
00889   internal::scoped_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;
00890   internal::scoped_ptr<internal::DeathTestFactory> death_test_factory_;
00891 #endif  // GTEST_HAS_DEATH_TEST
00892 
00893   // A per-thread stack of traces created by the SCOPED_TRACE() macro.
00894   internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_;
00895 
00896   // The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests()
00897   // starts.
00898   bool catch_exceptions_;
00899 
00900   GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl);
00901 };  // class UnitTestImpl
00902 
00903 // Convenience function for accessing the global UnitTest
00904 // implementation object.
00905 inline UnitTestImpl* GetUnitTestImpl() {
00906   return UnitTest::GetInstance()->impl();
00907 }
00908 
00909 #if GTEST_USES_SIMPLE_RE
00910 
00911 // Internal helper functions for implementing the simple regular
00912 // expression matcher.
00913 GTEST_API_ bool IsInSet(char ch, const char* str);
00914 GTEST_API_ bool IsAsciiDigit(char ch);
00915 GTEST_API_ bool IsAsciiPunct(char ch);
00916 GTEST_API_ bool IsRepeat(char ch);
00917 GTEST_API_ bool IsAsciiWhiteSpace(char ch);
00918 GTEST_API_ bool IsAsciiWordChar(char ch);
00919 GTEST_API_ bool IsValidEscape(char ch);
00920 GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch);
00921 GTEST_API_ bool ValidateRegex(const char* regex);
00922 GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str);
00923 GTEST_API_ bool MatchRepetitionAndRegexAtHead(
00924     bool escaped, char ch, char repeat, const char* regex, const char* str);
00925 GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str);
00926 
00927 #endif  // GTEST_USES_SIMPLE_RE
00928 
00929 // Parses the command line for Google Test flags, without initializing
00930 // other parts of Google Test.
00931 GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv);
00932 GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv);
00933 
00934 #if GTEST_HAS_DEATH_TEST
00935 
00936 // Returns the message describing the last system error, regardless of the
00937 // platform.
00938 GTEST_API_ String GetLastErrnoDescription();
00939 
00940 # if GTEST_OS_WINDOWS
00941 // Provides leak-safe Windows kernel handle ownership.
00942 class AutoHandle {
00943  public:
00944   AutoHandle() : handle_(INVALID_HANDLE_VALUE) {}
00945   explicit AutoHandle(HANDLE handle) : handle_(handle) {}
00946 
00947   ~AutoHandle() { Reset(); }
00948 
00949   HANDLE Get() const { return handle_; }
00950   void Reset() { Reset(INVALID_HANDLE_VALUE); }
00951   void Reset(HANDLE handle) {
00952     if (handle != handle_) {
00953       if (handle_ != INVALID_HANDLE_VALUE)
00954         ::CloseHandle(handle_);
00955       handle_ = handle;
00956     }
00957   }
00958 
00959  private:
00960   HANDLE handle_;
00961 
00962   GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle);
00963 };
00964 # endif  // GTEST_OS_WINDOWS
00965 
00966 // Attempts to parse a string into a positive integer pointed to by the
00967 // number parameter.  Returns true if that is possible.
00968 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use
00969 // it here.
00970 template <typename Integer>
00971 bool ParseNaturalNumber(const ::std::string& str, Integer* number) {
00972   // Fail fast if the given string does not begin with a digit;
00973   // this bypasses strtoXXX's "optional leading whitespace and plus
00974   // or minus sign" semantics, which are undesirable here.
00975   if (str.empty() || !IsDigit(str[0])) {
00976     return false;
00977   }
00978   errno = 0;
00979 
00980   char* end;
00981   // BiggestConvertible is the largest integer type that system-provided
00982   // string-to-number conversion routines can return.
00983 
00984 # if GTEST_OS_WINDOWS && !defined(__GNUC__)
00985 
00986   // MSVC and C++ Builder define __int64 instead of the standard long long.
00987   typedef unsigned __int64 BiggestConvertible;
00988   const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10);
00989 
00990 # else
00991 
00992   typedef unsigned long long BiggestConvertible;  // NOLINT
00993   const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10);
00994 
00995 # endif  // GTEST_OS_WINDOWS && !defined(__GNUC__)
00996 
00997   const bool parse_success = *end == '\0' && errno == 0;
00998 
00999   // TODO(vladl@google.com): Convert this to compile time assertion when it is
01000   // available.
01001   GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed));
01002 
01003   const Integer result = static_cast<Integer>(parsed);
01004   if (parse_success && static_cast<BiggestConvertible>(result) == parsed) {
01005     *number = result;
01006     return true;
01007   }
01008   return false;
01009 }
01010 #endif  // GTEST_HAS_DEATH_TEST
01011 
01012 // TestResult contains some private methods that should be hidden from
01013 // Google Test user but are required for testing. This class allow our tests
01014 // to access them.
01015 //
01016 // This class is supplied only for the purpose of testing Google Test's own
01017 // constructs. Do not use it in user tests, either directly or indirectly.
01018 class TestResultAccessor {
01019  public:
01020   static void RecordProperty(TestResult* test_result,
01021                              const TestProperty& property) {
01022     test_result->RecordProperty(property);
01023   }
01024 
01025   static void ClearTestPartResults(TestResult* test_result) {
01026     test_result->ClearTestPartResults();
01027   }
01028 
01029   static const std::vector<testing::TestPartResult>& test_part_results(
01030       const TestResult& test_result) {
01031     return test_result.test_part_results();
01032   }
01033 };
01034 
01035 }  // namespace internal
01036 }  // namespace testing
01037 
01038 #endif  // GTEST_SRC_GTEST_INTERNAL_INL_H_


pcl
Author(s): Open Perception
autogenerated on Wed Aug 26 2015 15:24:39