gtest-internal-inl.h 47 KB

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