gtest-internal-inl.h 45 KB

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