gtest-internal-inl.h 46 KB

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