/thirdparty/breakpad/third_party/protobuf/protobuf/gtest/src/gtest-internal-inl.h

http://github.com/tomahawk-player/tomahawk · C++ Header · 1074 lines · 491 code · 181 blank · 402 comment · 22 complexity · 5d2751a593014a55e6b4e21ee43aa335 MD5 · raw file

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