You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1038 lines
39 KiB

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