gtest-internal-inl.h 47 KB

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