Micro template library A library for building device drivers
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

11674 lines
428 KiB

  1. // Copyright 2008, 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. //
  30. // Google C++ Testing and Mocking Framework (Google Test)
  31. //
  32. // Sometimes it's desirable to build Google Test by compiling a single file.
  33. // This file serves this purpose.
  34. // This line ensures that gtest.h can be compiled on its own, even
  35. // when it's fused.
  36. #include "gtest.h"
  37. // The following lines pull in the real gtest *.cc files.
  38. // Copyright 2005, Google Inc.
  39. // All rights reserved.
  40. //
  41. // Redistribution and use in source and binary forms, with or without
  42. // modification, are permitted provided that the following conditions are
  43. // met:
  44. //
  45. // * Redistributions of source code must retain the above copyright
  46. // notice, this list of conditions and the following disclaimer.
  47. // * Redistributions in binary form must reproduce the above
  48. // copyright notice, this list of conditions and the following disclaimer
  49. // in the documentation and/or other materials provided with the
  50. // distribution.
  51. // * Neither the name of Google Inc. nor the names of its
  52. // contributors may be used to endorse or promote products derived from
  53. // this software without specific prior written permission.
  54. //
  55. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  56. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  57. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  58. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  59. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  60. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  61. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  62. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  63. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  64. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  65. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  66. //
  67. // The Google C++ Testing and Mocking Framework (Google Test)
  68. // Copyright 2007, Google Inc.
  69. // All rights reserved.
  70. //
  71. // Redistribution and use in source and binary forms, with or without
  72. // modification, are permitted provided that the following conditions are
  73. // met:
  74. //
  75. // * Redistributions of source code must retain the above copyright
  76. // notice, this list of conditions and the following disclaimer.
  77. // * Redistributions in binary form must reproduce the above
  78. // copyright notice, this list of conditions and the following disclaimer
  79. // in the documentation and/or other materials provided with the
  80. // distribution.
  81. // * Neither the name of Google Inc. nor the names of its
  82. // contributors may be used to endorse or promote products derived from
  83. // this software without specific prior written permission.
  84. //
  85. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  86. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  87. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  88. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  89. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  90. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  91. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  92. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  93. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  94. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  95. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  96. //
  97. // Utilities for testing Google Test itself and code that uses Google Test
  98. // (e.g. frameworks built on top of Google Test).
  99. // GOOGLETEST_CM0004 DO NOT DELETE
  100. #ifndef GTEST_INCLUDE_GTEST_GTEST_SPI_H_
  101. #define GTEST_INCLUDE_GTEST_GTEST_SPI_H_
  102. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
  103. /* class A needs to have dll-interface to be used by clients of class B */)
  104. namespace testing {
  105. // This helper class can be used to mock out Google Test failure reporting
  106. // so that we can test Google Test or code that builds on Google Test.
  107. //
  108. // An object of this class appends a TestPartResult object to the
  109. // TestPartResultArray object given in the constructor whenever a Google Test
  110. // failure is reported. It can either intercept only failures that are
  111. // generated in the same thread that created this object or it can intercept
  112. // all generated failures. The scope of this mock object can be controlled with
  113. // the second argument to the two arguments constructor.
  114. class GTEST_API_ ScopedFakeTestPartResultReporter
  115. : public TestPartResultReporterInterface {
  116. public:
  117. // The two possible mocking modes of this object.
  118. enum InterceptMode {
  119. INTERCEPT_ONLY_CURRENT_THREAD, // Intercepts only thread local failures.
  120. INTERCEPT_ALL_THREADS // Intercepts all failures.
  121. };
  122. // The c'tor sets this object as the test part result reporter used
  123. // by Google Test. The 'result' parameter specifies where to report the
  124. // results. This reporter will only catch failures generated in the current
  125. // thread. DEPRECATED
  126. explicit ScopedFakeTestPartResultReporter(TestPartResultArray* result);
  127. // Same as above, but you can choose the interception scope of this object.
  128. ScopedFakeTestPartResultReporter(InterceptMode intercept_mode,
  129. TestPartResultArray* result);
  130. // The d'tor restores the previous test part result reporter.
  131. ~ScopedFakeTestPartResultReporter() override;
  132. // Appends the TestPartResult object to the TestPartResultArray
  133. // received in the constructor.
  134. //
  135. // This method is from the TestPartResultReporterInterface
  136. // interface.
  137. void ReportTestPartResult(const TestPartResult& result) override;
  138. private:
  139. void Init();
  140. const InterceptMode intercept_mode_;
  141. TestPartResultReporterInterface* old_reporter_;
  142. TestPartResultArray* const result_;
  143. GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedFakeTestPartResultReporter);
  144. };
  145. namespace internal {
  146. // A helper class for implementing EXPECT_FATAL_FAILURE() and
  147. // EXPECT_NONFATAL_FAILURE(). Its destructor verifies that the given
  148. // TestPartResultArray contains exactly one failure that has the given
  149. // type and contains the given substring. If that's not the case, a
  150. // non-fatal failure will be generated.
  151. class GTEST_API_ SingleFailureChecker {
  152. public:
  153. // The constructor remembers the arguments.
  154. SingleFailureChecker(const TestPartResultArray* results,
  155. TestPartResult::Type type, const std::string& substr);
  156. ~SingleFailureChecker();
  157. private:
  158. const TestPartResultArray* const results_;
  159. const TestPartResult::Type type_;
  160. const std::string substr_;
  161. GTEST_DISALLOW_COPY_AND_ASSIGN_(SingleFailureChecker);
  162. };
  163. } // namespace internal
  164. } // namespace testing
  165. GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
  166. // A set of macros for testing Google Test assertions or code that's expected
  167. // to generate Google Test fatal failures. It verifies that the given
  168. // statement will cause exactly one fatal Google Test failure with 'substr'
  169. // being part of the failure message.
  170. //
  171. // There are two different versions of this macro. EXPECT_FATAL_FAILURE only
  172. // affects and considers failures generated in the current thread and
  173. // EXPECT_FATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
  174. //
  175. // The verification of the assertion is done correctly even when the statement
  176. // throws an exception or aborts the current function.
  177. //
  178. // Known restrictions:
  179. // - 'statement' cannot reference local non-static variables or
  180. // non-static members of the current object.
  181. // - 'statement' cannot return a value.
  182. // - You cannot stream a failure message to this macro.
  183. //
  184. // Note that even though the implementations of the following two
  185. // macros are much alike, we cannot refactor them to use a common
  186. // helper macro, due to some peculiarity in how the preprocessor
  187. // works. The AcceptsMacroThatExpandsToUnprotectedComma test in
  188. // gtest_unittest.cc will fail to compile if we do that.
  189. #define EXPECT_FATAL_FAILURE(statement, substr) \
  190. do { \
  191. class GTestExpectFatalFailureHelper {\
  192. public:\
  193. static void Execute() { statement; }\
  194. };\
  195. ::testing::TestPartResultArray gtest_failures;\
  196. ::testing::internal::SingleFailureChecker gtest_checker(\
  197. &gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
  198. {\
  199. ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
  200. ::testing::ScopedFakeTestPartResultReporter:: \
  201. INTERCEPT_ONLY_CURRENT_THREAD, &gtest_failures);\
  202. GTestExpectFatalFailureHelper::Execute();\
  203. }\
  204. } while (::testing::internal::AlwaysFalse())
  205. #define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
  206. do { \
  207. class GTestExpectFatalFailureHelper {\
  208. public:\
  209. static void Execute() { statement; }\
  210. };\
  211. ::testing::TestPartResultArray gtest_failures;\
  212. ::testing::internal::SingleFailureChecker gtest_checker(\
  213. &gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
  214. {\
  215. ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
  216. ::testing::ScopedFakeTestPartResultReporter:: \
  217. INTERCEPT_ALL_THREADS, &gtest_failures);\
  218. GTestExpectFatalFailureHelper::Execute();\
  219. }\
  220. } while (::testing::internal::AlwaysFalse())
  221. // A macro for testing Google Test assertions or code that's expected to
  222. // generate Google Test non-fatal failures. It asserts that the given
  223. // statement will cause exactly one non-fatal Google Test failure with 'substr'
  224. // being part of the failure message.
  225. //
  226. // There are two different versions of this macro. EXPECT_NONFATAL_FAILURE only
  227. // affects and considers failures generated in the current thread and
  228. // EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
  229. //
  230. // 'statement' is allowed to reference local variables and members of
  231. // the current object.
  232. //
  233. // The verification of the assertion is done correctly even when the statement
  234. // throws an exception or aborts the current function.
  235. //
  236. // Known restrictions:
  237. // - You cannot stream a failure message to this macro.
  238. //
  239. // Note that even though the implementations of the following two
  240. // macros are much alike, we cannot refactor them to use a common
  241. // helper macro, due to some peculiarity in how the preprocessor
  242. // works. If we do that, the code won't compile when the user gives
  243. // EXPECT_NONFATAL_FAILURE() a statement that contains a macro that
  244. // expands to code containing an unprotected comma. The
  245. // AcceptsMacroThatExpandsToUnprotectedComma test in gtest_unittest.cc
  246. // catches that.
  247. //
  248. // For the same reason, we have to write
  249. // if (::testing::internal::AlwaysTrue()) { statement; }
  250. // instead of
  251. // GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)
  252. // to avoid an MSVC warning on unreachable code.
  253. #define EXPECT_NONFATAL_FAILURE(statement, substr) \
  254. do {\
  255. ::testing::TestPartResultArray gtest_failures;\
  256. ::testing::internal::SingleFailureChecker gtest_checker(\
  257. &gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \
  258. (substr));\
  259. {\
  260. ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
  261. ::testing::ScopedFakeTestPartResultReporter:: \
  262. INTERCEPT_ONLY_CURRENT_THREAD, &gtest_failures);\
  263. if (::testing::internal::AlwaysTrue()) { statement; }\
  264. }\
  265. } while (::testing::internal::AlwaysFalse())
  266. #define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
  267. do {\
  268. ::testing::TestPartResultArray gtest_failures;\
  269. ::testing::internal::SingleFailureChecker gtest_checker(\
  270. &gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \
  271. (substr));\
  272. {\
  273. ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
  274. ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \
  275. &gtest_failures);\
  276. if (::testing::internal::AlwaysTrue()) { statement; }\
  277. }\
  278. } while (::testing::internal::AlwaysFalse())
  279. #endif // GTEST_INCLUDE_GTEST_GTEST_SPI_H_
  280. #include <ctype.h>
  281. #include <math.h>
  282. #include <stdarg.h>
  283. #include <stdio.h>
  284. #include <stdlib.h>
  285. #include <time.h>
  286. #include <wchar.h>
  287. #include <wctype.h>
  288. #include <algorithm>
  289. #include <iomanip>
  290. #include <limits>
  291. #include <list>
  292. #include <map>
  293. #include <ostream> // NOLINT
  294. #include <sstream>
  295. #include <vector>
  296. #if GTEST_OS_LINUX
  297. # define GTEST_HAS_GETTIMEOFDAY_ 1
  298. # include <fcntl.h> // NOLINT
  299. # include <limits.h> // NOLINT
  300. # include <sched.h> // NOLINT
  301. // Declares vsnprintf(). This header is not available on Windows.
  302. # include <strings.h> // NOLINT
  303. # include <sys/mman.h> // NOLINT
  304. # include <sys/time.h> // NOLINT
  305. # include <unistd.h> // NOLINT
  306. # include <string>
  307. #elif GTEST_OS_ZOS
  308. # define GTEST_HAS_GETTIMEOFDAY_ 1
  309. # include <sys/time.h> // NOLINT
  310. // On z/OS we additionally need strings.h for strcasecmp.
  311. # include <strings.h> // NOLINT
  312. #elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE.
  313. # include <windows.h> // NOLINT
  314. # undef min
  315. #elif GTEST_OS_WINDOWS // We are on Windows proper.
  316. # include <io.h> // NOLINT
  317. # include <sys/timeb.h> // NOLINT
  318. # include <sys/types.h> // NOLINT
  319. # include <sys/stat.h> // NOLINT
  320. # if GTEST_OS_WINDOWS_MINGW
  321. // MinGW has gettimeofday() but not _ftime64().
  322. # define GTEST_HAS_GETTIMEOFDAY_ 1
  323. # include <sys/time.h> // NOLINT
  324. # endif // GTEST_OS_WINDOWS_MINGW
  325. // cpplint thinks that the header is already included, so we want to
  326. // silence it.
  327. # include <windows.h> // NOLINT
  328. # undef min
  329. #else
  330. // Assume other platforms have gettimeofday().
  331. # define GTEST_HAS_GETTIMEOFDAY_ 1
  332. // cpplint thinks that the header is already included, so we want to
  333. // silence it.
  334. # include <sys/time.h> // NOLINT
  335. # include <unistd.h> // NOLINT
  336. #endif // GTEST_OS_LINUX
  337. #if GTEST_HAS_EXCEPTIONS
  338. # include <stdexcept>
  339. #endif
  340. #if GTEST_CAN_STREAM_RESULTS_
  341. # include <arpa/inet.h> // NOLINT
  342. # include <netdb.h> // NOLINT
  343. # include <sys/socket.h> // NOLINT
  344. # include <sys/types.h> // NOLINT
  345. #endif
  346. // Copyright 2005, Google Inc.
  347. // All rights reserved.
  348. //
  349. // Redistribution and use in source and binary forms, with or without
  350. // modification, are permitted provided that the following conditions are
  351. // met:
  352. //
  353. // * Redistributions of source code must retain the above copyright
  354. // notice, this list of conditions and the following disclaimer.
  355. // * Redistributions in binary form must reproduce the above
  356. // copyright notice, this list of conditions and the following disclaimer
  357. // in the documentation and/or other materials provided with the
  358. // distribution.
  359. // * Neither the name of Google Inc. nor the names of its
  360. // contributors may be used to endorse or promote products derived from
  361. // this software without specific prior written permission.
  362. //
  363. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  364. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  365. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  366. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  367. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  368. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  369. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  370. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  371. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  372. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  373. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  374. // Utility functions and classes used by the Google C++ testing framework.//
  375. // This file contains purely Google Test's internal implementation. Please
  376. // DO NOT #INCLUDE IT IN A USER PROGRAM.
  377. #ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_
  378. #define GTEST_SRC_GTEST_INTERNAL_INL_H_
  379. #ifndef _WIN32_WCE
  380. # include <errno.h>
  381. #endif // !_WIN32_WCE
  382. #include <stddef.h>
  383. #include <stdlib.h> // For strtoll/_strtoul64/malloc/free.
  384. #include <string.h> // For memmove.
  385. #include <algorithm>
  386. #include <memory>
  387. #include <string>
  388. #include <vector>
  389. #if GTEST_CAN_STREAM_RESULTS_
  390. # include <arpa/inet.h> // NOLINT
  391. # include <netdb.h> // NOLINT
  392. #endif
  393. #if GTEST_OS_WINDOWS
  394. # include <windows.h> // NOLINT
  395. #endif // GTEST_OS_WINDOWS
  396. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
  397. /* class A needs to have dll-interface to be used by clients of class B */)
  398. namespace testing {
  399. // Declares the flags.
  400. //
  401. // We don't want the users to modify this flag in the code, but want
  402. // Google Test's own unit tests to be able to access it. Therefore we
  403. // declare it here as opposed to in gtest.h.
  404. GTEST_DECLARE_bool_(death_test_use_fork);
  405. namespace internal {
  406. // The value of GetTestTypeId() as seen from within the Google Test
  407. // library. This is solely for testing GetTestTypeId().
  408. GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest;
  409. // Names of the flags (needed for parsing Google Test flags).
  410. const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests";
  411. const char kBreakOnFailureFlag[] = "break_on_failure";
  412. const char kCatchExceptionsFlag[] = "catch_exceptions";
  413. const char kColorFlag[] = "color";
  414. const char kFilterFlag[] = "filter";
  415. const char kListTestsFlag[] = "list_tests";
  416. const char kOutputFlag[] = "output";
  417. const char kPrintTimeFlag[] = "print_time";
  418. const char kPrintUTF8Flag[] = "print_utf8";
  419. const char kRandomSeedFlag[] = "random_seed";
  420. const char kRepeatFlag[] = "repeat";
  421. const char kShuffleFlag[] = "shuffle";
  422. const char kStackTraceDepthFlag[] = "stack_trace_depth";
  423. const char kStreamResultToFlag[] = "stream_result_to";
  424. const char kThrowOnFailureFlag[] = "throw_on_failure";
  425. const char kFlagfileFlag[] = "flagfile";
  426. // A valid random seed must be in [1, kMaxRandomSeed].
  427. const int kMaxRandomSeed = 99999;
  428. // g_help_flag is true iff the --help flag or an equivalent form is
  429. // specified on the command line.
  430. GTEST_API_ extern bool g_help_flag;
  431. // Returns the current time in milliseconds.
  432. GTEST_API_ TimeInMillis GetTimeInMillis();
  433. // Returns true iff Google Test should use colors in the output.
  434. GTEST_API_ bool ShouldUseColor(bool stdout_is_tty);
  435. // Formats the given time in milliseconds as seconds.
  436. GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms);
  437. // Converts the given time in milliseconds to a date string in the ISO 8601
  438. // format, without the timezone information. N.B.: due to the use the
  439. // non-reentrant localtime() function, this function is not thread safe. Do
  440. // not use it in any code that can be called from multiple threads.
  441. GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms);
  442. // Parses a string for an Int32 flag, in the form of "--flag=value".
  443. //
  444. // On success, stores the value of the flag in *value, and returns
  445. // true. On failure, returns false without changing *value.
  446. GTEST_API_ bool ParseInt32Flag(
  447. const char* str, const char* flag, Int32* value);
  448. // Returns a random seed in range [1, kMaxRandomSeed] based on the
  449. // given --gtest_random_seed flag value.
  450. inline int GetRandomSeedFromFlag(Int32 random_seed_flag) {
  451. const unsigned int raw_seed = (random_seed_flag == 0) ?
  452. static_cast<unsigned int>(GetTimeInMillis()) :
  453. static_cast<unsigned int>(random_seed_flag);
  454. // Normalizes the actual seed to range [1, kMaxRandomSeed] such that
  455. // it's easy to type.
  456. const int normalized_seed =
  457. static_cast<int>((raw_seed - 1U) %
  458. static_cast<unsigned int>(kMaxRandomSeed)) + 1;
  459. return normalized_seed;
  460. }
  461. // Returns the first valid random seed after 'seed'. The behavior is
  462. // undefined if 'seed' is invalid. The seed after kMaxRandomSeed is
  463. // considered to be 1.
  464. inline int GetNextRandomSeed(int seed) {
  465. GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed)
  466. << "Invalid random seed " << seed << " - must be in [1, "
  467. << kMaxRandomSeed << "].";
  468. const int next_seed = seed + 1;
  469. return (next_seed > kMaxRandomSeed) ? 1 : next_seed;
  470. }
  471. // This class saves the values of all Google Test flags in its c'tor, and
  472. // restores them in its d'tor.
  473. class GTestFlagSaver {
  474. public:
  475. // The c'tor.
  476. GTestFlagSaver() {
  477. also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests);
  478. break_on_failure_ = GTEST_FLAG(break_on_failure);
  479. catch_exceptions_ = GTEST_FLAG(catch_exceptions);
  480. color_ = GTEST_FLAG(color);
  481. death_test_style_ = GTEST_FLAG(death_test_style);
  482. death_test_use_fork_ = GTEST_FLAG(death_test_use_fork);
  483. filter_ = GTEST_FLAG(filter);
  484. internal_run_death_test_ = GTEST_FLAG(internal_run_death_test);
  485. list_tests_ = GTEST_FLAG(list_tests);
  486. output_ = GTEST_FLAG(output);
  487. print_time_ = GTEST_FLAG(print_time);
  488. print_utf8_ = GTEST_FLAG(print_utf8);
  489. random_seed_ = GTEST_FLAG(random_seed);
  490. repeat_ = GTEST_FLAG(repeat);
  491. shuffle_ = GTEST_FLAG(shuffle);
  492. stack_trace_depth_ = GTEST_FLAG(stack_trace_depth);
  493. stream_result_to_ = GTEST_FLAG(stream_result_to);
  494. throw_on_failure_ = GTEST_FLAG(throw_on_failure);
  495. }
  496. // The d'tor is not virtual. DO NOT INHERIT FROM THIS CLASS.
  497. ~GTestFlagSaver() {
  498. GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_;
  499. GTEST_FLAG(break_on_failure) = break_on_failure_;
  500. GTEST_FLAG(catch_exceptions) = catch_exceptions_;
  501. GTEST_FLAG(color) = color_;
  502. GTEST_FLAG(death_test_style) = death_test_style_;
  503. GTEST_FLAG(death_test_use_fork) = death_test_use_fork_;
  504. GTEST_FLAG(filter) = filter_;
  505. GTEST_FLAG(internal_run_death_test) = internal_run_death_test_;
  506. GTEST_FLAG(list_tests) = list_tests_;
  507. GTEST_FLAG(output) = output_;
  508. GTEST_FLAG(print_time) = print_time_;
  509. GTEST_FLAG(print_utf8) = print_utf8_;
  510. GTEST_FLAG(random_seed) = random_seed_;
  511. GTEST_FLAG(repeat) = repeat_;
  512. GTEST_FLAG(shuffle) = shuffle_;
  513. GTEST_FLAG(stack_trace_depth) = stack_trace_depth_;
  514. GTEST_FLAG(stream_result_to) = stream_result_to_;
  515. GTEST_FLAG(throw_on_failure) = throw_on_failure_;
  516. }
  517. private:
  518. // Fields for saving the original values of flags.
  519. bool also_run_disabled_tests_;
  520. bool break_on_failure_;
  521. bool catch_exceptions_;
  522. std::string color_;
  523. std::string death_test_style_;
  524. bool death_test_use_fork_;
  525. std::string filter_;
  526. std::string internal_run_death_test_;
  527. bool list_tests_;
  528. std::string output_;
  529. bool print_time_;
  530. bool print_utf8_;
  531. internal::Int32 random_seed_;
  532. internal::Int32 repeat_;
  533. bool shuffle_;
  534. internal::Int32 stack_trace_depth_;
  535. std::string stream_result_to_;
  536. bool throw_on_failure_;
  537. } GTEST_ATTRIBUTE_UNUSED_;
  538. // Converts a Unicode code point to a narrow string in UTF-8 encoding.
  539. // code_point parameter is of type UInt32 because wchar_t may not be
  540. // wide enough to contain a code point.
  541. // If the code_point is not a valid Unicode code point
  542. // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
  543. // to "(Invalid Unicode 0xXXXXXXXX)".
  544. GTEST_API_ std::string CodePointToUtf8(UInt32 code_point);
  545. // Converts a wide string to a narrow string in UTF-8 encoding.
  546. // The wide string is assumed to have the following encoding:
  547. // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin)
  548. // UTF-32 if sizeof(wchar_t) == 4 (on Linux)
  549. // Parameter str points to a null-terminated wide string.
  550. // Parameter num_chars may additionally limit the number
  551. // of wchar_t characters processed. -1 is used when the entire string
  552. // should be processed.
  553. // If the string contains code points that are not valid Unicode code points
  554. // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
  555. // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
  556. // and contains invalid UTF-16 surrogate pairs, values in those pairs
  557. // will be encoded as individual Unicode characters from Basic Normal Plane.
  558. GTEST_API_ std::string WideStringToUtf8(const wchar_t* str, int num_chars);
  559. // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
  560. // if the variable is present. If a file already exists at this location, this
  561. // function will write over it. If the variable is present, but the file cannot
  562. // be created, prints an error and exits.
  563. void WriteToShardStatusFileIfNeeded();
  564. // Checks whether sharding is enabled by examining the relevant
  565. // environment variable values. If the variables are present,
  566. // but inconsistent (e.g., shard_index >= total_shards), prints
  567. // an error and exits. If in_subprocess_for_death_test, sharding is
  568. // disabled because it must only be applied to the original test
  569. // process. Otherwise, we could filter out death tests we intended to execute.
  570. GTEST_API_ bool ShouldShard(const char* total_shards_str,
  571. const char* shard_index_str,
  572. bool in_subprocess_for_death_test);
  573. // Parses the environment variable var as an Int32. If it is unset,
  574. // returns default_val. If it is not an Int32, prints an error and
  575. // and aborts.
  576. GTEST_API_ Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val);
  577. // Given the total number of shards, the shard index, and the test id,
  578. // returns true iff the test should be run on this shard. The test id is
  579. // some arbitrary but unique non-negative integer assigned to each test
  580. // method. Assumes that 0 <= shard_index < total_shards.
  581. GTEST_API_ bool ShouldRunTestOnShard(
  582. int total_shards, int shard_index, int test_id);
  583. // STL container utilities.
  584. // Returns the number of elements in the given container that satisfy
  585. // the given predicate.
  586. template <class Container, typename Predicate>
  587. inline int CountIf(const Container& c, Predicate predicate) {
  588. // Implemented as an explicit loop since std::count_if() in libCstd on
  589. // Solaris has a non-standard signature.
  590. int count = 0;
  591. for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) {
  592. if (predicate(*it))
  593. ++count;
  594. }
  595. return count;
  596. }
  597. // Applies a function/functor to each element in the container.
  598. template <class Container, typename Functor>
  599. void ForEach(const Container& c, Functor functor) {
  600. std::for_each(c.begin(), c.end(), functor);
  601. }
  602. // Returns the i-th element of the vector, or default_value if i is not
  603. // in range [0, v.size()).
  604. template <typename E>
  605. inline E GetElementOr(const std::vector<E>& v, int i, E default_value) {
  606. return (i < 0 || i >= static_cast<int>(v.size())) ? default_value : v[i];
  607. }
  608. // Performs an in-place shuffle of a range of the vector's elements.
  609. // 'begin' and 'end' are element indices as an STL-style range;
  610. // i.e. [begin, end) are shuffled, where 'end' == size() means to
  611. // shuffle to the end of the vector.
  612. template <typename E>
  613. void ShuffleRange(internal::Random* random, int begin, int end,
  614. std::vector<E>* v) {
  615. const int size = static_cast<int>(v->size());
  616. GTEST_CHECK_(0 <= begin && begin <= size)
  617. << "Invalid shuffle range start " << begin << ": must be in range [0, "
  618. << size << "].";
  619. GTEST_CHECK_(begin <= end && end <= size)
  620. << "Invalid shuffle range finish " << end << ": must be in range ["
  621. << begin << ", " << size << "].";
  622. // Fisher-Yates shuffle, from
  623. // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
  624. for (int range_width = end - begin; range_width >= 2; range_width--) {
  625. const int last_in_range = begin + range_width - 1;
  626. const int selected = begin + random->Generate(range_width);
  627. std::swap((*v)[selected], (*v)[last_in_range]);
  628. }
  629. }
  630. // Performs an in-place shuffle of the vector's elements.
  631. template <typename E>
  632. inline void Shuffle(internal::Random* random, std::vector<E>* v) {
  633. ShuffleRange(random, 0, static_cast<int>(v->size()), v);
  634. }
  635. // A function for deleting an object. Handy for being used as a
  636. // functor.
  637. template <typename T>
  638. static void Delete(T* x) {
  639. delete x;
  640. }
  641. // A predicate that checks the key of a TestProperty against a known key.
  642. //
  643. // TestPropertyKeyIs is copyable.
  644. class TestPropertyKeyIs {
  645. public:
  646. // Constructor.
  647. //
  648. // TestPropertyKeyIs has NO default constructor.
  649. explicit TestPropertyKeyIs(const std::string& key) : key_(key) {}
  650. // Returns true iff the test name of test property matches on key_.
  651. bool operator()(const TestProperty& test_property) const {
  652. return test_property.key() == key_;
  653. }
  654. private:
  655. std::string key_;
  656. };
  657. // Class UnitTestOptions.
  658. //
  659. // This class contains functions for processing options the user
  660. // specifies when running the tests. It has only static members.
  661. //
  662. // In most cases, the user can specify an option using either an
  663. // environment variable or a command line flag. E.g. you can set the
  664. // test filter using either GTEST_FILTER or --gtest_filter. If both
  665. // the variable and the flag are present, the latter overrides the
  666. // former.
  667. class GTEST_API_ UnitTestOptions {
  668. public:
  669. // Functions for processing the gtest_output flag.
  670. // Returns the output format, or "" for normal printed output.
  671. static std::string GetOutputFormat();
  672. // Returns the absolute path of the requested output file, or the
  673. // default (test_detail.xml in the original working directory) if
  674. // none was explicitly specified.
  675. static std::string GetAbsolutePathToOutputFile();
  676. // Functions for processing the gtest_filter flag.
  677. // Returns true iff the wildcard pattern matches the string. The
  678. // first ':' or '\0' character in pattern marks the end of it.
  679. //
  680. // This recursive algorithm isn't very efficient, but is clear and
  681. // works well enough for matching test names, which are short.
  682. static bool PatternMatchesString(const char *pattern, const char *str);
  683. // Returns true iff the user-specified filter matches the test suite
  684. // name and the test name.
  685. static bool FilterMatchesTest(const std::string& test_suite_name,
  686. const std::string& test_name);
  687. #if GTEST_OS_WINDOWS
  688. // Function for supporting the gtest_catch_exception flag.
  689. // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
  690. // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
  691. // This function is useful as an __except condition.
  692. static int GTestShouldProcessSEH(DWORD exception_code);
  693. #endif // GTEST_OS_WINDOWS
  694. // Returns true if "name" matches the ':' separated list of glob-style
  695. // filters in "filter".
  696. static bool MatchesFilter(const std::string& name, const char* filter);
  697. };
  698. // Returns the current application's name, removing directory path if that
  699. // is present. Used by UnitTestOptions::GetOutputFile.
  700. GTEST_API_ FilePath GetCurrentExecutableName();
  701. // The role interface for getting the OS stack trace as a string.
  702. class OsStackTraceGetterInterface {
  703. public:
  704. OsStackTraceGetterInterface() {}
  705. virtual ~OsStackTraceGetterInterface() {}
  706. // Returns the current OS stack trace as an std::string. Parameters:
  707. //
  708. // max_depth - the maximum number of stack frames to be included
  709. // in the trace.
  710. // skip_count - the number of top frames to be skipped; doesn't count
  711. // against max_depth.
  712. virtual std::string CurrentStackTrace(int max_depth, int skip_count) = 0;
  713. // UponLeavingGTest() should be called immediately before Google Test calls
  714. // user code. It saves some information about the current stack that
  715. // CurrentStackTrace() will use to find and hide Google Test stack frames.
  716. virtual void UponLeavingGTest() = 0;
  717. // This string is inserted in place of stack frames that are part of
  718. // Google Test's implementation.
  719. static const char* const kElidedFramesMarker;
  720. private:
  721. GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface);
  722. };
  723. // A working implementation of the OsStackTraceGetterInterface interface.
  724. class OsStackTraceGetter : public OsStackTraceGetterInterface {
  725. public:
  726. OsStackTraceGetter() {}
  727. std::string CurrentStackTrace(int max_depth, int skip_count) override;
  728. void UponLeavingGTest() override;
  729. private:
  730. #if GTEST_HAS_ABSL
  731. Mutex mutex_; // Protects all internal state.
  732. // We save the stack frame below the frame that calls user code.
  733. // We do this because the address of the frame immediately below
  734. // the user code changes between the call to UponLeavingGTest()
  735. // and any calls to the stack trace code from within the user code.
  736. void* caller_frame_ = nullptr;
  737. #endif // GTEST_HAS_ABSL
  738. GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter);
  739. };
  740. // Information about a Google Test trace point.
  741. struct TraceInfo {
  742. const char* file;
  743. int line;
  744. std::string message;
  745. };
  746. // This is the default global test part result reporter used in UnitTestImpl.
  747. // This class should only be used by UnitTestImpl.
  748. class DefaultGlobalTestPartResultReporter
  749. : public TestPartResultReporterInterface {
  750. public:
  751. explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test);
  752. // Implements the TestPartResultReporterInterface. Reports the test part
  753. // result in the current test.
  754. void ReportTestPartResult(const TestPartResult& result) override;
  755. private:
  756. UnitTestImpl* const unit_test_;
  757. GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter);
  758. };
  759. // This is the default per thread test part result reporter used in
  760. // UnitTestImpl. This class should only be used by UnitTestImpl.
  761. class DefaultPerThreadTestPartResultReporter
  762. : public TestPartResultReporterInterface {
  763. public:
  764. explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test);
  765. // Implements the TestPartResultReporterInterface. The implementation just
  766. // delegates to the current global test part result reporter of *unit_test_.
  767. void ReportTestPartResult(const TestPartResult& result) override;
  768. private:
  769. UnitTestImpl* const unit_test_;
  770. GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter);
  771. };
  772. // The private implementation of the UnitTest class. We don't protect
  773. // the methods under a mutex, as this class is not accessible by a
  774. // user and the UnitTest class that delegates work to this class does
  775. // proper locking.
  776. class GTEST_API_ UnitTestImpl {
  777. public:
  778. explicit UnitTestImpl(UnitTest* parent);
  779. virtual ~UnitTestImpl();
  780. // There are two different ways to register your own TestPartResultReporter.
  781. // You can register your own repoter to listen either only for test results
  782. // from the current thread or for results from all threads.
  783. // By default, each per-thread test result repoter just passes a new
  784. // TestPartResult to the global test result reporter, which registers the
  785. // test part result for the currently running test.
  786. // Returns the global test part result reporter.
  787. TestPartResultReporterInterface* GetGlobalTestPartResultReporter();
  788. // Sets the global test part result reporter.
  789. void SetGlobalTestPartResultReporter(
  790. TestPartResultReporterInterface* reporter);
  791. // Returns the test part result reporter for the current thread.
  792. TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread();
  793. // Sets the test part result reporter for the current thread.
  794. void SetTestPartResultReporterForCurrentThread(
  795. TestPartResultReporterInterface* reporter);
  796. // Gets the number of successful test suites.
  797. int successful_test_suite_count() const;
  798. // Gets the number of failed test suites.
  799. int failed_test_suite_count() const;
  800. // Gets the number of all test suites.
  801. int total_test_suite_count() const;
  802. // Gets the number of all test suites that contain at least one test
  803. // that should run.
  804. int test_suite_to_run_count() const;
  805. // Gets the number of successful tests.
  806. int successful_test_count() const;
  807. // Gets the number of skipped tests.
  808. int skipped_test_count() const;
  809. // Gets the number of failed tests.
  810. int failed_test_count() const;
  811. // Gets the number of disabled tests that will be reported in the XML report.
  812. int reportable_disabled_test_count() const;
  813. // Gets the number of disabled tests.
  814. int disabled_test_count() const;
  815. // Gets the number of tests to be printed in the XML report.
  816. int reportable_test_count() const;
  817. // Gets the number of all tests.
  818. int total_test_count() const;
  819. // Gets the number of tests that should run.
  820. int test_to_run_count() const;
  821. // Gets the time of the test program start, in ms from the start of the
  822. // UNIX epoch.
  823. TimeInMillis start_timestamp() const { return start_timestamp_; }
  824. // Gets the elapsed time, in milliseconds.
  825. TimeInMillis elapsed_time() const { return elapsed_time_; }
  826. // Returns true iff the unit test passed (i.e. all test suites passed).
  827. bool Passed() const { return !Failed(); }
  828. // Returns true iff the unit test failed (i.e. some test suite failed
  829. // or something outside of all tests failed).
  830. bool Failed() const {
  831. return failed_test_suite_count() > 0 || ad_hoc_test_result()->Failed();
  832. }
  833. // Gets the i-th test suite among all the test suites. i can range from 0 to
  834. // total_test_suite_count() - 1. If i is not in that range, returns NULL.
  835. const TestSuite* GetTestSuite(int i) const {
  836. const int index = GetElementOr(test_suite_indices_, i, -1);
  837. return index < 0 ? nullptr : test_suites_[i];
  838. }
  839. // Legacy API is deprecated but still available
  840. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  841. const TestCase* GetTestCase(int i) const { return GetTestSuite(i); }
  842. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  843. // Gets the i-th test suite among all the test suites. i can range from 0 to
  844. // total_test_suite_count() - 1. If i is not in that range, returns NULL.
  845. TestSuite* GetMutableSuiteCase(int i) {
  846. const int index = GetElementOr(test_suite_indices_, i, -1);
  847. return index < 0 ? nullptr : test_suites_[index];
  848. }
  849. // Provides access to the event listener list.
  850. TestEventListeners* listeners() { return &listeners_; }
  851. // Returns the TestResult for the test that's currently running, or
  852. // the TestResult for the ad hoc test if no test is running.
  853. TestResult* current_test_result();
  854. // Returns the TestResult for the ad hoc test.
  855. const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; }
  856. // Sets the OS stack trace getter.
  857. //
  858. // Does nothing if the input and the current OS stack trace getter
  859. // are the same; otherwise, deletes the old getter and makes the
  860. // input the current getter.
  861. void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter);
  862. // Returns the current OS stack trace getter if it is not NULL;
  863. // otherwise, creates an OsStackTraceGetter, makes it the current
  864. // getter, and returns it.
  865. OsStackTraceGetterInterface* os_stack_trace_getter();
  866. // Returns the current OS stack trace as an std::string.
  867. //
  868. // The maximum number of stack frames to be included is specified by
  869. // the gtest_stack_trace_depth flag. The skip_count parameter
  870. // specifies the number of top frames to be skipped, which doesn't
  871. // count against the number of frames to be included.
  872. //
  873. // For example, if Foo() calls Bar(), which in turn calls
  874. // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
  875. // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
  876. std::string CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_;
  877. // Finds and returns a TestSuite with the given name. If one doesn't
  878. // exist, creates one and returns it.
  879. //
  880. // Arguments:
  881. //
  882. // test_suite_name: name of the test suite
  883. // type_param: the name of the test's type parameter, or NULL if
  884. // this is not a typed or a type-parameterized test.
  885. // set_up_tc: pointer to the function that sets up the test suite
  886. // tear_down_tc: pointer to the function that tears down the test suite
  887. TestSuite* GetTestSuite(const char* test_suite_name, const char* type_param,
  888. internal::SetUpTestSuiteFunc set_up_tc,
  889. internal::TearDownTestSuiteFunc tear_down_tc);
  890. // Legacy API is deprecated but still available
  891. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  892. TestCase* GetTestCase(const char* test_case_name, const char* type_param,
  893. internal::SetUpTestSuiteFunc set_up_tc,
  894. internal::TearDownTestSuiteFunc tear_down_tc) {
  895. return GetTestSuite(test_case_name, type_param, set_up_tc, tear_down_tc);
  896. }
  897. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  898. // Adds a TestInfo to the unit test.
  899. //
  900. // Arguments:
  901. //
  902. // set_up_tc: pointer to the function that sets up the test suite
  903. // tear_down_tc: pointer to the function that tears down the test suite
  904. // test_info: the TestInfo object
  905. void AddTestInfo(internal::SetUpTestSuiteFunc set_up_tc,
  906. internal::TearDownTestSuiteFunc tear_down_tc,
  907. TestInfo* test_info) {
  908. // In order to support thread-safe death tests, we need to
  909. // remember the original working directory when the test program
  910. // was first invoked. We cannot do this in RUN_ALL_TESTS(), as
  911. // the user may have changed the current directory before calling
  912. // RUN_ALL_TESTS(). Therefore we capture the current directory in
  913. // AddTestInfo(), which is called to register a TEST or TEST_F
  914. // before main() is reached.
  915. if (original_working_dir_.IsEmpty()) {
  916. original_working_dir_.Set(FilePath::GetCurrentDir());
  917. GTEST_CHECK_(!original_working_dir_.IsEmpty())
  918. << "Failed to get the current working directory.";
  919. }
  920. GetTestSuite(test_info->test_suite_name(), test_info->type_param(),
  921. set_up_tc, tear_down_tc)
  922. ->AddTestInfo(test_info);
  923. }
  924. // Returns ParameterizedTestSuiteRegistry object used to keep track of
  925. // value-parameterized tests and instantiate and register them.
  926. internal::ParameterizedTestSuiteRegistry& parameterized_test_registry() {
  927. return parameterized_test_registry_;
  928. }
  929. // Sets the TestSuite object for the test that's currently running.
  930. void set_current_test_suite(TestSuite* a_current_test_suite) {
  931. current_test_suite_ = a_current_test_suite;
  932. }
  933. // Sets the TestInfo object for the test that's currently running. If
  934. // current_test_info is NULL, the assertion results will be stored in
  935. // ad_hoc_test_result_.
  936. void set_current_test_info(TestInfo* a_current_test_info) {
  937. current_test_info_ = a_current_test_info;
  938. }
  939. // Registers all parameterized tests defined using TEST_P and
  940. // INSTANTIATE_TEST_SUITE_P, creating regular tests for each test/parameter
  941. // combination. This method can be called more then once; it has guards
  942. // protecting from registering the tests more then once. If
  943. // value-parameterized tests are disabled, RegisterParameterizedTests is
  944. // present but does nothing.
  945. void RegisterParameterizedTests();
  946. // Runs all tests in this UnitTest object, prints the result, and
  947. // returns true if all tests are successful. If any exception is
  948. // thrown during a test, this test is considered to be failed, but
  949. // the rest of the tests will still be run.
  950. bool RunAllTests();
  951. // Clears the results of all tests, except the ad hoc tests.
  952. void ClearNonAdHocTestResult() {
  953. ForEach(test_suites_, TestSuite::ClearTestSuiteResult);
  954. }
  955. // Clears the results of ad-hoc test assertions.
  956. void ClearAdHocTestResult() {
  957. ad_hoc_test_result_.Clear();
  958. }
  959. // Adds a TestProperty to the current TestResult object when invoked in a
  960. // context of a test or a test suite, or to the global property set. If the
  961. // result already contains a property with the same key, the value will be
  962. // updated.
  963. void RecordProperty(const TestProperty& test_property);
  964. enum ReactionToSharding {
  965. HONOR_SHARDING_PROTOCOL,
  966. IGNORE_SHARDING_PROTOCOL
  967. };
  968. // Matches the full name of each test against the user-specified
  969. // filter to decide whether the test should run, then records the
  970. // result in each TestSuite and TestInfo object.
  971. // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests
  972. // based on sharding variables in the environment.
  973. // Returns the number of tests that should run.
  974. int FilterTests(ReactionToSharding shard_tests);
  975. // Prints the names of the tests matching the user-specified filter flag.
  976. void ListTestsMatchingFilter();
  977. const TestSuite* current_test_suite() const { return current_test_suite_; }
  978. TestInfo* current_test_info() { return current_test_info_; }
  979. const TestInfo* current_test_info() const { return current_test_info_; }
  980. // Returns the vector of environments that need to be set-up/torn-down
  981. // before/after the tests are run.
  982. std::vector<Environment*>& environments() { return environments_; }
  983. // Getters for the per-thread Google Test trace stack.
  984. std::vector<TraceInfo>& gtest_trace_stack() {
  985. return *(gtest_trace_stack_.pointer());
  986. }
  987. const std::vector<TraceInfo>& gtest_trace_stack() const {
  988. return gtest_trace_stack_.get();
  989. }
  990. #if GTEST_HAS_DEATH_TEST
  991. void InitDeathTestSubprocessControlInfo() {
  992. internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());
  993. }
  994. // Returns a pointer to the parsed --gtest_internal_run_death_test
  995. // flag, or NULL if that flag was not specified.
  996. // This information is useful only in a death test child process.
  997. // Must not be called before a call to InitGoogleTest.
  998. const InternalRunDeathTestFlag* internal_run_death_test_flag() const {
  999. return internal_run_death_test_flag_.get();
  1000. }
  1001. // Returns a pointer to the current death test factory.
  1002. internal::DeathTestFactory* death_test_factory() {
  1003. return death_test_factory_.get();
  1004. }
  1005. void SuppressTestEventsIfInSubprocess();
  1006. friend class ReplaceDeathTestFactory;
  1007. #endif // GTEST_HAS_DEATH_TEST
  1008. // Initializes the event listener performing XML output as specified by
  1009. // UnitTestOptions. Must not be called before InitGoogleTest.
  1010. void ConfigureXmlOutput();
  1011. #if GTEST_CAN_STREAM_RESULTS_
  1012. // Initializes the event listener for streaming test results to a socket.
  1013. // Must not be called before InitGoogleTest.
  1014. void ConfigureStreamingOutput();
  1015. #endif
  1016. // Performs initialization dependent upon flag values obtained in
  1017. // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
  1018. // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
  1019. // this function is also called from RunAllTests. Since this function can be
  1020. // called more than once, it has to be idempotent.
  1021. void PostFlagParsingInit();
  1022. // Gets the random seed used at the start of the current test iteration.
  1023. int random_seed() const { return random_seed_; }
  1024. // Gets the random number generator.
  1025. internal::Random* random() { return &random_; }
  1026. // Shuffles all test suites, and the tests within each test suite,
  1027. // making sure that death tests are still run first.
  1028. void ShuffleTests();
  1029. // Restores the test suites and tests to their order before the first shuffle.
  1030. void UnshuffleTests();
  1031. // Returns the value of GTEST_FLAG(catch_exceptions) at the moment
  1032. // UnitTest::Run() starts.
  1033. bool catch_exceptions() const { return catch_exceptions_; }
  1034. private:
  1035. friend class ::testing::UnitTest;
  1036. // Used by UnitTest::Run() to capture the state of
  1037. // GTEST_FLAG(catch_exceptions) at the moment it starts.
  1038. void set_catch_exceptions(bool value) { catch_exceptions_ = value; }
  1039. // The UnitTest object that owns this implementation object.
  1040. UnitTest* const parent_;
  1041. // The working directory when the first TEST() or TEST_F() was
  1042. // executed.
  1043. internal::FilePath original_working_dir_;
  1044. // The default test part result reporters.
  1045. DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_;
  1046. DefaultPerThreadTestPartResultReporter
  1047. default_per_thread_test_part_result_reporter_;
  1048. // Points to (but doesn't own) the global test part result reporter.
  1049. TestPartResultReporterInterface* global_test_part_result_repoter_;
  1050. // Protects read and write access to global_test_part_result_reporter_.
  1051. internal::Mutex global_test_part_result_reporter_mutex_;
  1052. // Points to (but doesn't own) the per-thread test part result reporter.
  1053. internal::ThreadLocal<TestPartResultReporterInterface*>
  1054. per_thread_test_part_result_reporter_;
  1055. // The vector of environments that need to be set-up/torn-down
  1056. // before/after the tests are run.
  1057. std::vector<Environment*> environments_;
  1058. // The vector of TestSuites in their original order. It owns the
  1059. // elements in the vector.
  1060. std::vector<TestSuite*> test_suites_;
  1061. // Provides a level of indirection for the test suite list to allow
  1062. // easy shuffling and restoring the test suite order. The i-th
  1063. // element of this vector is the index of the i-th test suite in the
  1064. // shuffled order.
  1065. std::vector<int> test_suite_indices_;
  1066. // ParameterizedTestRegistry object used to register value-parameterized
  1067. // tests.
  1068. internal::ParameterizedTestSuiteRegistry parameterized_test_registry_;
  1069. // Indicates whether RegisterParameterizedTests() has been called already.
  1070. bool parameterized_tests_registered_;
  1071. // Index of the last death test suite registered. Initially -1.
  1072. int last_death_test_suite_;
  1073. // This points to the TestSuite for the currently running test. It
  1074. // changes as Google Test goes through one test suite after another.
  1075. // When no test is running, this is set to NULL and Google Test
  1076. // stores assertion results in ad_hoc_test_result_. Initially NULL.
  1077. TestSuite* current_test_suite_;
  1078. // This points to the TestInfo for the currently running test. It
  1079. // changes as Google Test goes through one test after another. When
  1080. // no test is running, this is set to NULL and Google Test stores
  1081. // assertion results in ad_hoc_test_result_. Initially NULL.
  1082. TestInfo* current_test_info_;
  1083. // Normally, a user only writes assertions inside a TEST or TEST_F,
  1084. // or inside a function called by a TEST or TEST_F. Since Google
  1085. // Test keeps track of which test is current running, it can
  1086. // associate such an assertion with the test it belongs to.
  1087. //
  1088. // If an assertion is encountered when no TEST or TEST_F is running,
  1089. // Google Test attributes the assertion result to an imaginary "ad hoc"
  1090. // test, and records the result in ad_hoc_test_result_.
  1091. TestResult ad_hoc_test_result_;
  1092. // The list of event listeners that can be used to track events inside
  1093. // Google Test.
  1094. TestEventListeners listeners_;
  1095. // The OS stack trace getter. Will be deleted when the UnitTest
  1096. // object is destructed. By default, an OsStackTraceGetter is used,
  1097. // but the user can set this field to use a custom getter if that is
  1098. // desired.
  1099. OsStackTraceGetterInterface* os_stack_trace_getter_;
  1100. // True iff PostFlagParsingInit() has been called.
  1101. bool post_flag_parse_init_performed_;
  1102. // The random number seed used at the beginning of the test run.
  1103. int random_seed_;
  1104. // Our random number generator.
  1105. internal::Random random_;
  1106. // The time of the test program start, in ms from the start of the
  1107. // UNIX epoch.
  1108. TimeInMillis start_timestamp_;
  1109. // How long the test took to run, in milliseconds.
  1110. TimeInMillis elapsed_time_;
  1111. #if GTEST_HAS_DEATH_TEST
  1112. // The decomposed components of the gtest_internal_run_death_test flag,
  1113. // parsed when RUN_ALL_TESTS is called.
  1114. std::unique_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;
  1115. std::unique_ptr<internal::DeathTestFactory> death_test_factory_;
  1116. #endif // GTEST_HAS_DEATH_TEST
  1117. // A per-thread stack of traces created by the SCOPED_TRACE() macro.
  1118. internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_;
  1119. // The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests()
  1120. // starts.
  1121. bool catch_exceptions_;
  1122. GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl);
  1123. }; // class UnitTestImpl
  1124. // Convenience function for accessing the global UnitTest
  1125. // implementation object.
  1126. inline UnitTestImpl* GetUnitTestImpl() {
  1127. return UnitTest::GetInstance()->impl();
  1128. }
  1129. #if GTEST_USES_SIMPLE_RE
  1130. // Internal helper functions for implementing the simple regular
  1131. // expression matcher.
  1132. GTEST_API_ bool IsInSet(char ch, const char* str);
  1133. GTEST_API_ bool IsAsciiDigit(char ch);
  1134. GTEST_API_ bool IsAsciiPunct(char ch);
  1135. GTEST_API_ bool IsRepeat(char ch);
  1136. GTEST_API_ bool IsAsciiWhiteSpace(char ch);
  1137. GTEST_API_ bool IsAsciiWordChar(char ch);
  1138. GTEST_API_ bool IsValidEscape(char ch);
  1139. GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch);
  1140. GTEST_API_ bool ValidateRegex(const char* regex);
  1141. GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str);
  1142. GTEST_API_ bool MatchRepetitionAndRegexAtHead(
  1143. bool escaped, char ch, char repeat, const char* regex, const char* str);
  1144. GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str);
  1145. #endif // GTEST_USES_SIMPLE_RE
  1146. // Parses the command line for Google Test flags, without initializing
  1147. // other parts of Google Test.
  1148. GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv);
  1149. GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv);
  1150. #if GTEST_HAS_DEATH_TEST
  1151. // Returns the message describing the last system error, regardless of the
  1152. // platform.
  1153. GTEST_API_ std::string GetLastErrnoDescription();
  1154. // Attempts to parse a string into a positive integer pointed to by the
  1155. // number parameter. Returns true if that is possible.
  1156. // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use
  1157. // it here.
  1158. template <typename Integer>
  1159. bool ParseNaturalNumber(const ::std::string& str, Integer* number) {
  1160. // Fail fast if the given string does not begin with a digit;
  1161. // this bypasses strtoXXX's "optional leading whitespace and plus
  1162. // or minus sign" semantics, which are undesirable here.
  1163. if (str.empty() || !IsDigit(str[0])) {
  1164. return false;
  1165. }
  1166. errno = 0;
  1167. char* end;
  1168. // BiggestConvertible is the largest integer type that system-provided
  1169. // string-to-number conversion routines can return.
  1170. # if GTEST_OS_WINDOWS && !defined(__GNUC__)
  1171. // MSVC and C++ Builder define __int64 instead of the standard long long.
  1172. typedef unsigned __int64 BiggestConvertible;
  1173. const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10);
  1174. # else
  1175. typedef unsigned long long BiggestConvertible; // NOLINT
  1176. const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10);
  1177. # endif // GTEST_OS_WINDOWS && !defined(__GNUC__)
  1178. const bool parse_success = *end == '\0' && errno == 0;
  1179. GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed));
  1180. const Integer result = static_cast<Integer>(parsed);
  1181. if (parse_success && static_cast<BiggestConvertible>(result) == parsed) {
  1182. *number = result;
  1183. return true;
  1184. }
  1185. return false;
  1186. }
  1187. #endif // GTEST_HAS_DEATH_TEST
  1188. // TestResult contains some private methods that should be hidden from
  1189. // Google Test user but are required for testing. This class allow our tests
  1190. // to access them.
  1191. //
  1192. // This class is supplied only for the purpose of testing Google Test's own
  1193. // constructs. Do not use it in user tests, either directly or indirectly.
  1194. class TestResultAccessor {
  1195. public:
  1196. static void RecordProperty(TestResult* test_result,
  1197. const std::string& xml_element,
  1198. const TestProperty& property) {
  1199. test_result->RecordProperty(xml_element, property);
  1200. }
  1201. static void ClearTestPartResults(TestResult* test_result) {
  1202. test_result->ClearTestPartResults();
  1203. }
  1204. static const std::vector<testing::TestPartResult>& test_part_results(
  1205. const TestResult& test_result) {
  1206. return test_result.test_part_results();
  1207. }
  1208. };
  1209. #if GTEST_CAN_STREAM_RESULTS_
  1210. // Streams test results to the given port on the given host machine.
  1211. class StreamingListener : public EmptyTestEventListener {
  1212. public:
  1213. // Abstract base class for writing strings to a socket.
  1214. class AbstractSocketWriter {
  1215. public:
  1216. virtual ~AbstractSocketWriter() {}
  1217. // Sends a string to the socket.
  1218. virtual void Send(const std::string& message) = 0;
  1219. // Closes the socket.
  1220. virtual void CloseConnection() {}
  1221. // Sends a string and a newline to the socket.
  1222. void SendLn(const std::string& message) { Send(message + "\n"); }
  1223. };
  1224. // Concrete class for actually writing strings to a socket.
  1225. class SocketWriter : public AbstractSocketWriter {
  1226. public:
  1227. SocketWriter(const std::string& host, const std::string& port)
  1228. : sockfd_(-1), host_name_(host), port_num_(port) {
  1229. MakeConnection();
  1230. }
  1231. ~SocketWriter() override {
  1232. if (sockfd_ != -1)
  1233. CloseConnection();
  1234. }
  1235. // Sends a string to the socket.
  1236. void Send(const std::string& message) override {
  1237. GTEST_CHECK_(sockfd_ != -1)
  1238. << "Send() can be called only when there is a connection.";
  1239. const int len = static_cast<int>(message.length());
  1240. if (write(sockfd_, message.c_str(), len) != len) {
  1241. GTEST_LOG_(WARNING)
  1242. << "stream_result_to: failed to stream to "
  1243. << host_name_ << ":" << port_num_;
  1244. }
  1245. }
  1246. private:
  1247. // Creates a client socket and connects to the server.
  1248. void MakeConnection();
  1249. // Closes the socket.
  1250. void CloseConnection() override {
  1251. GTEST_CHECK_(sockfd_ != -1)
  1252. << "CloseConnection() can be called only when there is a connection.";
  1253. close(sockfd_);
  1254. sockfd_ = -1;
  1255. }
  1256. int sockfd_; // socket file descriptor
  1257. const std::string host_name_;
  1258. const std::string port_num_;
  1259. GTEST_DISALLOW_COPY_AND_ASSIGN_(SocketWriter);
  1260. }; // class SocketWriter
  1261. // Escapes '=', '&', '%', and '\n' characters in str as "%xx".
  1262. static std::string UrlEncode(const char* str);
  1263. StreamingListener(const std::string& host, const std::string& port)
  1264. : socket_writer_(new SocketWriter(host, port)) {
  1265. Start();
  1266. }
  1267. explicit StreamingListener(AbstractSocketWriter* socket_writer)
  1268. : socket_writer_(socket_writer) { Start(); }
  1269. void OnTestProgramStart(const UnitTest& /* unit_test */) override {
  1270. SendLn("event=TestProgramStart");
  1271. }
  1272. void OnTestProgramEnd(const UnitTest& unit_test) override {
  1273. // Note that Google Test current only report elapsed time for each
  1274. // test iteration, not for the entire test program.
  1275. SendLn("event=TestProgramEnd&passed=" + FormatBool(unit_test.Passed()));
  1276. // Notify the streaming server to stop.
  1277. socket_writer_->CloseConnection();
  1278. }
  1279. void OnTestIterationStart(const UnitTest& /* unit_test */,
  1280. int iteration) override {
  1281. SendLn("event=TestIterationStart&iteration=" +
  1282. StreamableToString(iteration));
  1283. }
  1284. void OnTestIterationEnd(const UnitTest& unit_test,
  1285. int /* iteration */) override {
  1286. SendLn("event=TestIterationEnd&passed=" +
  1287. FormatBool(unit_test.Passed()) + "&elapsed_time=" +
  1288. StreamableToString(unit_test.elapsed_time()) + "ms");
  1289. }
  1290. // Note that "event=TestCaseStart" is a wire format and has to remain
  1291. // "case" for compatibilty
  1292. void OnTestCaseStart(const TestCase& test_case) override {
  1293. SendLn(std::string("event=TestCaseStart&name=") + test_case.name());
  1294. }
  1295. // Note that "event=TestCaseEnd" is a wire format and has to remain
  1296. // "case" for compatibilty
  1297. void OnTestCaseEnd(const TestCase& test_case) override {
  1298. SendLn("event=TestCaseEnd&passed=" + FormatBool(test_case.Passed()) +
  1299. "&elapsed_time=" + StreamableToString(test_case.elapsed_time()) +
  1300. "ms");
  1301. }
  1302. void OnTestStart(const TestInfo& test_info) override {
  1303. SendLn(std::string("event=TestStart&name=") + test_info.name());
  1304. }
  1305. void OnTestEnd(const TestInfo& test_info) override {
  1306. SendLn("event=TestEnd&passed=" +
  1307. FormatBool((test_info.result())->Passed()) +
  1308. "&elapsed_time=" +
  1309. StreamableToString((test_info.result())->elapsed_time()) + "ms");
  1310. }
  1311. void OnTestPartResult(const TestPartResult& test_part_result) override {
  1312. const char* file_name = test_part_result.file_name();
  1313. if (file_name == nullptr) file_name = "";
  1314. SendLn("event=TestPartResult&file=" + UrlEncode(file_name) +
  1315. "&line=" + StreamableToString(test_part_result.line_number()) +
  1316. "&message=" + UrlEncode(test_part_result.message()));
  1317. }
  1318. private:
  1319. // Sends the given message and a newline to the socket.
  1320. void SendLn(const std::string& message) { socket_writer_->SendLn(message); }
  1321. // Called at the start of streaming to notify the receiver what
  1322. // protocol we are using.
  1323. void Start() { SendLn("gtest_streaming_protocol_version=1.0"); }
  1324. std::string FormatBool(bool value) { return value ? "1" : "0"; }
  1325. const std::unique_ptr<AbstractSocketWriter> socket_writer_;
  1326. GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener);
  1327. }; // class StreamingListener
  1328. #endif // GTEST_CAN_STREAM_RESULTS_
  1329. } // namespace internal
  1330. } // namespace testing
  1331. GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
  1332. #endif // GTEST_SRC_GTEST_INTERNAL_INL_H_
  1333. #if GTEST_OS_WINDOWS
  1334. # define vsnprintf _vsnprintf
  1335. #endif // GTEST_OS_WINDOWS
  1336. #if GTEST_OS_MAC
  1337. #ifndef GTEST_OS_IOS
  1338. #include <crt_externs.h>
  1339. #endif
  1340. #endif
  1341. #if GTEST_HAS_ABSL
  1342. #include "absl/debugging/failure_signal_handler.h"
  1343. #include "absl/debugging/stacktrace.h"
  1344. #include "absl/debugging/symbolize.h"
  1345. #include "absl/strings/str_cat.h"
  1346. #endif // GTEST_HAS_ABSL
  1347. namespace testing {
  1348. using internal::CountIf;
  1349. using internal::ForEach;
  1350. using internal::GetElementOr;
  1351. using internal::Shuffle;
  1352. // Constants.
  1353. // A test whose test suite name or test name matches this filter is
  1354. // disabled and not run.
  1355. static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
  1356. // A test suite whose name matches this filter is considered a death
  1357. // test suite and will be run before test suites whose name doesn't
  1358. // match this filter.
  1359. static const char kDeathTestSuiteFilter[] = "*DeathTest:*DeathTest/*";
  1360. // A test filter that matches everything.
  1361. static const char kUniversalFilter[] = "*";
  1362. // The default output format.
  1363. static const char kDefaultOutputFormat[] = "xml";
  1364. // The default output file.
  1365. static const char kDefaultOutputFile[] = "test_detail";
  1366. // The environment variable name for the test shard index.
  1367. static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
  1368. // The environment variable name for the total number of test shards.
  1369. static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
  1370. // The environment variable name for the test shard status file.
  1371. static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
  1372. namespace internal {
  1373. // The text used in failure messages to indicate the start of the
  1374. // stack trace.
  1375. const char kStackTraceMarker[] = "\nStack trace:\n";
  1376. // g_help_flag is true iff the --help flag or an equivalent form is
  1377. // specified on the command line.
  1378. bool g_help_flag = false;
  1379. // Utilty function to Open File for Writing
  1380. static FILE* OpenFileForWriting(const std::string& output_file) {
  1381. FILE* fileout = nullptr;
  1382. FilePath output_file_path(output_file);
  1383. FilePath output_dir(output_file_path.RemoveFileName());
  1384. if (output_dir.CreateDirectoriesRecursively()) {
  1385. fileout = posix::FOpen(output_file.c_str(), "w");
  1386. }
  1387. if (fileout == nullptr) {
  1388. GTEST_LOG_(FATAL) << "Unable to open file \"" << output_file << "\"";
  1389. }
  1390. return fileout;
  1391. }
  1392. } // namespace internal
  1393. // Bazel passes in the argument to '--test_filter' via the TESTBRIDGE_TEST_ONLY
  1394. // environment variable.
  1395. static const char* GetDefaultFilter() {
  1396. const char* const testbridge_test_only =
  1397. internal::posix::GetEnv("TESTBRIDGE_TEST_ONLY");
  1398. if (testbridge_test_only != nullptr) {
  1399. return testbridge_test_only;
  1400. }
  1401. return kUniversalFilter;
  1402. }
  1403. GTEST_DEFINE_bool_(
  1404. also_run_disabled_tests,
  1405. internal::BoolFromGTestEnv("also_run_disabled_tests", false),
  1406. "Run disabled tests too, in addition to the tests normally being run.");
  1407. GTEST_DEFINE_bool_(
  1408. break_on_failure,
  1409. internal::BoolFromGTestEnv("break_on_failure", false),
  1410. "True iff a failed assertion should be a debugger break-point.");
  1411. GTEST_DEFINE_bool_(
  1412. catch_exceptions,
  1413. internal::BoolFromGTestEnv("catch_exceptions", true),
  1414. "True iff " GTEST_NAME_
  1415. " should catch exceptions and treat them as test failures.");
  1416. GTEST_DEFINE_string_(
  1417. color,
  1418. internal::StringFromGTestEnv("color", "auto"),
  1419. "Whether to use colors in the output. Valid values: yes, no, "
  1420. "and auto. 'auto' means to use colors if the output is "
  1421. "being sent to a terminal and the TERM environment variable "
  1422. "is set to a terminal type that supports colors.");
  1423. GTEST_DEFINE_string_(
  1424. filter,
  1425. internal::StringFromGTestEnv("filter", GetDefaultFilter()),
  1426. "A colon-separated list of glob (not regex) patterns "
  1427. "for filtering the tests to run, optionally followed by a "
  1428. "'-' and a : separated list of negative patterns (tests to "
  1429. "exclude). A test is run if it matches one of the positive "
  1430. "patterns and does not match any of the negative patterns.");
  1431. GTEST_DEFINE_bool_(
  1432. install_failure_signal_handler,
  1433. internal::BoolFromGTestEnv("install_failure_signal_handler", false),
  1434. "If true and supported on the current platform, " GTEST_NAME_ " should "
  1435. "install a signal handler that dumps debugging information when fatal "
  1436. "signals are raised.");
  1437. GTEST_DEFINE_bool_(list_tests, false,
  1438. "List all tests without running them.");
  1439. // The net priority order after flag processing is thus:
  1440. // --gtest_output command line flag
  1441. // GTEST_OUTPUT environment variable
  1442. // XML_OUTPUT_FILE environment variable
  1443. // ''
  1444. GTEST_DEFINE_string_(
  1445. output,
  1446. internal::StringFromGTestEnv("output",
  1447. internal::OutputFlagAlsoCheckEnvVar().c_str()),
  1448. "A format (defaults to \"xml\" but can be specified to be \"json\"), "
  1449. "optionally followed by a colon and an output file name or directory. "
  1450. "A directory is indicated by a trailing pathname separator. "
  1451. "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
  1452. "If a directory is specified, output files will be created "
  1453. "within that directory, with file-names based on the test "
  1454. "executable's name and, if necessary, made unique by adding "
  1455. "digits.");
  1456. GTEST_DEFINE_bool_(
  1457. print_time,
  1458. internal::BoolFromGTestEnv("print_time", true),
  1459. "True iff " GTEST_NAME_
  1460. " should display elapsed time in text output.");
  1461. GTEST_DEFINE_bool_(
  1462. print_utf8,
  1463. internal::BoolFromGTestEnv("print_utf8", true),
  1464. "True iff " GTEST_NAME_
  1465. " prints UTF8 characters as text.");
  1466. GTEST_DEFINE_int32_(
  1467. random_seed,
  1468. internal::Int32FromGTestEnv("random_seed", 0),
  1469. "Random number seed to use when shuffling test orders. Must be in range "
  1470. "[1, 99999], or 0 to use a seed based on the current time.");
  1471. GTEST_DEFINE_int32_(
  1472. repeat,
  1473. internal::Int32FromGTestEnv("repeat", 1),
  1474. "How many times to repeat each test. Specify a negative number "
  1475. "for repeating forever. Useful for shaking out flaky tests.");
  1476. GTEST_DEFINE_bool_(
  1477. show_internal_stack_frames, false,
  1478. "True iff " GTEST_NAME_ " should include internal stack frames when "
  1479. "printing test failure stack traces.");
  1480. GTEST_DEFINE_bool_(
  1481. shuffle,
  1482. internal::BoolFromGTestEnv("shuffle", false),
  1483. "True iff " GTEST_NAME_
  1484. " should randomize tests' order on every run.");
  1485. GTEST_DEFINE_int32_(
  1486. stack_trace_depth,
  1487. internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
  1488. "The maximum number of stack frames to print when an "
  1489. "assertion fails. The valid range is 0 through 100, inclusive.");
  1490. GTEST_DEFINE_string_(
  1491. stream_result_to,
  1492. internal::StringFromGTestEnv("stream_result_to", ""),
  1493. "This flag specifies the host name and the port number on which to stream "
  1494. "test results. Example: \"localhost:555\". The flag is effective only on "
  1495. "Linux.");
  1496. GTEST_DEFINE_bool_(
  1497. throw_on_failure,
  1498. internal::BoolFromGTestEnv("throw_on_failure", false),
  1499. "When this flag is specified, a failed assertion will throw an exception "
  1500. "if exceptions are enabled or exit the program with a non-zero code "
  1501. "otherwise. For use with an external test framework.");
  1502. #if GTEST_USE_OWN_FLAGFILE_FLAG_
  1503. GTEST_DEFINE_string_(
  1504. flagfile,
  1505. internal::StringFromGTestEnv("flagfile", ""),
  1506. "This flag specifies the flagfile to read command-line flags from.");
  1507. #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
  1508. namespace internal {
  1509. // Generates a random number from [0, range), using a Linear
  1510. // Congruential Generator (LCG). Crashes if 'range' is 0 or greater
  1511. // than kMaxRange.
  1512. UInt32 Random::Generate(UInt32 range) {
  1513. // These constants are the same as are used in glibc's rand(3).
  1514. // Use wider types than necessary to prevent unsigned overflow diagnostics.
  1515. state_ = static_cast<UInt32>(1103515245ULL*state_ + 12345U) % kMaxRange;
  1516. GTEST_CHECK_(range > 0)
  1517. << "Cannot generate a number in the range [0, 0).";
  1518. GTEST_CHECK_(range <= kMaxRange)
  1519. << "Generation of a number in [0, " << range << ") was requested, "
  1520. << "but this can only generate numbers in [0, " << kMaxRange << ").";
  1521. // Converting via modulus introduces a bit of downward bias, but
  1522. // it's simple, and a linear congruential generator isn't too good
  1523. // to begin with.
  1524. return state_ % range;
  1525. }
  1526. // GTestIsInitialized() returns true iff the user has initialized
  1527. // Google Test. Useful for catching the user mistake of not initializing
  1528. // Google Test before calling RUN_ALL_TESTS().
  1529. static bool GTestIsInitialized() { return GetArgvs().size() > 0; }
  1530. // Iterates over a vector of TestSuites, keeping a running sum of the
  1531. // results of calling a given int-returning method on each.
  1532. // Returns the sum.
  1533. static int SumOverTestSuiteList(const std::vector<TestSuite*>& case_list,
  1534. int (TestSuite::*method)() const) {
  1535. int sum = 0;
  1536. for (size_t i = 0; i < case_list.size(); i++) {
  1537. sum += (case_list[i]->*method)();
  1538. }
  1539. return sum;
  1540. }
  1541. // Returns true iff the test suite passed.
  1542. static bool TestSuitePassed(const TestSuite* test_suite) {
  1543. return test_suite->should_run() && test_suite->Passed();
  1544. }
  1545. // Returns true iff the test suite failed.
  1546. static bool TestSuiteFailed(const TestSuite* test_suite) {
  1547. return test_suite->should_run() && test_suite->Failed();
  1548. }
  1549. // Returns true iff test_suite contains at least one test that should
  1550. // run.
  1551. static bool ShouldRunTestSuite(const TestSuite* test_suite) {
  1552. return test_suite->should_run();
  1553. }
  1554. // AssertHelper constructor.
  1555. AssertHelper::AssertHelper(TestPartResult::Type type,
  1556. const char* file,
  1557. int line,
  1558. const char* message)
  1559. : data_(new AssertHelperData(type, file, line, message)) {
  1560. }
  1561. AssertHelper::~AssertHelper() {
  1562. delete data_;
  1563. }
  1564. // Message assignment, for assertion streaming support.
  1565. void AssertHelper::operator=(const Message& message) const {
  1566. UnitTest::GetInstance()->
  1567. AddTestPartResult(data_->type, data_->file, data_->line,
  1568. AppendUserMessage(data_->message, message),
  1569. UnitTest::GetInstance()->impl()
  1570. ->CurrentOsStackTraceExceptTop(1)
  1571. // Skips the stack frame for this function itself.
  1572. ); // NOLINT
  1573. }
  1574. // A copy of all command line arguments. Set by InitGoogleTest().
  1575. static ::std::vector<std::string> g_argvs;
  1576. ::std::vector<std::string> GetArgvs() {
  1577. #if defined(GTEST_CUSTOM_GET_ARGVS_)
  1578. // GTEST_CUSTOM_GET_ARGVS_() may return a container of std::string or
  1579. // ::string. This code converts it to the appropriate type.
  1580. const auto& custom = GTEST_CUSTOM_GET_ARGVS_();
  1581. return ::std::vector<std::string>(custom.begin(), custom.end());
  1582. #else // defined(GTEST_CUSTOM_GET_ARGVS_)
  1583. return g_argvs;
  1584. #endif // defined(GTEST_CUSTOM_GET_ARGVS_)
  1585. }
  1586. // Returns the current application's name, removing directory path if that
  1587. // is present.
  1588. FilePath GetCurrentExecutableName() {
  1589. FilePath result;
  1590. #if GTEST_OS_WINDOWS || GTEST_OS_OS2
  1591. result.Set(FilePath(GetArgvs()[0]).RemoveExtension("exe"));
  1592. #else
  1593. result.Set(FilePath(GetArgvs()[0]));
  1594. #endif // GTEST_OS_WINDOWS
  1595. return result.RemoveDirectoryName();
  1596. }
  1597. // Functions for processing the gtest_output flag.
  1598. // Returns the output format, or "" for normal printed output.
  1599. std::string UnitTestOptions::GetOutputFormat() {
  1600. const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
  1601. const char* const colon = strchr(gtest_output_flag, ':');
  1602. return (colon == nullptr)
  1603. ? std::string(gtest_output_flag)
  1604. : std::string(gtest_output_flag, colon - gtest_output_flag);
  1605. }
  1606. // Returns the name of the requested output file, or the default if none
  1607. // was explicitly specified.
  1608. std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
  1609. const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
  1610. std::string format = GetOutputFormat();
  1611. if (format.empty())
  1612. format = std::string(kDefaultOutputFormat);
  1613. const char* const colon = strchr(gtest_output_flag, ':');
  1614. if (colon == nullptr)
  1615. return internal::FilePath::MakeFileName(
  1616. internal::FilePath(
  1617. UnitTest::GetInstance()->original_working_dir()),
  1618. internal::FilePath(kDefaultOutputFile), 0,
  1619. format.c_str()).string();
  1620. internal::FilePath output_name(colon + 1);
  1621. if (!output_name.IsAbsolutePath())
  1622. output_name = internal::FilePath::ConcatPaths(
  1623. internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
  1624. internal::FilePath(colon + 1));
  1625. if (!output_name.IsDirectory())
  1626. return output_name.string();
  1627. internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
  1628. output_name, internal::GetCurrentExecutableName(),
  1629. GetOutputFormat().c_str()));
  1630. return result.string();
  1631. }
  1632. // Returns true iff the wildcard pattern matches the string. The
  1633. // first ':' or '\0' character in pattern marks the end of it.
  1634. //
  1635. // This recursive algorithm isn't very efficient, but is clear and
  1636. // works well enough for matching test names, which are short.
  1637. bool UnitTestOptions::PatternMatchesString(const char *pattern,
  1638. const char *str) {
  1639. switch (*pattern) {
  1640. case '\0':
  1641. case ':': // Either ':' or '\0' marks the end of the pattern.
  1642. return *str == '\0';
  1643. case '?': // Matches any single character.
  1644. return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);
  1645. case '*': // Matches any string (possibly empty) of characters.
  1646. return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||
  1647. PatternMatchesString(pattern + 1, str);
  1648. default: // Non-special character. Matches itself.
  1649. return *pattern == *str &&
  1650. PatternMatchesString(pattern + 1, str + 1);
  1651. }
  1652. }
  1653. bool UnitTestOptions::MatchesFilter(
  1654. const std::string& name, const char* filter) {
  1655. const char *cur_pattern = filter;
  1656. for (;;) {
  1657. if (PatternMatchesString(cur_pattern, name.c_str())) {
  1658. return true;
  1659. }
  1660. // Finds the next pattern in the filter.
  1661. cur_pattern = strchr(cur_pattern, ':');
  1662. // Returns if no more pattern can be found.
  1663. if (cur_pattern == nullptr) {
  1664. return false;
  1665. }
  1666. // Skips the pattern separater (the ':' character).
  1667. cur_pattern++;
  1668. }
  1669. }
  1670. // Returns true iff the user-specified filter matches the test suite
  1671. // name and the test name.
  1672. bool UnitTestOptions::FilterMatchesTest(const std::string& test_suite_name,
  1673. const std::string& test_name) {
  1674. const std::string& full_name = test_suite_name + "." + test_name.c_str();
  1675. // Split --gtest_filter at '-', if there is one, to separate into
  1676. // positive filter and negative filter portions
  1677. const char* const p = GTEST_FLAG(filter).c_str();
  1678. const char* const dash = strchr(p, '-');
  1679. std::string positive;
  1680. std::string negative;
  1681. if (dash == nullptr) {
  1682. positive = GTEST_FLAG(filter).c_str(); // Whole string is a positive filter
  1683. negative = "";
  1684. } else {
  1685. positive = std::string(p, dash); // Everything up to the dash
  1686. negative = std::string(dash + 1); // Everything after the dash
  1687. if (positive.empty()) {
  1688. // Treat '-test1' as the same as '*-test1'
  1689. positive = kUniversalFilter;
  1690. }
  1691. }
  1692. // A filter is a colon-separated list of patterns. It matches a
  1693. // test if any pattern in it matches the test.
  1694. return (MatchesFilter(full_name, positive.c_str()) &&
  1695. !MatchesFilter(full_name, negative.c_str()));
  1696. }
  1697. #if GTEST_HAS_SEH
  1698. // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
  1699. // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
  1700. // This function is useful as an __except condition.
  1701. int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
  1702. // Google Test should handle a SEH exception if:
  1703. // 1. the user wants it to, AND
  1704. // 2. this is not a breakpoint exception, AND
  1705. // 3. this is not a C++ exception (VC++ implements them via SEH,
  1706. // apparently).
  1707. //
  1708. // SEH exception code for C++ exceptions.
  1709. // (see http://support.microsoft.com/kb/185294 for more information).
  1710. const DWORD kCxxExceptionCode = 0xe06d7363;
  1711. bool should_handle = true;
  1712. if (!GTEST_FLAG(catch_exceptions))
  1713. should_handle = false;
  1714. else if (exception_code == EXCEPTION_BREAKPOINT)
  1715. should_handle = false;
  1716. else if (exception_code == kCxxExceptionCode)
  1717. should_handle = false;
  1718. return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
  1719. }
  1720. #endif // GTEST_HAS_SEH
  1721. } // namespace internal
  1722. // The c'tor sets this object as the test part result reporter used by
  1723. // Google Test. The 'result' parameter specifies where to report the
  1724. // results. Intercepts only failures from the current thread.
  1725. ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
  1726. TestPartResultArray* result)
  1727. : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
  1728. result_(result) {
  1729. Init();
  1730. }
  1731. // The c'tor sets this object as the test part result reporter used by
  1732. // Google Test. The 'result' parameter specifies where to report the
  1733. // results.
  1734. ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
  1735. InterceptMode intercept_mode, TestPartResultArray* result)
  1736. : intercept_mode_(intercept_mode),
  1737. result_(result) {
  1738. Init();
  1739. }
  1740. void ScopedFakeTestPartResultReporter::Init() {
  1741. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  1742. if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
  1743. old_reporter_ = impl->GetGlobalTestPartResultReporter();
  1744. impl->SetGlobalTestPartResultReporter(this);
  1745. } else {
  1746. old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
  1747. impl->SetTestPartResultReporterForCurrentThread(this);
  1748. }
  1749. }
  1750. // The d'tor restores the test part result reporter used by Google Test
  1751. // before.
  1752. ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
  1753. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  1754. if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
  1755. impl->SetGlobalTestPartResultReporter(old_reporter_);
  1756. } else {
  1757. impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
  1758. }
  1759. }
  1760. // Increments the test part result count and remembers the result.
  1761. // This method is from the TestPartResultReporterInterface interface.
  1762. void ScopedFakeTestPartResultReporter::ReportTestPartResult(
  1763. const TestPartResult& result) {
  1764. result_->Append(result);
  1765. }
  1766. namespace internal {
  1767. // Returns the type ID of ::testing::Test. We should always call this
  1768. // instead of GetTypeId< ::testing::Test>() to get the type ID of
  1769. // testing::Test. This is to work around a suspected linker bug when
  1770. // using Google Test as a framework on Mac OS X. The bug causes
  1771. // GetTypeId< ::testing::Test>() to return different values depending
  1772. // on whether the call is from the Google Test framework itself or
  1773. // from user test code. GetTestTypeId() is guaranteed to always
  1774. // return the same value, as it always calls GetTypeId<>() from the
  1775. // gtest.cc, which is within the Google Test framework.
  1776. TypeId GetTestTypeId() {
  1777. return GetTypeId<Test>();
  1778. }
  1779. // The value of GetTestTypeId() as seen from within the Google Test
  1780. // library. This is solely for testing GetTestTypeId().
  1781. extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
  1782. // This predicate-formatter checks that 'results' contains a test part
  1783. // failure of the given type and that the failure message contains the
  1784. // given substring.
  1785. static AssertionResult HasOneFailure(const char* /* results_expr */,
  1786. const char* /* type_expr */,
  1787. const char* /* substr_expr */,
  1788. const TestPartResultArray& results,
  1789. TestPartResult::Type type,
  1790. const std::string& substr) {
  1791. const std::string expected(type == TestPartResult::kFatalFailure ?
  1792. "1 fatal failure" :
  1793. "1 non-fatal failure");
  1794. Message msg;
  1795. if (results.size() != 1) {
  1796. msg << "Expected: " << expected << "\n"
  1797. << " Actual: " << results.size() << " failures";
  1798. for (int i = 0; i < results.size(); i++) {
  1799. msg << "\n" << results.GetTestPartResult(i);
  1800. }
  1801. return AssertionFailure() << msg;
  1802. }
  1803. const TestPartResult& r = results.GetTestPartResult(0);
  1804. if (r.type() != type) {
  1805. return AssertionFailure() << "Expected: " << expected << "\n"
  1806. << " Actual:\n"
  1807. << r;
  1808. }
  1809. if (strstr(r.message(), substr.c_str()) == nullptr) {
  1810. return AssertionFailure() << "Expected: " << expected << " containing \""
  1811. << substr << "\"\n"
  1812. << " Actual:\n"
  1813. << r;
  1814. }
  1815. return AssertionSuccess();
  1816. }
  1817. // The constructor of SingleFailureChecker remembers where to look up
  1818. // test part results, what type of failure we expect, and what
  1819. // substring the failure message should contain.
  1820. SingleFailureChecker::SingleFailureChecker(const TestPartResultArray* results,
  1821. TestPartResult::Type type,
  1822. const std::string& substr)
  1823. : results_(results), type_(type), substr_(substr) {}
  1824. // The destructor of SingleFailureChecker verifies that the given
  1825. // TestPartResultArray contains exactly one failure that has the given
  1826. // type and contains the given substring. If that's not the case, a
  1827. // non-fatal failure will be generated.
  1828. SingleFailureChecker::~SingleFailureChecker() {
  1829. EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_);
  1830. }
  1831. DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
  1832. UnitTestImpl* unit_test) : unit_test_(unit_test) {}
  1833. void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
  1834. const TestPartResult& result) {
  1835. unit_test_->current_test_result()->AddTestPartResult(result);
  1836. unit_test_->listeners()->repeater()->OnTestPartResult(result);
  1837. }
  1838. DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
  1839. UnitTestImpl* unit_test) : unit_test_(unit_test) {}
  1840. void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
  1841. const TestPartResult& result) {
  1842. unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
  1843. }
  1844. // Returns the global test part result reporter.
  1845. TestPartResultReporterInterface*
  1846. UnitTestImpl::GetGlobalTestPartResultReporter() {
  1847. internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
  1848. return global_test_part_result_repoter_;
  1849. }
  1850. // Sets the global test part result reporter.
  1851. void UnitTestImpl::SetGlobalTestPartResultReporter(
  1852. TestPartResultReporterInterface* reporter) {
  1853. internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
  1854. global_test_part_result_repoter_ = reporter;
  1855. }
  1856. // Returns the test part result reporter for the current thread.
  1857. TestPartResultReporterInterface*
  1858. UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
  1859. return per_thread_test_part_result_reporter_.get();
  1860. }
  1861. // Sets the test part result reporter for the current thread.
  1862. void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
  1863. TestPartResultReporterInterface* reporter) {
  1864. per_thread_test_part_result_reporter_.set(reporter);
  1865. }
  1866. // Gets the number of successful test suites.
  1867. int UnitTestImpl::successful_test_suite_count() const {
  1868. return CountIf(test_suites_, TestSuitePassed);
  1869. }
  1870. // Gets the number of failed test suites.
  1871. int UnitTestImpl::failed_test_suite_count() const {
  1872. return CountIf(test_suites_, TestSuiteFailed);
  1873. }
  1874. // Gets the number of all test suites.
  1875. int UnitTestImpl::total_test_suite_count() const {
  1876. return static_cast<int>(test_suites_.size());
  1877. }
  1878. // Gets the number of all test suites that contain at least one test
  1879. // that should run.
  1880. int UnitTestImpl::test_suite_to_run_count() const {
  1881. return CountIf(test_suites_, ShouldRunTestSuite);
  1882. }
  1883. // Gets the number of successful tests.
  1884. int UnitTestImpl::successful_test_count() const {
  1885. return SumOverTestSuiteList(test_suites_, &TestSuite::successful_test_count);
  1886. }
  1887. // Gets the number of skipped tests.
  1888. int UnitTestImpl::skipped_test_count() const {
  1889. return SumOverTestSuiteList(test_suites_, &TestSuite::skipped_test_count);
  1890. }
  1891. // Gets the number of failed tests.
  1892. int UnitTestImpl::failed_test_count() const {
  1893. return SumOverTestSuiteList(test_suites_, &TestSuite::failed_test_count);
  1894. }
  1895. // Gets the number of disabled tests that will be reported in the XML report.
  1896. int UnitTestImpl::reportable_disabled_test_count() const {
  1897. return SumOverTestSuiteList(test_suites_,
  1898. &TestSuite::reportable_disabled_test_count);
  1899. }
  1900. // Gets the number of disabled tests.
  1901. int UnitTestImpl::disabled_test_count() const {
  1902. return SumOverTestSuiteList(test_suites_, &TestSuite::disabled_test_count);
  1903. }
  1904. // Gets the number of tests to be printed in the XML report.
  1905. int UnitTestImpl::reportable_test_count() const {
  1906. return SumOverTestSuiteList(test_suites_, &TestSuite::reportable_test_count);
  1907. }
  1908. // Gets the number of all tests.
  1909. int UnitTestImpl::total_test_count() const {
  1910. return SumOverTestSuiteList(test_suites_, &TestSuite::total_test_count);
  1911. }
  1912. // Gets the number of tests that should run.
  1913. int UnitTestImpl::test_to_run_count() const {
  1914. return SumOverTestSuiteList(test_suites_, &TestSuite::test_to_run_count);
  1915. }
  1916. // Returns the current OS stack trace as an std::string.
  1917. //
  1918. // The maximum number of stack frames to be included is specified by
  1919. // the gtest_stack_trace_depth flag. The skip_count parameter
  1920. // specifies the number of top frames to be skipped, which doesn't
  1921. // count against the number of frames to be included.
  1922. //
  1923. // For example, if Foo() calls Bar(), which in turn calls
  1924. // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
  1925. // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
  1926. std::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
  1927. return os_stack_trace_getter()->CurrentStackTrace(
  1928. static_cast<int>(GTEST_FLAG(stack_trace_depth)),
  1929. skip_count + 1
  1930. // Skips the user-specified number of frames plus this function
  1931. // itself.
  1932. ); // NOLINT
  1933. }
  1934. // Returns the current time in milliseconds.
  1935. TimeInMillis GetTimeInMillis() {
  1936. #if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__)
  1937. // Difference between 1970-01-01 and 1601-01-01 in milliseconds.
  1938. // http://analogous.blogspot.com/2005/04/epoch.html
  1939. const TimeInMillis kJavaEpochToWinFileTimeDelta =
  1940. static_cast<TimeInMillis>(116444736UL) * 100000UL;
  1941. const DWORD kTenthMicrosInMilliSecond = 10000;
  1942. SYSTEMTIME now_systime;
  1943. FILETIME now_filetime;
  1944. ULARGE_INTEGER now_int64;
  1945. GetSystemTime(&now_systime);
  1946. if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
  1947. now_int64.LowPart = now_filetime.dwLowDateTime;
  1948. now_int64.HighPart = now_filetime.dwHighDateTime;
  1949. now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
  1950. kJavaEpochToWinFileTimeDelta;
  1951. return now_int64.QuadPart;
  1952. }
  1953. return 0;
  1954. #elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_
  1955. __timeb64 now;
  1956. // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996
  1957. // (deprecated function) there.
  1958. GTEST_DISABLE_MSC_DEPRECATED_PUSH_()
  1959. _ftime64(&now);
  1960. GTEST_DISABLE_MSC_DEPRECATED_POP_()
  1961. return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
  1962. #elif GTEST_HAS_GETTIMEOFDAY_
  1963. struct timeval now;
  1964. gettimeofday(&now, nullptr);
  1965. return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
  1966. #else
  1967. # error "Don't know how to get the current time on your system."
  1968. #endif
  1969. }
  1970. // Utilities
  1971. // class String.
  1972. #if GTEST_OS_WINDOWS_MOBILE
  1973. // Creates a UTF-16 wide string from the given ANSI string, allocating
  1974. // memory using new. The caller is responsible for deleting the return
  1975. // value using delete[]. Returns the wide string, or NULL if the
  1976. // input is NULL.
  1977. LPCWSTR String::AnsiToUtf16(const char* ansi) {
  1978. if (!ansi) return nullptr;
  1979. const int length = strlen(ansi);
  1980. const int unicode_length =
  1981. MultiByteToWideChar(CP_ACP, 0, ansi, length, nullptr, 0);
  1982. WCHAR* unicode = new WCHAR[unicode_length + 1];
  1983. MultiByteToWideChar(CP_ACP, 0, ansi, length,
  1984. unicode, unicode_length);
  1985. unicode[unicode_length] = 0;
  1986. return unicode;
  1987. }
  1988. // Creates an ANSI string from the given wide string, allocating
  1989. // memory using new. The caller is responsible for deleting the return
  1990. // value using delete[]. Returns the ANSI string, or NULL if the
  1991. // input is NULL.
  1992. const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
  1993. if (!utf16_str) return nullptr;
  1994. const int ansi_length = WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, nullptr,
  1995. 0, nullptr, nullptr);
  1996. char* ansi = new char[ansi_length + 1];
  1997. WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, ansi, ansi_length, nullptr,
  1998. nullptr);
  1999. ansi[ansi_length] = 0;
  2000. return ansi;
  2001. }
  2002. #endif // GTEST_OS_WINDOWS_MOBILE
  2003. // Compares two C strings. Returns true iff they have the same content.
  2004. //
  2005. // Unlike strcmp(), this function can handle NULL argument(s). A NULL
  2006. // C string is considered different to any non-NULL C string,
  2007. // including the empty string.
  2008. bool String::CStringEquals(const char * lhs, const char * rhs) {
  2009. if (lhs == nullptr) return rhs == nullptr;
  2010. if (rhs == nullptr) return false;
  2011. return strcmp(lhs, rhs) == 0;
  2012. }
  2013. #if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
  2014. // Converts an array of wide chars to a narrow string using the UTF-8
  2015. // encoding, and streams the result to the given Message object.
  2016. static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
  2017. Message* msg) {
  2018. for (size_t i = 0; i != length; ) { // NOLINT
  2019. if (wstr[i] != L'\0') {
  2020. *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
  2021. while (i != length && wstr[i] != L'\0')
  2022. i++;
  2023. } else {
  2024. *msg << '\0';
  2025. i++;
  2026. }
  2027. }
  2028. }
  2029. #endif // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
  2030. void SplitString(const ::std::string& str, char delimiter,
  2031. ::std::vector< ::std::string>* dest) {
  2032. ::std::vector< ::std::string> parsed;
  2033. ::std::string::size_type pos = 0;
  2034. while (::testing::internal::AlwaysTrue()) {
  2035. const ::std::string::size_type colon = str.find(delimiter, pos);
  2036. if (colon == ::std::string::npos) {
  2037. parsed.push_back(str.substr(pos));
  2038. break;
  2039. } else {
  2040. parsed.push_back(str.substr(pos, colon - pos));
  2041. pos = colon + 1;
  2042. }
  2043. }
  2044. dest->swap(parsed);
  2045. }
  2046. } // namespace internal
  2047. // Constructs an empty Message.
  2048. // We allocate the stringstream separately because otherwise each use of
  2049. // ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's
  2050. // stack frame leading to huge stack frames in some cases; gcc does not reuse
  2051. // the stack space.
  2052. Message::Message() : ss_(new ::std::stringstream) {
  2053. // By default, we want there to be enough precision when printing
  2054. // a double to a Message.
  2055. *ss_ << std::setprecision(std::numeric_limits<double>::digits10 + 2);
  2056. }
  2057. // These two overloads allow streaming a wide C string to a Message
  2058. // using the UTF-8 encoding.
  2059. Message& Message::operator <<(const wchar_t* wide_c_str) {
  2060. return *this << internal::String::ShowWideCString(wide_c_str);
  2061. }
  2062. Message& Message::operator <<(wchar_t* wide_c_str) {
  2063. return *this << internal::String::ShowWideCString(wide_c_str);
  2064. }
  2065. #if GTEST_HAS_STD_WSTRING
  2066. // Converts the given wide string to a narrow string using the UTF-8
  2067. // encoding, and streams the result to this Message object.
  2068. Message& Message::operator <<(const ::std::wstring& wstr) {
  2069. internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
  2070. return *this;
  2071. }
  2072. #endif // GTEST_HAS_STD_WSTRING
  2073. #if GTEST_HAS_GLOBAL_WSTRING
  2074. // Converts the given wide string to a narrow string using the UTF-8
  2075. // encoding, and streams the result to this Message object.
  2076. Message& Message::operator <<(const ::wstring& wstr) {
  2077. internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
  2078. return *this;
  2079. }
  2080. #endif // GTEST_HAS_GLOBAL_WSTRING
  2081. // Gets the text streamed to this object so far as an std::string.
  2082. // Each '\0' character in the buffer is replaced with "\\0".
  2083. std::string Message::GetString() const {
  2084. return internal::StringStreamToString(ss_.get());
  2085. }
  2086. // AssertionResult constructors.
  2087. // Used in EXPECT_TRUE/FALSE(assertion_result).
  2088. AssertionResult::AssertionResult(const AssertionResult& other)
  2089. : success_(other.success_),
  2090. message_(other.message_.get() != nullptr
  2091. ? new ::std::string(*other.message_)
  2092. : static_cast< ::std::string*>(nullptr)) {}
  2093. // Swaps two AssertionResults.
  2094. void AssertionResult::swap(AssertionResult& other) {
  2095. using std::swap;
  2096. swap(success_, other.success_);
  2097. swap(message_, other.message_);
  2098. }
  2099. // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
  2100. AssertionResult AssertionResult::operator!() const {
  2101. AssertionResult negation(!success_);
  2102. if (message_.get() != nullptr) negation << *message_;
  2103. return negation;
  2104. }
  2105. // Makes a successful assertion result.
  2106. AssertionResult AssertionSuccess() {
  2107. return AssertionResult(true);
  2108. }
  2109. // Makes a failed assertion result.
  2110. AssertionResult AssertionFailure() {
  2111. return AssertionResult(false);
  2112. }
  2113. // Makes a failed assertion result with the given failure message.
  2114. // Deprecated; use AssertionFailure() << message.
  2115. AssertionResult AssertionFailure(const Message& message) {
  2116. return AssertionFailure() << message;
  2117. }
  2118. namespace internal {
  2119. namespace edit_distance {
  2120. std::vector<EditType> CalculateOptimalEdits(const std::vector<size_t>& left,
  2121. const std::vector<size_t>& right) {
  2122. std::vector<std::vector<double> > costs(
  2123. left.size() + 1, std::vector<double>(right.size() + 1));
  2124. std::vector<std::vector<EditType> > best_move(
  2125. left.size() + 1, std::vector<EditType>(right.size() + 1));
  2126. // Populate for empty right.
  2127. for (size_t l_i = 0; l_i < costs.size(); ++l_i) {
  2128. costs[l_i][0] = static_cast<double>(l_i);
  2129. best_move[l_i][0] = kRemove;
  2130. }
  2131. // Populate for empty left.
  2132. for (size_t r_i = 1; r_i < costs[0].size(); ++r_i) {
  2133. costs[0][r_i] = static_cast<double>(r_i);
  2134. best_move[0][r_i] = kAdd;
  2135. }
  2136. for (size_t l_i = 0; l_i < left.size(); ++l_i) {
  2137. for (size_t r_i = 0; r_i < right.size(); ++r_i) {
  2138. if (left[l_i] == right[r_i]) {
  2139. // Found a match. Consume it.
  2140. costs[l_i + 1][r_i + 1] = costs[l_i][r_i];
  2141. best_move[l_i + 1][r_i + 1] = kMatch;
  2142. continue;
  2143. }
  2144. const double add = costs[l_i + 1][r_i];
  2145. const double remove = costs[l_i][r_i + 1];
  2146. const double replace = costs[l_i][r_i];
  2147. if (add < remove && add < replace) {
  2148. costs[l_i + 1][r_i + 1] = add + 1;
  2149. best_move[l_i + 1][r_i + 1] = kAdd;
  2150. } else if (remove < add && remove < replace) {
  2151. costs[l_i + 1][r_i + 1] = remove + 1;
  2152. best_move[l_i + 1][r_i + 1] = kRemove;
  2153. } else {
  2154. // We make replace a little more expensive than add/remove to lower
  2155. // their priority.
  2156. costs[l_i + 1][r_i + 1] = replace + 1.00001;
  2157. best_move[l_i + 1][r_i + 1] = kReplace;
  2158. }
  2159. }
  2160. }
  2161. // Reconstruct the best path. We do it in reverse order.
  2162. std::vector<EditType> best_path;
  2163. for (size_t l_i = left.size(), r_i = right.size(); l_i > 0 || r_i > 0;) {
  2164. EditType move = best_move[l_i][r_i];
  2165. best_path.push_back(move);
  2166. l_i -= move != kAdd;
  2167. r_i -= move != kRemove;
  2168. }
  2169. std::reverse(best_path.begin(), best_path.end());
  2170. return best_path;
  2171. }
  2172. namespace {
  2173. // Helper class to convert string into ids with deduplication.
  2174. class InternalStrings {
  2175. public:
  2176. size_t GetId(const std::string& str) {
  2177. IdMap::iterator it = ids_.find(str);
  2178. if (it != ids_.end()) return it->second;
  2179. size_t id = ids_.size();
  2180. return ids_[str] = id;
  2181. }
  2182. private:
  2183. typedef std::map<std::string, size_t> IdMap;
  2184. IdMap ids_;
  2185. };
  2186. } // namespace
  2187. std::vector<EditType> CalculateOptimalEdits(
  2188. const std::vector<std::string>& left,
  2189. const std::vector<std::string>& right) {
  2190. std::vector<size_t> left_ids, right_ids;
  2191. {
  2192. InternalStrings intern_table;
  2193. for (size_t i = 0; i < left.size(); ++i) {
  2194. left_ids.push_back(intern_table.GetId(left[i]));
  2195. }
  2196. for (size_t i = 0; i < right.size(); ++i) {
  2197. right_ids.push_back(intern_table.GetId(right[i]));
  2198. }
  2199. }
  2200. return CalculateOptimalEdits(left_ids, right_ids);
  2201. }
  2202. namespace {
  2203. // Helper class that holds the state for one hunk and prints it out to the
  2204. // stream.
  2205. // It reorders adds/removes when possible to group all removes before all
  2206. // adds. It also adds the hunk header before printint into the stream.
  2207. class Hunk {
  2208. public:
  2209. Hunk(size_t left_start, size_t right_start)
  2210. : left_start_(left_start),
  2211. right_start_(right_start),
  2212. adds_(),
  2213. removes_(),
  2214. common_() {}
  2215. void PushLine(char edit, const char* line) {
  2216. switch (edit) {
  2217. case ' ':
  2218. ++common_;
  2219. FlushEdits();
  2220. hunk_.push_back(std::make_pair(' ', line));
  2221. break;
  2222. case '-':
  2223. ++removes_;
  2224. hunk_removes_.push_back(std::make_pair('-', line));
  2225. break;
  2226. case '+':
  2227. ++adds_;
  2228. hunk_adds_.push_back(std::make_pair('+', line));
  2229. break;
  2230. }
  2231. }
  2232. void PrintTo(std::ostream* os) {
  2233. PrintHeader(os);
  2234. FlushEdits();
  2235. for (std::list<std::pair<char, const char*> >::const_iterator it =
  2236. hunk_.begin();
  2237. it != hunk_.end(); ++it) {
  2238. *os << it->first << it->second << "\n";
  2239. }
  2240. }
  2241. bool has_edits() const { return adds_ || removes_; }
  2242. private:
  2243. void FlushEdits() {
  2244. hunk_.splice(hunk_.end(), hunk_removes_);
  2245. hunk_.splice(hunk_.end(), hunk_adds_);
  2246. }
  2247. // Print a unified diff header for one hunk.
  2248. // The format is
  2249. // "@@ -<left_start>,<left_length> +<right_start>,<right_length> @@"
  2250. // where the left/right parts are omitted if unnecessary.
  2251. void PrintHeader(std::ostream* ss) const {
  2252. *ss << "@@ ";
  2253. if (removes_) {
  2254. *ss << "-" << left_start_ << "," << (removes_ + common_);
  2255. }
  2256. if (removes_ && adds_) {
  2257. *ss << " ";
  2258. }
  2259. if (adds_) {
  2260. *ss << "+" << right_start_ << "," << (adds_ + common_);
  2261. }
  2262. *ss << " @@\n";
  2263. }
  2264. size_t left_start_, right_start_;
  2265. size_t adds_, removes_, common_;
  2266. std::list<std::pair<char, const char*> > hunk_, hunk_adds_, hunk_removes_;
  2267. };
  2268. } // namespace
  2269. // Create a list of diff hunks in Unified diff format.
  2270. // Each hunk has a header generated by PrintHeader above plus a body with
  2271. // lines prefixed with ' ' for no change, '-' for deletion and '+' for
  2272. // addition.
  2273. // 'context' represents the desired unchanged prefix/suffix around the diff.
  2274. // If two hunks are close enough that their contexts overlap, then they are
  2275. // joined into one hunk.
  2276. std::string CreateUnifiedDiff(const std::vector<std::string>& left,
  2277. const std::vector<std::string>& right,
  2278. size_t context) {
  2279. const std::vector<EditType> edits = CalculateOptimalEdits(left, right);
  2280. size_t l_i = 0, r_i = 0, edit_i = 0;
  2281. std::stringstream ss;
  2282. while (edit_i < edits.size()) {
  2283. // Find first edit.
  2284. while (edit_i < edits.size() && edits[edit_i] == kMatch) {
  2285. ++l_i;
  2286. ++r_i;
  2287. ++edit_i;
  2288. }
  2289. // Find the first line to include in the hunk.
  2290. const size_t prefix_context = std::min(l_i, context);
  2291. Hunk hunk(l_i - prefix_context + 1, r_i - prefix_context + 1);
  2292. for (size_t i = prefix_context; i > 0; --i) {
  2293. hunk.PushLine(' ', left[l_i - i].c_str());
  2294. }
  2295. // Iterate the edits until we found enough suffix for the hunk or the input
  2296. // is over.
  2297. size_t n_suffix = 0;
  2298. for (; edit_i < edits.size(); ++edit_i) {
  2299. if (n_suffix >= context) {
  2300. // Continue only if the next hunk is very close.
  2301. std::vector<EditType>::const_iterator it = edits.begin() + edit_i;
  2302. while (it != edits.end() && *it == kMatch) ++it;
  2303. if (it == edits.end() || (it - edits.begin()) - edit_i >= context) {
  2304. // There is no next edit or it is too far away.
  2305. break;
  2306. }
  2307. }
  2308. EditType edit = edits[edit_i];
  2309. // Reset count when a non match is found.
  2310. n_suffix = edit == kMatch ? n_suffix + 1 : 0;
  2311. if (edit == kMatch || edit == kRemove || edit == kReplace) {
  2312. hunk.PushLine(edit == kMatch ? ' ' : '-', left[l_i].c_str());
  2313. }
  2314. if (edit == kAdd || edit == kReplace) {
  2315. hunk.PushLine('+', right[r_i].c_str());
  2316. }
  2317. // Advance indices, depending on edit type.
  2318. l_i += edit != kAdd;
  2319. r_i += edit != kRemove;
  2320. }
  2321. if (!hunk.has_edits()) {
  2322. // We are done. We don't want this hunk.
  2323. break;
  2324. }
  2325. hunk.PrintTo(&ss);
  2326. }
  2327. return ss.str();
  2328. }
  2329. } // namespace edit_distance
  2330. namespace {
  2331. // The string representation of the values received in EqFailure() are already
  2332. // escaped. Split them on escaped '\n' boundaries. Leave all other escaped
  2333. // characters the same.
  2334. std::vector<std::string> SplitEscapedString(const std::string& str) {
  2335. std::vector<std::string> lines;
  2336. size_t start = 0, end = str.size();
  2337. if (end > 2 && str[0] == '"' && str[end - 1] == '"') {
  2338. ++start;
  2339. --end;
  2340. }
  2341. bool escaped = false;
  2342. for (size_t i = start; i + 1 < end; ++i) {
  2343. if (escaped) {
  2344. escaped = false;
  2345. if (str[i] == 'n') {
  2346. lines.push_back(str.substr(start, i - start - 1));
  2347. start = i + 1;
  2348. }
  2349. } else {
  2350. escaped = str[i] == '\\';
  2351. }
  2352. }
  2353. lines.push_back(str.substr(start, end - start));
  2354. return lines;
  2355. }
  2356. } // namespace
  2357. // Constructs and returns the message for an equality assertion
  2358. // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
  2359. //
  2360. // The first four parameters are the expressions used in the assertion
  2361. // and their values, as strings. For example, for ASSERT_EQ(foo, bar)
  2362. // where foo is 5 and bar is 6, we have:
  2363. //
  2364. // lhs_expression: "foo"
  2365. // rhs_expression: "bar"
  2366. // lhs_value: "5"
  2367. // rhs_value: "6"
  2368. //
  2369. // The ignoring_case parameter is true iff the assertion is a
  2370. // *_STRCASEEQ*. When it's true, the string "Ignoring case" will
  2371. // be inserted into the message.
  2372. AssertionResult EqFailure(const char* lhs_expression,
  2373. const char* rhs_expression,
  2374. const std::string& lhs_value,
  2375. const std::string& rhs_value,
  2376. bool ignoring_case) {
  2377. Message msg;
  2378. msg << "Expected equality of these values:";
  2379. msg << "\n " << lhs_expression;
  2380. if (lhs_value != lhs_expression) {
  2381. msg << "\n Which is: " << lhs_value;
  2382. }
  2383. msg << "\n " << rhs_expression;
  2384. if (rhs_value != rhs_expression) {
  2385. msg << "\n Which is: " << rhs_value;
  2386. }
  2387. if (ignoring_case) {
  2388. msg << "\nIgnoring case";
  2389. }
  2390. if (!lhs_value.empty() && !rhs_value.empty()) {
  2391. const std::vector<std::string> lhs_lines =
  2392. SplitEscapedString(lhs_value);
  2393. const std::vector<std::string> rhs_lines =
  2394. SplitEscapedString(rhs_value);
  2395. if (lhs_lines.size() > 1 || rhs_lines.size() > 1) {
  2396. msg << "\nWith diff:\n"
  2397. << edit_distance::CreateUnifiedDiff(lhs_lines, rhs_lines);
  2398. }
  2399. }
  2400. return AssertionFailure() << msg;
  2401. }
  2402. // Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
  2403. std::string GetBoolAssertionFailureMessage(
  2404. const AssertionResult& assertion_result,
  2405. const char* expression_text,
  2406. const char* actual_predicate_value,
  2407. const char* expected_predicate_value) {
  2408. const char* actual_message = assertion_result.message();
  2409. Message msg;
  2410. msg << "Value of: " << expression_text
  2411. << "\n Actual: " << actual_predicate_value;
  2412. if (actual_message[0] != '\0')
  2413. msg << " (" << actual_message << ")";
  2414. msg << "\nExpected: " << expected_predicate_value;
  2415. return msg.GetString();
  2416. }
  2417. // Helper function for implementing ASSERT_NEAR.
  2418. AssertionResult DoubleNearPredFormat(const char* expr1,
  2419. const char* expr2,
  2420. const char* abs_error_expr,
  2421. double val1,
  2422. double val2,
  2423. double abs_error) {
  2424. const double diff = fabs(val1 - val2);
  2425. if (diff <= abs_error) return AssertionSuccess();
  2426. return AssertionFailure()
  2427. << "The difference between " << expr1 << " and " << expr2
  2428. << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"
  2429. << expr1 << " evaluates to " << val1 << ",\n"
  2430. << expr2 << " evaluates to " << val2 << ", and\n"
  2431. << abs_error_expr << " evaluates to " << abs_error << ".";
  2432. }
  2433. // Helper template for implementing FloatLE() and DoubleLE().
  2434. template <typename RawType>
  2435. AssertionResult FloatingPointLE(const char* expr1,
  2436. const char* expr2,
  2437. RawType val1,
  2438. RawType val2) {
  2439. // Returns success if val1 is less than val2,
  2440. if (val1 < val2) {
  2441. return AssertionSuccess();
  2442. }
  2443. // or if val1 is almost equal to val2.
  2444. const FloatingPoint<RawType> lhs(val1), rhs(val2);
  2445. if (lhs.AlmostEquals(rhs)) {
  2446. return AssertionSuccess();
  2447. }
  2448. // Note that the above two checks will both fail if either val1 or
  2449. // val2 is NaN, as the IEEE floating-point standard requires that
  2450. // any predicate involving a NaN must return false.
  2451. ::std::stringstream val1_ss;
  2452. val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
  2453. << val1;
  2454. ::std::stringstream val2_ss;
  2455. val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
  2456. << val2;
  2457. return AssertionFailure()
  2458. << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
  2459. << " Actual: " << StringStreamToString(&val1_ss) << " vs "
  2460. << StringStreamToString(&val2_ss);
  2461. }
  2462. } // namespace internal
  2463. // Asserts that val1 is less than, or almost equal to, val2. Fails
  2464. // otherwise. In particular, it fails if either val1 or val2 is NaN.
  2465. AssertionResult FloatLE(const char* expr1, const char* expr2,
  2466. float val1, float val2) {
  2467. return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
  2468. }
  2469. // Asserts that val1 is less than, or almost equal to, val2. Fails
  2470. // otherwise. In particular, it fails if either val1 or val2 is NaN.
  2471. AssertionResult DoubleLE(const char* expr1, const char* expr2,
  2472. double val1, double val2) {
  2473. return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
  2474. }
  2475. namespace internal {
  2476. // The helper function for {ASSERT|EXPECT}_EQ with int or enum
  2477. // arguments.
  2478. AssertionResult CmpHelperEQ(const char* lhs_expression,
  2479. const char* rhs_expression,
  2480. BiggestInt lhs,
  2481. BiggestInt rhs) {
  2482. if (lhs == rhs) {
  2483. return AssertionSuccess();
  2484. }
  2485. return EqFailure(lhs_expression,
  2486. rhs_expression,
  2487. FormatForComparisonFailureMessage(lhs, rhs),
  2488. FormatForComparisonFailureMessage(rhs, lhs),
  2489. false);
  2490. }
  2491. // A macro for implementing the helper functions needed to implement
  2492. // ASSERT_?? and EXPECT_?? with integer or enum arguments. It is here
  2493. // just to avoid copy-and-paste of similar code.
  2494. #define GTEST_IMPL_CMP_HELPER_(op_name, op)\
  2495. AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
  2496. BiggestInt val1, BiggestInt val2) {\
  2497. if (val1 op val2) {\
  2498. return AssertionSuccess();\
  2499. } else {\
  2500. return AssertionFailure() \
  2501. << "Expected: (" << expr1 << ") " #op " (" << expr2\
  2502. << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
  2503. << " vs " << FormatForComparisonFailureMessage(val2, val1);\
  2504. }\
  2505. }
  2506. // Implements the helper function for {ASSERT|EXPECT}_NE with int or
  2507. // enum arguments.
  2508. GTEST_IMPL_CMP_HELPER_(NE, !=)
  2509. // Implements the helper function for {ASSERT|EXPECT}_LE with int or
  2510. // enum arguments.
  2511. GTEST_IMPL_CMP_HELPER_(LE, <=)
  2512. // Implements the helper function for {ASSERT|EXPECT}_LT with int or
  2513. // enum arguments.
  2514. GTEST_IMPL_CMP_HELPER_(LT, < )
  2515. // Implements the helper function for {ASSERT|EXPECT}_GE with int or
  2516. // enum arguments.
  2517. GTEST_IMPL_CMP_HELPER_(GE, >=)
  2518. // Implements the helper function for {ASSERT|EXPECT}_GT with int or
  2519. // enum arguments.
  2520. GTEST_IMPL_CMP_HELPER_(GT, > )
  2521. #undef GTEST_IMPL_CMP_HELPER_
  2522. // The helper function for {ASSERT|EXPECT}_STREQ.
  2523. AssertionResult CmpHelperSTREQ(const char* lhs_expression,
  2524. const char* rhs_expression,
  2525. const char* lhs,
  2526. const char* rhs) {
  2527. if (String::CStringEquals(lhs, rhs)) {
  2528. return AssertionSuccess();
  2529. }
  2530. return EqFailure(lhs_expression,
  2531. rhs_expression,
  2532. PrintToString(lhs),
  2533. PrintToString(rhs),
  2534. false);
  2535. }
  2536. // The helper function for {ASSERT|EXPECT}_STRCASEEQ.
  2537. AssertionResult CmpHelperSTRCASEEQ(const char* lhs_expression,
  2538. const char* rhs_expression,
  2539. const char* lhs,
  2540. const char* rhs) {
  2541. if (String::CaseInsensitiveCStringEquals(lhs, rhs)) {
  2542. return AssertionSuccess();
  2543. }
  2544. return EqFailure(lhs_expression,
  2545. rhs_expression,
  2546. PrintToString(lhs),
  2547. PrintToString(rhs),
  2548. true);
  2549. }
  2550. // The helper function for {ASSERT|EXPECT}_STRNE.
  2551. AssertionResult CmpHelperSTRNE(const char* s1_expression,
  2552. const char* s2_expression,
  2553. const char* s1,
  2554. const char* s2) {
  2555. if (!String::CStringEquals(s1, s2)) {
  2556. return AssertionSuccess();
  2557. } else {
  2558. return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
  2559. << s2_expression << "), actual: \""
  2560. << s1 << "\" vs \"" << s2 << "\"";
  2561. }
  2562. }
  2563. // The helper function for {ASSERT|EXPECT}_STRCASENE.
  2564. AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
  2565. const char* s2_expression,
  2566. const char* s1,
  2567. const char* s2) {
  2568. if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
  2569. return AssertionSuccess();
  2570. } else {
  2571. return AssertionFailure()
  2572. << "Expected: (" << s1_expression << ") != ("
  2573. << s2_expression << ") (ignoring case), actual: \""
  2574. << s1 << "\" vs \"" << s2 << "\"";
  2575. }
  2576. }
  2577. } // namespace internal
  2578. namespace {
  2579. // Helper functions for implementing IsSubString() and IsNotSubstring().
  2580. // This group of overloaded functions return true iff needle is a
  2581. // substring of haystack. NULL is considered a substring of itself
  2582. // only.
  2583. bool IsSubstringPred(const char* needle, const char* haystack) {
  2584. if (needle == nullptr || haystack == nullptr) return needle == haystack;
  2585. return strstr(haystack, needle) != nullptr;
  2586. }
  2587. bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
  2588. if (needle == nullptr || haystack == nullptr) return needle == haystack;
  2589. return wcsstr(haystack, needle) != nullptr;
  2590. }
  2591. // StringType here can be either ::std::string or ::std::wstring.
  2592. template <typename StringType>
  2593. bool IsSubstringPred(const StringType& needle,
  2594. const StringType& haystack) {
  2595. return haystack.find(needle) != StringType::npos;
  2596. }
  2597. // This function implements either IsSubstring() or IsNotSubstring(),
  2598. // depending on the value of the expected_to_be_substring parameter.
  2599. // StringType here can be const char*, const wchar_t*, ::std::string,
  2600. // or ::std::wstring.
  2601. template <typename StringType>
  2602. AssertionResult IsSubstringImpl(
  2603. bool expected_to_be_substring,
  2604. const char* needle_expr, const char* haystack_expr,
  2605. const StringType& needle, const StringType& haystack) {
  2606. if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
  2607. return AssertionSuccess();
  2608. const bool is_wide_string = sizeof(needle[0]) > 1;
  2609. const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
  2610. return AssertionFailure()
  2611. << "Value of: " << needle_expr << "\n"
  2612. << " Actual: " << begin_string_quote << needle << "\"\n"
  2613. << "Expected: " << (expected_to_be_substring ? "" : "not ")
  2614. << "a substring of " << haystack_expr << "\n"
  2615. << "Which is: " << begin_string_quote << haystack << "\"";
  2616. }
  2617. } // namespace
  2618. // IsSubstring() and IsNotSubstring() check whether needle is a
  2619. // substring of haystack (NULL is considered a substring of itself
  2620. // only), and return an appropriate error message when they fail.
  2621. AssertionResult IsSubstring(
  2622. const char* needle_expr, const char* haystack_expr,
  2623. const char* needle, const char* haystack) {
  2624. return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
  2625. }
  2626. AssertionResult IsSubstring(
  2627. const char* needle_expr, const char* haystack_expr,
  2628. const wchar_t* needle, const wchar_t* haystack) {
  2629. return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
  2630. }
  2631. AssertionResult IsNotSubstring(
  2632. const char* needle_expr, const char* haystack_expr,
  2633. const char* needle, const char* haystack) {
  2634. return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
  2635. }
  2636. AssertionResult IsNotSubstring(
  2637. const char* needle_expr, const char* haystack_expr,
  2638. const wchar_t* needle, const wchar_t* haystack) {
  2639. return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
  2640. }
  2641. AssertionResult IsSubstring(
  2642. const char* needle_expr, const char* haystack_expr,
  2643. const ::std::string& needle, const ::std::string& haystack) {
  2644. return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
  2645. }
  2646. AssertionResult IsNotSubstring(
  2647. const char* needle_expr, const char* haystack_expr,
  2648. const ::std::string& needle, const ::std::string& haystack) {
  2649. return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
  2650. }
  2651. #if GTEST_HAS_STD_WSTRING
  2652. AssertionResult IsSubstring(
  2653. const char* needle_expr, const char* haystack_expr,
  2654. const ::std::wstring& needle, const ::std::wstring& haystack) {
  2655. return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
  2656. }
  2657. AssertionResult IsNotSubstring(
  2658. const char* needle_expr, const char* haystack_expr,
  2659. const ::std::wstring& needle, const ::std::wstring& haystack) {
  2660. return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
  2661. }
  2662. #endif // GTEST_HAS_STD_WSTRING
  2663. namespace internal {
  2664. #if GTEST_OS_WINDOWS
  2665. namespace {
  2666. // Helper function for IsHRESULT{SuccessFailure} predicates
  2667. AssertionResult HRESULTFailureHelper(const char* expr,
  2668. const char* expected,
  2669. long hr) { // NOLINT
  2670. # if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_TV_TITLE
  2671. // Windows CE doesn't support FormatMessage.
  2672. const char error_text[] = "";
  2673. # else
  2674. // Looks up the human-readable system message for the HRESULT code
  2675. // and since we're not passing any params to FormatMessage, we don't
  2676. // want inserts expanded.
  2677. const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
  2678. FORMAT_MESSAGE_IGNORE_INSERTS;
  2679. const DWORD kBufSize = 4096;
  2680. // Gets the system's human readable message string for this HRESULT.
  2681. char error_text[kBufSize] = { '\0' };
  2682. DWORD message_length = ::FormatMessageA(kFlags,
  2683. 0, // no source, we're asking system
  2684. hr, // the error
  2685. 0, // no line width restrictions
  2686. error_text, // output buffer
  2687. kBufSize, // buf size
  2688. nullptr); // no arguments for inserts
  2689. // Trims tailing white space (FormatMessage leaves a trailing CR-LF)
  2690. for (; message_length && IsSpace(error_text[message_length - 1]);
  2691. --message_length) {
  2692. error_text[message_length - 1] = '\0';
  2693. }
  2694. # endif // GTEST_OS_WINDOWS_MOBILE
  2695. const std::string error_hex("0x" + String::FormatHexInt(hr));
  2696. return ::testing::AssertionFailure()
  2697. << "Expected: " << expr << " " << expected << ".\n"
  2698. << " Actual: " << error_hex << " " << error_text << "\n";
  2699. }
  2700. } // namespace
  2701. AssertionResult IsHRESULTSuccess(const char* expr, long hr) { // NOLINT
  2702. if (SUCCEEDED(hr)) {
  2703. return AssertionSuccess();
  2704. }
  2705. return HRESULTFailureHelper(expr, "succeeds", hr);
  2706. }
  2707. AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT
  2708. if (FAILED(hr)) {
  2709. return AssertionSuccess();
  2710. }
  2711. return HRESULTFailureHelper(expr, "fails", hr);
  2712. }
  2713. #endif // GTEST_OS_WINDOWS
  2714. // Utility functions for encoding Unicode text (wide strings) in
  2715. // UTF-8.
  2716. // A Unicode code-point can have up to 21 bits, and is encoded in UTF-8
  2717. // like this:
  2718. //
  2719. // Code-point length Encoding
  2720. // 0 - 7 bits 0xxxxxxx
  2721. // 8 - 11 bits 110xxxxx 10xxxxxx
  2722. // 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx
  2723. // 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  2724. // The maximum code-point a one-byte UTF-8 sequence can represent.
  2725. const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) << 7) - 1;
  2726. // The maximum code-point a two-byte UTF-8 sequence can represent.
  2727. const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1;
  2728. // The maximum code-point a three-byte UTF-8 sequence can represent.
  2729. const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2*6)) - 1;
  2730. // The maximum code-point a four-byte UTF-8 sequence can represent.
  2731. const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3*6)) - 1;
  2732. // Chops off the n lowest bits from a bit pattern. Returns the n
  2733. // lowest bits. As a side effect, the original bit pattern will be
  2734. // shifted to the right by n bits.
  2735. inline UInt32 ChopLowBits(UInt32* bits, int n) {
  2736. const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1);
  2737. *bits >>= n;
  2738. return low_bits;
  2739. }
  2740. // Converts a Unicode code point to a narrow string in UTF-8 encoding.
  2741. // code_point parameter is of type UInt32 because wchar_t may not be
  2742. // wide enough to contain a code point.
  2743. // If the code_point is not a valid Unicode code point
  2744. // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
  2745. // to "(Invalid Unicode 0xXXXXXXXX)".
  2746. std::string CodePointToUtf8(UInt32 code_point) {
  2747. if (code_point > kMaxCodePoint4) {
  2748. return "(Invalid Unicode 0x" + String::FormatHexInt(code_point) + ")";
  2749. }
  2750. char str[5]; // Big enough for the largest valid code point.
  2751. if (code_point <= kMaxCodePoint1) {
  2752. str[1] = '\0';
  2753. str[0] = static_cast<char>(code_point); // 0xxxxxxx
  2754. } else if (code_point <= kMaxCodePoint2) {
  2755. str[2] = '\0';
  2756. str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  2757. str[0] = static_cast<char>(0xC0 | code_point); // 110xxxxx
  2758. } else if (code_point <= kMaxCodePoint3) {
  2759. str[3] = '\0';
  2760. str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  2761. str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  2762. str[0] = static_cast<char>(0xE0 | code_point); // 1110xxxx
  2763. } else { // code_point <= kMaxCodePoint4
  2764. str[4] = '\0';
  2765. str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  2766. str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  2767. str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  2768. str[0] = static_cast<char>(0xF0 | code_point); // 11110xxx
  2769. }
  2770. return str;
  2771. }
  2772. // The following two functions only make sense if the system
  2773. // uses UTF-16 for wide string encoding. All supported systems
  2774. // with 16 bit wchar_t (Windows, Cygwin) do use UTF-16.
  2775. // Determines if the arguments constitute UTF-16 surrogate pair
  2776. // and thus should be combined into a single Unicode code point
  2777. // using CreateCodePointFromUtf16SurrogatePair.
  2778. inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
  2779. return sizeof(wchar_t) == 2 &&
  2780. (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;
  2781. }
  2782. // Creates a Unicode code point from UTF16 surrogate pair.
  2783. inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first,
  2784. wchar_t second) {
  2785. const UInt32 mask = (1 << 10) - 1;
  2786. return (sizeof(wchar_t) == 2) ?
  2787. (((first & mask) << 10) | (second & mask)) + 0x10000 :
  2788. // This function should not be called when the condition is
  2789. // false, but we provide a sensible default in case it is.
  2790. static_cast<UInt32>(first);
  2791. }
  2792. // Converts a wide string to a narrow string in UTF-8 encoding.
  2793. // The wide string is assumed to have the following encoding:
  2794. // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin)
  2795. // UTF-32 if sizeof(wchar_t) == 4 (on Linux)
  2796. // Parameter str points to a null-terminated wide string.
  2797. // Parameter num_chars may additionally limit the number
  2798. // of wchar_t characters processed. -1 is used when the entire string
  2799. // should be processed.
  2800. // If the string contains code points that are not valid Unicode code points
  2801. // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
  2802. // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
  2803. // and contains invalid UTF-16 surrogate pairs, values in those pairs
  2804. // will be encoded as individual Unicode characters from Basic Normal Plane.
  2805. std::string WideStringToUtf8(const wchar_t* str, int num_chars) {
  2806. if (num_chars == -1)
  2807. num_chars = static_cast<int>(wcslen(str));
  2808. ::std::stringstream stream;
  2809. for (int i = 0; i < num_chars; ++i) {
  2810. UInt32 unicode_code_point;
  2811. if (str[i] == L'\0') {
  2812. break;
  2813. } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
  2814. unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i],
  2815. str[i + 1]);
  2816. i++;
  2817. } else {
  2818. unicode_code_point = static_cast<UInt32>(str[i]);
  2819. }
  2820. stream << CodePointToUtf8(unicode_code_point);
  2821. }
  2822. return StringStreamToString(&stream);
  2823. }
  2824. // Converts a wide C string to an std::string using the UTF-8 encoding.
  2825. // NULL will be converted to "(null)".
  2826. std::string String::ShowWideCString(const wchar_t * wide_c_str) {
  2827. if (wide_c_str == nullptr) return "(null)";
  2828. return internal::WideStringToUtf8(wide_c_str, -1);
  2829. }
  2830. // Compares two wide C strings. Returns true iff they have the same
  2831. // content.
  2832. //
  2833. // Unlike wcscmp(), this function can handle NULL argument(s). A NULL
  2834. // C string is considered different to any non-NULL C string,
  2835. // including the empty string.
  2836. bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {
  2837. if (lhs == nullptr) return rhs == nullptr;
  2838. if (rhs == nullptr) return false;
  2839. return wcscmp(lhs, rhs) == 0;
  2840. }
  2841. // Helper function for *_STREQ on wide strings.
  2842. AssertionResult CmpHelperSTREQ(const char* lhs_expression,
  2843. const char* rhs_expression,
  2844. const wchar_t* lhs,
  2845. const wchar_t* rhs) {
  2846. if (String::WideCStringEquals(lhs, rhs)) {
  2847. return AssertionSuccess();
  2848. }
  2849. return EqFailure(lhs_expression,
  2850. rhs_expression,
  2851. PrintToString(lhs),
  2852. PrintToString(rhs),
  2853. false);
  2854. }
  2855. // Helper function for *_STRNE on wide strings.
  2856. AssertionResult CmpHelperSTRNE(const char* s1_expression,
  2857. const char* s2_expression,
  2858. const wchar_t* s1,
  2859. const wchar_t* s2) {
  2860. if (!String::WideCStringEquals(s1, s2)) {
  2861. return AssertionSuccess();
  2862. }
  2863. return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
  2864. << s2_expression << "), actual: "
  2865. << PrintToString(s1)
  2866. << " vs " << PrintToString(s2);
  2867. }
  2868. // Compares two C strings, ignoring case. Returns true iff they have
  2869. // the same content.
  2870. //
  2871. // Unlike strcasecmp(), this function can handle NULL argument(s). A
  2872. // NULL C string is considered different to any non-NULL C string,
  2873. // including the empty string.
  2874. bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) {
  2875. if (lhs == nullptr) return rhs == nullptr;
  2876. if (rhs == nullptr) return false;
  2877. return posix::StrCaseCmp(lhs, rhs) == 0;
  2878. }
  2879. // Compares two wide C strings, ignoring case. Returns true iff they
  2880. // have the same content.
  2881. //
  2882. // Unlike wcscasecmp(), this function can handle NULL argument(s).
  2883. // A NULL C string is considered different to any non-NULL wide C string,
  2884. // including the empty string.
  2885. // NB: The implementations on different platforms slightly differ.
  2886. // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
  2887. // environment variable. On GNU platform this method uses wcscasecmp
  2888. // which compares according to LC_CTYPE category of the current locale.
  2889. // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
  2890. // current locale.
  2891. bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
  2892. const wchar_t* rhs) {
  2893. if (lhs == nullptr) return rhs == nullptr;
  2894. if (rhs == nullptr) return false;
  2895. #if GTEST_OS_WINDOWS
  2896. return _wcsicmp(lhs, rhs) == 0;
  2897. #elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID
  2898. return wcscasecmp(lhs, rhs) == 0;
  2899. #else
  2900. // Android, Mac OS X and Cygwin don't define wcscasecmp.
  2901. // Other unknown OSes may not define it either.
  2902. wint_t left, right;
  2903. do {
  2904. left = towlower(*lhs++);
  2905. right = towlower(*rhs++);
  2906. } while (left && left == right);
  2907. return left == right;
  2908. #endif // OS selector
  2909. }
  2910. // Returns true iff str ends with the given suffix, ignoring case.
  2911. // Any string is considered to end with an empty suffix.
  2912. bool String::EndsWithCaseInsensitive(
  2913. const std::string& str, const std::string& suffix) {
  2914. const size_t str_len = str.length();
  2915. const size_t suffix_len = suffix.length();
  2916. return (str_len >= suffix_len) &&
  2917. CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len,
  2918. suffix.c_str());
  2919. }
  2920. // Formats an int value as "%02d".
  2921. std::string String::FormatIntWidth2(int value) {
  2922. std::stringstream ss;
  2923. ss << std::setfill('0') << std::setw(2) << value;
  2924. return ss.str();
  2925. }
  2926. // Formats an int value as "%X".
  2927. std::string String::FormatHexInt(int value) {
  2928. std::stringstream ss;
  2929. ss << std::hex << std::uppercase << value;
  2930. return ss.str();
  2931. }
  2932. // Formats a byte as "%02X".
  2933. std::string String::FormatByte(unsigned char value) {
  2934. std::stringstream ss;
  2935. ss << std::setfill('0') << std::setw(2) << std::hex << std::uppercase
  2936. << static_cast<unsigned int>(value);
  2937. return ss.str();
  2938. }
  2939. // Converts the buffer in a stringstream to an std::string, converting NUL
  2940. // bytes to "\\0" along the way.
  2941. std::string StringStreamToString(::std::stringstream* ss) {
  2942. const ::std::string& str = ss->str();
  2943. const char* const start = str.c_str();
  2944. const char* const end = start + str.length();
  2945. std::string result;
  2946. result.reserve(2 * (end - start));
  2947. for (const char* ch = start; ch != end; ++ch) {
  2948. if (*ch == '\0') {
  2949. result += "\\0"; // Replaces NUL with "\\0";
  2950. } else {
  2951. result += *ch;
  2952. }
  2953. }
  2954. return result;
  2955. }
  2956. // Appends the user-supplied message to the Google-Test-generated message.
  2957. std::string AppendUserMessage(const std::string& gtest_msg,
  2958. const Message& user_msg) {
  2959. // Appends the user message if it's non-empty.
  2960. const std::string user_msg_string = user_msg.GetString();
  2961. if (user_msg_string.empty()) {
  2962. return gtest_msg;
  2963. }
  2964. return gtest_msg + "\n" + user_msg_string;
  2965. }
  2966. } // namespace internal
  2967. // class TestResult
  2968. // Creates an empty TestResult.
  2969. TestResult::TestResult()
  2970. : death_test_count_(0),
  2971. elapsed_time_(0) {
  2972. }
  2973. // D'tor.
  2974. TestResult::~TestResult() {
  2975. }
  2976. // Returns the i-th test part result among all the results. i can
  2977. // range from 0 to total_part_count() - 1. If i is not in that range,
  2978. // aborts the program.
  2979. const TestPartResult& TestResult::GetTestPartResult(int i) const {
  2980. if (i < 0 || i >= total_part_count())
  2981. internal::posix::Abort();
  2982. return test_part_results_.at(i);
  2983. }
  2984. // Returns the i-th test property. i can range from 0 to
  2985. // test_property_count() - 1. If i is not in that range, aborts the
  2986. // program.
  2987. const TestProperty& TestResult::GetTestProperty(int i) const {
  2988. if (i < 0 || i >= test_property_count())
  2989. internal::posix::Abort();
  2990. return test_properties_.at(i);
  2991. }
  2992. // Clears the test part results.
  2993. void TestResult::ClearTestPartResults() {
  2994. test_part_results_.clear();
  2995. }
  2996. // Adds a test part result to the list.
  2997. void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
  2998. test_part_results_.push_back(test_part_result);
  2999. }
  3000. // Adds a test property to the list. If a property with the same key as the
  3001. // supplied property is already represented, the value of this test_property
  3002. // replaces the old value for that key.
  3003. void TestResult::RecordProperty(const std::string& xml_element,
  3004. const TestProperty& test_property) {
  3005. if (!ValidateTestProperty(xml_element, test_property)) {
  3006. return;
  3007. }
  3008. internal::MutexLock lock(&test_properites_mutex_);
  3009. const std::vector<TestProperty>::iterator property_with_matching_key =
  3010. std::find_if(test_properties_.begin(), test_properties_.end(),
  3011. internal::TestPropertyKeyIs(test_property.key()));
  3012. if (property_with_matching_key == test_properties_.end()) {
  3013. test_properties_.push_back(test_property);
  3014. return;
  3015. }
  3016. property_with_matching_key->SetValue(test_property.value());
  3017. }
  3018. // The list of reserved attributes used in the <testsuites> element of XML
  3019. // output.
  3020. static const char* const kReservedTestSuitesAttributes[] = {
  3021. "disabled",
  3022. "errors",
  3023. "failures",
  3024. "name",
  3025. "random_seed",
  3026. "tests",
  3027. "time",
  3028. "timestamp"
  3029. };
  3030. // The list of reserved attributes used in the <testsuite> element of XML
  3031. // output.
  3032. static const char* const kReservedTestSuiteAttributes[] = {
  3033. "disabled",
  3034. "errors",
  3035. "failures",
  3036. "name",
  3037. "tests",
  3038. "time"
  3039. };
  3040. // The list of reserved attributes used in the <testcase> element of XML output.
  3041. static const char* const kReservedTestCaseAttributes[] = {
  3042. "classname", "name", "status", "time",
  3043. "type_param", "value_param", "file", "line"};
  3044. template <int kSize>
  3045. std::vector<std::string> ArrayAsVector(const char* const (&array)[kSize]) {
  3046. return std::vector<std::string>(array, array + kSize);
  3047. }
  3048. static std::vector<std::string> GetReservedAttributesForElement(
  3049. const std::string& xml_element) {
  3050. if (xml_element == "testsuites") {
  3051. return ArrayAsVector(kReservedTestSuitesAttributes);
  3052. } else if (xml_element == "testsuite") {
  3053. return ArrayAsVector(kReservedTestSuiteAttributes);
  3054. } else if (xml_element == "testcase") {
  3055. return ArrayAsVector(kReservedTestCaseAttributes);
  3056. } else {
  3057. GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element;
  3058. }
  3059. // This code is unreachable but some compilers may not realizes that.
  3060. return std::vector<std::string>();
  3061. }
  3062. static std::string FormatWordList(const std::vector<std::string>& words) {
  3063. Message word_list;
  3064. for (size_t i = 0; i < words.size(); ++i) {
  3065. if (i > 0 && words.size() > 2) {
  3066. word_list << ", ";
  3067. }
  3068. if (i == words.size() - 1) {
  3069. word_list << "and ";
  3070. }
  3071. word_list << "'" << words[i] << "'";
  3072. }
  3073. return word_list.GetString();
  3074. }
  3075. static bool ValidateTestPropertyName(
  3076. const std::string& property_name,
  3077. const std::vector<std::string>& reserved_names) {
  3078. if (std::find(reserved_names.begin(), reserved_names.end(), property_name) !=
  3079. reserved_names.end()) {
  3080. ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name
  3081. << " (" << FormatWordList(reserved_names)
  3082. << " are reserved by " << GTEST_NAME_ << ")";
  3083. return false;
  3084. }
  3085. return true;
  3086. }
  3087. // Adds a failure if the key is a reserved attribute of the element named
  3088. // xml_element. Returns true if the property is valid.
  3089. bool TestResult::ValidateTestProperty(const std::string& xml_element,
  3090. const TestProperty& test_property) {
  3091. return ValidateTestPropertyName(test_property.key(),
  3092. GetReservedAttributesForElement(xml_element));
  3093. }
  3094. // Clears the object.
  3095. void TestResult::Clear() {
  3096. test_part_results_.clear();
  3097. test_properties_.clear();
  3098. death_test_count_ = 0;
  3099. elapsed_time_ = 0;
  3100. }
  3101. // Returns true off the test part was skipped.
  3102. static bool TestPartSkipped(const TestPartResult& result) {
  3103. return result.skipped();
  3104. }
  3105. // Returns true iff the test was skipped.
  3106. bool TestResult::Skipped() const {
  3107. return !Failed() && CountIf(test_part_results_, TestPartSkipped) > 0;
  3108. }
  3109. // Returns true iff the test failed.
  3110. bool TestResult::Failed() const {
  3111. for (int i = 0; i < total_part_count(); ++i) {
  3112. if (GetTestPartResult(i).failed())
  3113. return true;
  3114. }
  3115. return false;
  3116. }
  3117. // Returns true iff the test part fatally failed.
  3118. static bool TestPartFatallyFailed(const TestPartResult& result) {
  3119. return result.fatally_failed();
  3120. }
  3121. // Returns true iff the test fatally failed.
  3122. bool TestResult::HasFatalFailure() const {
  3123. return CountIf(test_part_results_, TestPartFatallyFailed) > 0;
  3124. }
  3125. // Returns true iff the test part non-fatally failed.
  3126. static bool TestPartNonfatallyFailed(const TestPartResult& result) {
  3127. return result.nonfatally_failed();
  3128. }
  3129. // Returns true iff the test has a non-fatal failure.
  3130. bool TestResult::HasNonfatalFailure() const {
  3131. return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0;
  3132. }
  3133. // Gets the number of all test parts. This is the sum of the number
  3134. // of successful test parts and the number of failed test parts.
  3135. int TestResult::total_part_count() const {
  3136. return static_cast<int>(test_part_results_.size());
  3137. }
  3138. // Returns the number of the test properties.
  3139. int TestResult::test_property_count() const {
  3140. return static_cast<int>(test_properties_.size());
  3141. }
  3142. // class Test
  3143. // Creates a Test object.
  3144. // The c'tor saves the states of all flags.
  3145. Test::Test()
  3146. : gtest_flag_saver_(new GTEST_FLAG_SAVER_) {
  3147. }
  3148. // The d'tor restores the states of all flags. The actual work is
  3149. // done by the d'tor of the gtest_flag_saver_ field, and thus not
  3150. // visible here.
  3151. Test::~Test() {
  3152. }
  3153. // Sets up the test fixture.
  3154. //
  3155. // A sub-class may override this.
  3156. void Test::SetUp() {
  3157. }
  3158. // Tears down the test fixture.
  3159. //
  3160. // A sub-class may override this.
  3161. void Test::TearDown() {
  3162. }
  3163. // Allows user supplied key value pairs to be recorded for later output.
  3164. void Test::RecordProperty(const std::string& key, const std::string& value) {
  3165. UnitTest::GetInstance()->RecordProperty(key, value);
  3166. }
  3167. // Allows user supplied key value pairs to be recorded for later output.
  3168. void Test::RecordProperty(const std::string& key, int value) {
  3169. Message value_message;
  3170. value_message << value;
  3171. RecordProperty(key, value_message.GetString().c_str());
  3172. }
  3173. namespace internal {
  3174. void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
  3175. const std::string& message) {
  3176. // This function is a friend of UnitTest and as such has access to
  3177. // AddTestPartResult.
  3178. UnitTest::GetInstance()->AddTestPartResult(
  3179. result_type,
  3180. nullptr, // No info about the source file where the exception occurred.
  3181. -1, // We have no info on which line caused the exception.
  3182. message,
  3183. ""); // No stack trace, either.
  3184. }
  3185. } // namespace internal
  3186. // Google Test requires all tests in the same test suite to use the same test
  3187. // fixture class. This function checks if the current test has the
  3188. // same fixture class as the first test in the current test suite. If
  3189. // yes, it returns true; otherwise it generates a Google Test failure and
  3190. // returns false.
  3191. bool Test::HasSameFixtureClass() {
  3192. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  3193. const TestSuite* const test_suite = impl->current_test_suite();
  3194. // Info about the first test in the current test suite.
  3195. const TestInfo* const first_test_info = test_suite->test_info_list()[0];
  3196. const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_;
  3197. const char* const first_test_name = first_test_info->name();
  3198. // Info about the current test.
  3199. const TestInfo* const this_test_info = impl->current_test_info();
  3200. const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_;
  3201. const char* const this_test_name = this_test_info->name();
  3202. if (this_fixture_id != first_fixture_id) {
  3203. // Is the first test defined using TEST?
  3204. const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();
  3205. // Is this test defined using TEST?
  3206. const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();
  3207. if (first_is_TEST || this_is_TEST) {
  3208. // Both TEST and TEST_F appear in same test suite, which is incorrect.
  3209. // Tell the user how to fix this.
  3210. // Gets the name of the TEST and the name of the TEST_F. Note
  3211. // that first_is_TEST and this_is_TEST cannot both be true, as
  3212. // the fixture IDs are different for the two tests.
  3213. const char* const TEST_name =
  3214. first_is_TEST ? first_test_name : this_test_name;
  3215. const char* const TEST_F_name =
  3216. first_is_TEST ? this_test_name : first_test_name;
  3217. ADD_FAILURE()
  3218. << "All tests in the same test suite must use the same test fixture\n"
  3219. << "class, so mixing TEST_F and TEST in the same test suite is\n"
  3220. << "illegal. In test suite " << this_test_info->test_suite_name()
  3221. << ",\n"
  3222. << "test " << TEST_F_name << " is defined using TEST_F but\n"
  3223. << "test " << TEST_name << " is defined using TEST. You probably\n"
  3224. << "want to change the TEST to TEST_F or move it to another test\n"
  3225. << "case.";
  3226. } else {
  3227. // Two fixture classes with the same name appear in two different
  3228. // namespaces, which is not allowed. Tell the user how to fix this.
  3229. ADD_FAILURE()
  3230. << "All tests in the same test suite must use the same test fixture\n"
  3231. << "class. However, in test suite "
  3232. << this_test_info->test_suite_name() << ",\n"
  3233. << "you defined test " << first_test_name << " and test "
  3234. << this_test_name << "\n"
  3235. << "using two different test fixture classes. This can happen if\n"
  3236. << "the two classes are from different namespaces or translation\n"
  3237. << "units and have the same name. You should probably rename one\n"
  3238. << "of the classes to put the tests into different test suites.";
  3239. }
  3240. return false;
  3241. }
  3242. return true;
  3243. }
  3244. #if GTEST_HAS_SEH
  3245. // Adds an "exception thrown" fatal failure to the current test. This
  3246. // function returns its result via an output parameter pointer because VC++
  3247. // prohibits creation of objects with destructors on stack in functions
  3248. // using __try (see error C2712).
  3249. static std::string* FormatSehExceptionMessage(DWORD exception_code,
  3250. const char* location) {
  3251. Message message;
  3252. message << "SEH exception with code 0x" << std::setbase(16) <<
  3253. exception_code << std::setbase(10) << " thrown in " << location << ".";
  3254. return new std::string(message.GetString());
  3255. }
  3256. #endif // GTEST_HAS_SEH
  3257. namespace internal {
  3258. #if GTEST_HAS_EXCEPTIONS
  3259. // Adds an "exception thrown" fatal failure to the current test.
  3260. static std::string FormatCxxExceptionMessage(const char* description,
  3261. const char* location) {
  3262. Message message;
  3263. if (description != nullptr) {
  3264. message << "C++ exception with description \"" << description << "\"";
  3265. } else {
  3266. message << "Unknown C++ exception";
  3267. }
  3268. message << " thrown in " << location << ".";
  3269. return message.GetString();
  3270. }
  3271. static std::string PrintTestPartResultToString(
  3272. const TestPartResult& test_part_result);
  3273. GoogleTestFailureException::GoogleTestFailureException(
  3274. const TestPartResult& failure)
  3275. : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
  3276. #endif // GTEST_HAS_EXCEPTIONS
  3277. // We put these helper functions in the internal namespace as IBM's xlC
  3278. // compiler rejects the code if they were declared static.
  3279. // Runs the given method and handles SEH exceptions it throws, when
  3280. // SEH is supported; returns the 0-value for type Result in case of an
  3281. // SEH exception. (Microsoft compilers cannot handle SEH and C++
  3282. // exceptions in the same function. Therefore, we provide a separate
  3283. // wrapper function for handling SEH exceptions.)
  3284. template <class T, typename Result>
  3285. Result HandleSehExceptionsInMethodIfSupported(
  3286. T* object, Result (T::*method)(), const char* location) {
  3287. #if GTEST_HAS_SEH
  3288. __try {
  3289. return (object->*method)();
  3290. } __except (internal::UnitTestOptions::GTestShouldProcessSEH( // NOLINT
  3291. GetExceptionCode())) {
  3292. // We create the exception message on the heap because VC++ prohibits
  3293. // creation of objects with destructors on stack in functions using __try
  3294. // (see error C2712).
  3295. std::string* exception_message = FormatSehExceptionMessage(
  3296. GetExceptionCode(), location);
  3297. internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
  3298. *exception_message);
  3299. delete exception_message;
  3300. return static_cast<Result>(0);
  3301. }
  3302. #else
  3303. (void)location;
  3304. return (object->*method)();
  3305. #endif // GTEST_HAS_SEH
  3306. }
  3307. // Runs the given method and catches and reports C++ and/or SEH-style
  3308. // exceptions, if they are supported; returns the 0-value for type
  3309. // Result in case of an SEH exception.
  3310. template <class T, typename Result>
  3311. Result HandleExceptionsInMethodIfSupported(
  3312. T* object, Result (T::*method)(), const char* location) {
  3313. // NOTE: The user code can affect the way in which Google Test handles
  3314. // exceptions by setting GTEST_FLAG(catch_exceptions), but only before
  3315. // RUN_ALL_TESTS() starts. It is technically possible to check the flag
  3316. // after the exception is caught and either report or re-throw the
  3317. // exception based on the flag's value:
  3318. //
  3319. // try {
  3320. // // Perform the test method.
  3321. // } catch (...) {
  3322. // if (GTEST_FLAG(catch_exceptions))
  3323. // // Report the exception as failure.
  3324. // else
  3325. // throw; // Re-throws the original exception.
  3326. // }
  3327. //
  3328. // However, the purpose of this flag is to allow the program to drop into
  3329. // the debugger when the exception is thrown. On most platforms, once the
  3330. // control enters the catch block, the exception origin information is
  3331. // lost and the debugger will stop the program at the point of the
  3332. // re-throw in this function -- instead of at the point of the original
  3333. // throw statement in the code under test. For this reason, we perform
  3334. // the check early, sacrificing the ability to affect Google Test's
  3335. // exception handling in the method where the exception is thrown.
  3336. if (internal::GetUnitTestImpl()->catch_exceptions()) {
  3337. #if GTEST_HAS_EXCEPTIONS
  3338. try {
  3339. return HandleSehExceptionsInMethodIfSupported(object, method, location);
  3340. } catch (const AssertionException&) { // NOLINT
  3341. // This failure was reported already.
  3342. } catch (const internal::GoogleTestFailureException&) { // NOLINT
  3343. // This exception type can only be thrown by a failed Google
  3344. // Test assertion with the intention of letting another testing
  3345. // framework catch it. Therefore we just re-throw it.
  3346. throw;
  3347. } catch (const std::exception& e) { // NOLINT
  3348. internal::ReportFailureInUnknownLocation(
  3349. TestPartResult::kFatalFailure,
  3350. FormatCxxExceptionMessage(e.what(), location));
  3351. } catch (...) { // NOLINT
  3352. internal::ReportFailureInUnknownLocation(
  3353. TestPartResult::kFatalFailure,
  3354. FormatCxxExceptionMessage(nullptr, location));
  3355. }
  3356. return static_cast<Result>(0);
  3357. #else
  3358. return HandleSehExceptionsInMethodIfSupported(object, method, location);
  3359. #endif // GTEST_HAS_EXCEPTIONS
  3360. } else {
  3361. return (object->*method)();
  3362. }
  3363. }
  3364. } // namespace internal
  3365. // Runs the test and updates the test result.
  3366. void Test::Run() {
  3367. if (!HasSameFixtureClass()) return;
  3368. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  3369. impl->os_stack_trace_getter()->UponLeavingGTest();
  3370. internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()");
  3371. // We will run the test only if SetUp() was successful and didn't call
  3372. // GTEST_SKIP().
  3373. if (!HasFatalFailure() && !IsSkipped()) {
  3374. impl->os_stack_trace_getter()->UponLeavingGTest();
  3375. internal::HandleExceptionsInMethodIfSupported(
  3376. this, &Test::TestBody, "the test body");
  3377. }
  3378. // However, we want to clean up as much as possible. Hence we will
  3379. // always call TearDown(), even if SetUp() or the test body has
  3380. // failed.
  3381. impl->os_stack_trace_getter()->UponLeavingGTest();
  3382. internal::HandleExceptionsInMethodIfSupported(
  3383. this, &Test::TearDown, "TearDown()");
  3384. }
  3385. // Returns true iff the current test has a fatal failure.
  3386. bool Test::HasFatalFailure() {
  3387. return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
  3388. }
  3389. // Returns true iff the current test has a non-fatal failure.
  3390. bool Test::HasNonfatalFailure() {
  3391. return internal::GetUnitTestImpl()->current_test_result()->
  3392. HasNonfatalFailure();
  3393. }
  3394. // Returns true iff the current test was skipped.
  3395. bool Test::IsSkipped() {
  3396. return internal::GetUnitTestImpl()->current_test_result()->Skipped();
  3397. }
  3398. // class TestInfo
  3399. // Constructs a TestInfo object. It assumes ownership of the test factory
  3400. // object.
  3401. TestInfo::TestInfo(const std::string& a_test_suite_name,
  3402. const std::string& a_name, const char* a_type_param,
  3403. const char* a_value_param,
  3404. internal::CodeLocation a_code_location,
  3405. internal::TypeId fixture_class_id,
  3406. internal::TestFactoryBase* factory)
  3407. : test_suite_name_(a_test_suite_name),
  3408. name_(a_name),
  3409. type_param_(a_type_param ? new std::string(a_type_param) : nullptr),
  3410. value_param_(a_value_param ? new std::string(a_value_param) : nullptr),
  3411. location_(a_code_location),
  3412. fixture_class_id_(fixture_class_id),
  3413. should_run_(false),
  3414. is_disabled_(false),
  3415. matches_filter_(false),
  3416. factory_(factory),
  3417. result_() {}
  3418. // Destructs a TestInfo object.
  3419. TestInfo::~TestInfo() { delete factory_; }
  3420. namespace internal {
  3421. // Creates a new TestInfo object and registers it with Google Test;
  3422. // returns the created object.
  3423. //
  3424. // Arguments:
  3425. //
  3426. // test_suite_name: name of the test suite
  3427. // name: name of the test
  3428. // type_param: the name of the test's type parameter, or NULL if
  3429. // this is not a typed or a type-parameterized test.
  3430. // value_param: text representation of the test's value parameter,
  3431. // or NULL if this is not a value-parameterized test.
  3432. // code_location: code location where the test is defined
  3433. // fixture_class_id: ID of the test fixture class
  3434. // set_up_tc: pointer to the function that sets up the test suite
  3435. // tear_down_tc: pointer to the function that tears down the test suite
  3436. // factory: pointer to the factory that creates a test object.
  3437. // The newly created TestInfo instance will assume
  3438. // ownership of the factory object.
  3439. TestInfo* MakeAndRegisterTestInfo(
  3440. const char* test_suite_name, const char* name, const char* type_param,
  3441. const char* value_param, CodeLocation code_location,
  3442. TypeId fixture_class_id, SetUpTestSuiteFunc set_up_tc,
  3443. TearDownTestSuiteFunc tear_down_tc, TestFactoryBase* factory) {
  3444. TestInfo* const test_info =
  3445. new TestInfo(test_suite_name, name, type_param, value_param,
  3446. code_location, fixture_class_id, factory);
  3447. GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
  3448. return test_info;
  3449. }
  3450. void ReportInvalidTestSuiteType(const char* test_suite_name,
  3451. CodeLocation code_location) {
  3452. Message errors;
  3453. errors
  3454. << "Attempted redefinition of test suite " << test_suite_name << ".\n"
  3455. << "All tests in the same test suite must use the same test fixture\n"
  3456. << "class. However, in test suite " << test_suite_name << ", you tried\n"
  3457. << "to define a test using a fixture class different from the one\n"
  3458. << "used earlier. This can happen if the two fixture classes are\n"
  3459. << "from different namespaces and have the same name. You should\n"
  3460. << "probably rename one of the classes to put the tests into different\n"
  3461. << "test suites.";
  3462. GTEST_LOG_(ERROR) << FormatFileLocation(code_location.file.c_str(),
  3463. code_location.line)
  3464. << " " << errors.GetString();
  3465. }
  3466. } // namespace internal
  3467. namespace {
  3468. // A predicate that checks the test name of a TestInfo against a known
  3469. // value.
  3470. //
  3471. // This is used for implementation of the TestSuite class only. We put
  3472. // it in the anonymous namespace to prevent polluting the outer
  3473. // namespace.
  3474. //
  3475. // TestNameIs is copyable.
  3476. class TestNameIs {
  3477. public:
  3478. // Constructor.
  3479. //
  3480. // TestNameIs has NO default constructor.
  3481. explicit TestNameIs(const char* name)
  3482. : name_(name) {}
  3483. // Returns true iff the test name of test_info matches name_.
  3484. bool operator()(const TestInfo * test_info) const {
  3485. return test_info && test_info->name() == name_;
  3486. }
  3487. private:
  3488. std::string name_;
  3489. };
  3490. } // namespace
  3491. namespace internal {
  3492. // This method expands all parameterized tests registered with macros TEST_P
  3493. // and INSTANTIATE_TEST_SUITE_P into regular tests and registers those.
  3494. // This will be done just once during the program runtime.
  3495. void UnitTestImpl::RegisterParameterizedTests() {
  3496. if (!parameterized_tests_registered_) {
  3497. parameterized_test_registry_.RegisterTests();
  3498. parameterized_tests_registered_ = true;
  3499. }
  3500. }
  3501. } // namespace internal
  3502. // Creates the test object, runs it, records its result, and then
  3503. // deletes it.
  3504. void TestInfo::Run() {
  3505. if (!should_run_) return;
  3506. // Tells UnitTest where to store test result.
  3507. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  3508. impl->set_current_test_info(this);
  3509. TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
  3510. // Notifies the unit test event listeners that a test is about to start.
  3511. repeater->OnTestStart(*this);
  3512. const TimeInMillis start = internal::GetTimeInMillis();
  3513. impl->os_stack_trace_getter()->UponLeavingGTest();
  3514. // Creates the test object.
  3515. Test* const test = internal::HandleExceptionsInMethodIfSupported(
  3516. factory_, &internal::TestFactoryBase::CreateTest,
  3517. "the test fixture's constructor");
  3518. // Runs the test if the constructor didn't generate a fatal failure or invoke
  3519. // GTEST_SKIP().
  3520. // Note that the object will not be null
  3521. if (!Test::HasFatalFailure() && !Test::IsSkipped()) {
  3522. // This doesn't throw as all user code that can throw are wrapped into
  3523. // exception handling code.
  3524. test->Run();
  3525. }
  3526. // Deletes the test object.
  3527. impl->os_stack_trace_getter()->UponLeavingGTest();
  3528. internal::HandleExceptionsInMethodIfSupported(
  3529. test, &Test::DeleteSelf_, "the test fixture's destructor");
  3530. result_.set_elapsed_time(internal::GetTimeInMillis() - start);
  3531. // Notifies the unit test event listener that a test has just finished.
  3532. repeater->OnTestEnd(*this);
  3533. // Tells UnitTest to stop associating assertion results to this
  3534. // test.
  3535. impl->set_current_test_info(nullptr);
  3536. }
  3537. // class TestSuite
  3538. // Gets the number of successful tests in this test suite.
  3539. int TestSuite::successful_test_count() const {
  3540. return CountIf(test_info_list_, TestPassed);
  3541. }
  3542. // Gets the number of successful tests in this test suite.
  3543. int TestSuite::skipped_test_count() const {
  3544. return CountIf(test_info_list_, TestSkipped);
  3545. }
  3546. // Gets the number of failed tests in this test suite.
  3547. int TestSuite::failed_test_count() const {
  3548. return CountIf(test_info_list_, TestFailed);
  3549. }
  3550. // Gets the number of disabled tests that will be reported in the XML report.
  3551. int TestSuite::reportable_disabled_test_count() const {
  3552. return CountIf(test_info_list_, TestReportableDisabled);
  3553. }
  3554. // Gets the number of disabled tests in this test suite.
  3555. int TestSuite::disabled_test_count() const {
  3556. return CountIf(test_info_list_, TestDisabled);
  3557. }
  3558. // Gets the number of tests to be printed in the XML report.
  3559. int TestSuite::reportable_test_count() const {
  3560. return CountIf(test_info_list_, TestReportable);
  3561. }
  3562. // Get the number of tests in this test suite that should run.
  3563. int TestSuite::test_to_run_count() const {
  3564. return CountIf(test_info_list_, ShouldRunTest);
  3565. }
  3566. // Gets the number of all tests.
  3567. int TestSuite::total_test_count() const {
  3568. return static_cast<int>(test_info_list_.size());
  3569. }
  3570. // Creates a TestSuite with the given name.
  3571. //
  3572. // Arguments:
  3573. //
  3574. // name: name of the test suite
  3575. // a_type_param: the name of the test suite's type parameter, or NULL if
  3576. // this is not a typed or a type-parameterized test suite.
  3577. // set_up_tc: pointer to the function that sets up the test suite
  3578. // tear_down_tc: pointer to the function that tears down the test suite
  3579. TestSuite::TestSuite(const char* a_name, const char* a_type_param,
  3580. internal::SetUpTestSuiteFunc set_up_tc,
  3581. internal::TearDownTestSuiteFunc tear_down_tc)
  3582. : name_(a_name),
  3583. type_param_(a_type_param ? new std::string(a_type_param) : nullptr),
  3584. set_up_tc_(set_up_tc),
  3585. tear_down_tc_(tear_down_tc),
  3586. should_run_(false),
  3587. elapsed_time_(0) {}
  3588. // Destructor of TestSuite.
  3589. TestSuite::~TestSuite() {
  3590. // Deletes every Test in the collection.
  3591. ForEach(test_info_list_, internal::Delete<TestInfo>);
  3592. }
  3593. // Returns the i-th test among all the tests. i can range from 0 to
  3594. // total_test_count() - 1. If i is not in that range, returns NULL.
  3595. const TestInfo* TestSuite::GetTestInfo(int i) const {
  3596. const int index = GetElementOr(test_indices_, i, -1);
  3597. return index < 0 ? nullptr : test_info_list_[index];
  3598. }
  3599. // Returns the i-th test among all the tests. i can range from 0 to
  3600. // total_test_count() - 1. If i is not in that range, returns NULL.
  3601. TestInfo* TestSuite::GetMutableTestInfo(int i) {
  3602. const int index = GetElementOr(test_indices_, i, -1);
  3603. return index < 0 ? nullptr : test_info_list_[index];
  3604. }
  3605. // Adds a test to this test suite. Will delete the test upon
  3606. // destruction of the TestSuite object.
  3607. void TestSuite::AddTestInfo(TestInfo* test_info) {
  3608. test_info_list_.push_back(test_info);
  3609. test_indices_.push_back(static_cast<int>(test_indices_.size()));
  3610. }
  3611. // Runs every test in this TestSuite.
  3612. void TestSuite::Run() {
  3613. if (!should_run_) return;
  3614. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  3615. impl->set_current_test_suite(this);
  3616. TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
  3617. // Call both legacy and the new API
  3618. repeater->OnTestSuiteStart(*this);
  3619. // Legacy API is deprecated but still available
  3620. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI
  3621. repeater->OnTestCaseStart(*this);
  3622. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI
  3623. impl->os_stack_trace_getter()->UponLeavingGTest();
  3624. internal::HandleExceptionsInMethodIfSupported(
  3625. this, &TestSuite::RunSetUpTestSuite, "SetUpTestSuite()");
  3626. const internal::TimeInMillis start = internal::GetTimeInMillis();
  3627. for (int i = 0; i < total_test_count(); i++) {
  3628. GetMutableTestInfo(i)->Run();
  3629. }
  3630. elapsed_time_ = internal::GetTimeInMillis() - start;
  3631. impl->os_stack_trace_getter()->UponLeavingGTest();
  3632. internal::HandleExceptionsInMethodIfSupported(
  3633. this, &TestSuite::RunTearDownTestSuite, "TearDownTestSuite()");
  3634. // Call both legacy and the new API
  3635. repeater->OnTestSuiteEnd(*this);
  3636. // Legacy API is deprecated but still available
  3637. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI
  3638. repeater->OnTestCaseEnd(*this);
  3639. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI
  3640. impl->set_current_test_suite(nullptr);
  3641. }
  3642. // Clears the results of all tests in this test suite.
  3643. void TestSuite::ClearResult() {
  3644. ad_hoc_test_result_.Clear();
  3645. ForEach(test_info_list_, TestInfo::ClearTestResult);
  3646. }
  3647. // Shuffles the tests in this test suite.
  3648. void TestSuite::ShuffleTests(internal::Random* random) {
  3649. Shuffle(random, &test_indices_);
  3650. }
  3651. // Restores the test order to before the first shuffle.
  3652. void TestSuite::UnshuffleTests() {
  3653. for (size_t i = 0; i < test_indices_.size(); i++) {
  3654. test_indices_[i] = static_cast<int>(i);
  3655. }
  3656. }
  3657. // Formats a countable noun. Depending on its quantity, either the
  3658. // singular form or the plural form is used. e.g.
  3659. //
  3660. // FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
  3661. // FormatCountableNoun(5, "book", "books") returns "5 books".
  3662. static std::string FormatCountableNoun(int count,
  3663. const char * singular_form,
  3664. const char * plural_form) {
  3665. return internal::StreamableToString(count) + " " +
  3666. (count == 1 ? singular_form : plural_form);
  3667. }
  3668. // Formats the count of tests.
  3669. static std::string FormatTestCount(int test_count) {
  3670. return FormatCountableNoun(test_count, "test", "tests");
  3671. }
  3672. // Formats the count of test suites.
  3673. static std::string FormatTestSuiteCount(int test_suite_count) {
  3674. return FormatCountableNoun(test_suite_count, "test suite", "test suites");
  3675. }
  3676. // Converts a TestPartResult::Type enum to human-friendly string
  3677. // representation. Both kNonFatalFailure and kFatalFailure are translated
  3678. // to "Failure", as the user usually doesn't care about the difference
  3679. // between the two when viewing the test result.
  3680. static const char * TestPartResultTypeToString(TestPartResult::Type type) {
  3681. switch (type) {
  3682. case TestPartResult::kSkip:
  3683. return "Skipped";
  3684. case TestPartResult::kSuccess:
  3685. return "Success";
  3686. case TestPartResult::kNonFatalFailure:
  3687. case TestPartResult::kFatalFailure:
  3688. #ifdef _MSC_VER
  3689. return "error: ";
  3690. #else
  3691. return "Failure\n";
  3692. #endif
  3693. default:
  3694. return "Unknown result type";
  3695. }
  3696. }
  3697. namespace internal {
  3698. // Prints a TestPartResult to an std::string.
  3699. static std::string PrintTestPartResultToString(
  3700. const TestPartResult& test_part_result) {
  3701. return (Message()
  3702. << internal::FormatFileLocation(test_part_result.file_name(),
  3703. test_part_result.line_number())
  3704. << " " << TestPartResultTypeToString(test_part_result.type())
  3705. << test_part_result.message()).GetString();
  3706. }
  3707. // Prints a TestPartResult.
  3708. static void PrintTestPartResult(const TestPartResult& test_part_result) {
  3709. const std::string& result =
  3710. PrintTestPartResultToString(test_part_result);
  3711. printf("%s\n", result.c_str());
  3712. fflush(stdout);
  3713. // If the test program runs in Visual Studio or a debugger, the
  3714. // following statements add the test part result message to the Output
  3715. // window such that the user can double-click on it to jump to the
  3716. // corresponding source code location; otherwise they do nothing.
  3717. #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
  3718. // We don't call OutputDebugString*() on Windows Mobile, as printing
  3719. // to stdout is done by OutputDebugString() there already - we don't
  3720. // want the same message printed twice.
  3721. ::OutputDebugStringA(result.c_str());
  3722. ::OutputDebugStringA("\n");
  3723. #endif
  3724. }
  3725. // class PrettyUnitTestResultPrinter
  3726. #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \
  3727. !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
  3728. // Returns the character attribute for the given color.
  3729. static WORD GetColorAttribute(GTestColor color) {
  3730. switch (color) {
  3731. case COLOR_RED: return FOREGROUND_RED;
  3732. case COLOR_GREEN: return FOREGROUND_GREEN;
  3733. case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
  3734. default: return 0;
  3735. }
  3736. }
  3737. static int GetBitOffset(WORD color_mask) {
  3738. if (color_mask == 0) return 0;
  3739. int bitOffset = 0;
  3740. while ((color_mask & 1) == 0) {
  3741. color_mask >>= 1;
  3742. ++bitOffset;
  3743. }
  3744. return bitOffset;
  3745. }
  3746. static WORD GetNewColor(GTestColor color, WORD old_color_attrs) {
  3747. // Let's reuse the BG
  3748. static const WORD background_mask = BACKGROUND_BLUE | BACKGROUND_GREEN |
  3749. BACKGROUND_RED | BACKGROUND_INTENSITY;
  3750. static const WORD foreground_mask = FOREGROUND_BLUE | FOREGROUND_GREEN |
  3751. FOREGROUND_RED | FOREGROUND_INTENSITY;
  3752. const WORD existing_bg = old_color_attrs & background_mask;
  3753. WORD new_color =
  3754. GetColorAttribute(color) | existing_bg | FOREGROUND_INTENSITY;
  3755. static const int bg_bitOffset = GetBitOffset(background_mask);
  3756. static const int fg_bitOffset = GetBitOffset(foreground_mask);
  3757. if (((new_color & background_mask) >> bg_bitOffset) ==
  3758. ((new_color & foreground_mask) >> fg_bitOffset)) {
  3759. new_color ^= FOREGROUND_INTENSITY; // invert intensity
  3760. }
  3761. return new_color;
  3762. }
  3763. #else
  3764. // Returns the ANSI color code for the given color. COLOR_DEFAULT is
  3765. // an invalid input.
  3766. static const char* GetAnsiColorCode(GTestColor color) {
  3767. switch (color) {
  3768. case COLOR_RED: return "1";
  3769. case COLOR_GREEN: return "2";
  3770. case COLOR_YELLOW: return "3";
  3771. default:
  3772. return nullptr;
  3773. };
  3774. }
  3775. #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
  3776. // Returns true iff Google Test should use colors in the output.
  3777. bool ShouldUseColor(bool stdout_is_tty) {
  3778. const char* const gtest_color = GTEST_FLAG(color).c_str();
  3779. if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
  3780. #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
  3781. // On Windows the TERM variable is usually not set, but the
  3782. // console there does support colors.
  3783. return stdout_is_tty;
  3784. #else
  3785. // On non-Windows platforms, we rely on the TERM variable.
  3786. const char* const term = posix::GetEnv("TERM");
  3787. const bool term_supports_color =
  3788. String::CStringEquals(term, "xterm") ||
  3789. String::CStringEquals(term, "xterm-color") ||
  3790. String::CStringEquals(term, "xterm-256color") ||
  3791. String::CStringEquals(term, "screen") ||
  3792. String::CStringEquals(term, "screen-256color") ||
  3793. String::CStringEquals(term, "tmux") ||
  3794. String::CStringEquals(term, "tmux-256color") ||
  3795. String::CStringEquals(term, "rxvt-unicode") ||
  3796. String::CStringEquals(term, "rxvt-unicode-256color") ||
  3797. String::CStringEquals(term, "linux") ||
  3798. String::CStringEquals(term, "cygwin");
  3799. return stdout_is_tty && term_supports_color;
  3800. #endif // GTEST_OS_WINDOWS
  3801. }
  3802. return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
  3803. String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
  3804. String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
  3805. String::CStringEquals(gtest_color, "1");
  3806. // We take "yes", "true", "t", and "1" as meaning "yes". If the
  3807. // value is neither one of these nor "auto", we treat it as "no" to
  3808. // be conservative.
  3809. }
  3810. // Helpers for printing colored strings to stdout. Note that on Windows, we
  3811. // cannot simply emit special characters and have the terminal change colors.
  3812. // This routine must actually emit the characters rather than return a string
  3813. // that would be colored when printed, as can be done on Linux.
  3814. void ColoredPrintf(GTestColor color, const char* fmt, ...) {
  3815. va_list args;
  3816. va_start(args, fmt);
  3817. #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_ZOS || GTEST_OS_IOS || \
  3818. GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT
  3819. const bool use_color = AlwaysFalse();
  3820. #else
  3821. static const bool in_color_mode =
  3822. ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
  3823. const bool use_color = in_color_mode && (color != COLOR_DEFAULT);
  3824. #endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_ZOS
  3825. if (!use_color) {
  3826. vprintf(fmt, args);
  3827. va_end(args);
  3828. return;
  3829. }
  3830. #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \
  3831. !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
  3832. const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
  3833. // Gets the current text color.
  3834. CONSOLE_SCREEN_BUFFER_INFO buffer_info;
  3835. GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
  3836. const WORD old_color_attrs = buffer_info.wAttributes;
  3837. const WORD new_color = GetNewColor(color, old_color_attrs);
  3838. // We need to flush the stream buffers into the console before each
  3839. // SetConsoleTextAttribute call lest it affect the text that is already
  3840. // printed but has not yet reached the console.
  3841. fflush(stdout);
  3842. SetConsoleTextAttribute(stdout_handle, new_color);
  3843. vprintf(fmt, args);
  3844. fflush(stdout);
  3845. // Restores the text color.
  3846. SetConsoleTextAttribute(stdout_handle, old_color_attrs);
  3847. #else
  3848. printf("\033[0;3%sm", GetAnsiColorCode(color));
  3849. vprintf(fmt, args);
  3850. printf("\033[m"); // Resets the terminal to default.
  3851. #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
  3852. va_end(args);
  3853. }
  3854. // Text printed in Google Test's text output and --gtest_list_tests
  3855. // output to label the type parameter and value parameter for a test.
  3856. static const char kTypeParamLabel[] = "TypeParam";
  3857. static const char kValueParamLabel[] = "GetParam()";
  3858. static void PrintFullTestCommentIfPresent(const TestInfo& test_info) {
  3859. const char* const type_param = test_info.type_param();
  3860. const char* const value_param = test_info.value_param();
  3861. if (type_param != nullptr || value_param != nullptr) {
  3862. printf(", where ");
  3863. if (type_param != nullptr) {
  3864. printf("%s = %s", kTypeParamLabel, type_param);
  3865. if (value_param != nullptr) printf(" and ");
  3866. }
  3867. if (value_param != nullptr) {
  3868. printf("%s = %s", kValueParamLabel, value_param);
  3869. }
  3870. }
  3871. }
  3872. // This class implements the TestEventListener interface.
  3873. //
  3874. // Class PrettyUnitTestResultPrinter is copyable.
  3875. class PrettyUnitTestResultPrinter : public TestEventListener {
  3876. public:
  3877. PrettyUnitTestResultPrinter() {}
  3878. static void PrintTestName(const char* test_suite, const char* test) {
  3879. printf("%s.%s", test_suite, test);
  3880. }
  3881. // The following methods override what's in the TestEventListener class.
  3882. void OnTestProgramStart(const UnitTest& /*unit_test*/) override {}
  3883. void OnTestIterationStart(const UnitTest& unit_test, int iteration) override;
  3884. void OnEnvironmentsSetUpStart(const UnitTest& unit_test) override;
  3885. void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) override {}
  3886. void OnTestCaseStart(const TestSuite& test_suite) override;
  3887. void OnTestStart(const TestInfo& test_info) override;
  3888. void OnTestPartResult(const TestPartResult& result) override;
  3889. void OnTestEnd(const TestInfo& test_info) override;
  3890. void OnTestCaseEnd(const TestSuite& test_suite) override;
  3891. void OnEnvironmentsTearDownStart(const UnitTest& unit_test) override;
  3892. void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) override {}
  3893. void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
  3894. void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {}
  3895. private:
  3896. static void PrintFailedTests(const UnitTest& unit_test);
  3897. static void PrintSkippedTests(const UnitTest& unit_test);
  3898. };
  3899. // Fired before each iteration of tests starts.
  3900. void PrettyUnitTestResultPrinter::OnTestIterationStart(
  3901. const UnitTest& unit_test, int iteration) {
  3902. if (GTEST_FLAG(repeat) != 1)
  3903. printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
  3904. const char* const filter = GTEST_FLAG(filter).c_str();
  3905. // Prints the filter if it's not *. This reminds the user that some
  3906. // tests may be skipped.
  3907. if (!String::CStringEquals(filter, kUniversalFilter)) {
  3908. ColoredPrintf(COLOR_YELLOW,
  3909. "Note: %s filter = %s\n", GTEST_NAME_, filter);
  3910. }
  3911. if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
  3912. const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
  3913. ColoredPrintf(COLOR_YELLOW,
  3914. "Note: This is test shard %d of %s.\n",
  3915. static_cast<int>(shard_index) + 1,
  3916. internal::posix::GetEnv(kTestTotalShards));
  3917. }
  3918. if (GTEST_FLAG(shuffle)) {
  3919. ColoredPrintf(COLOR_YELLOW,
  3920. "Note: Randomizing tests' orders with a seed of %d .\n",
  3921. unit_test.random_seed());
  3922. }
  3923. ColoredPrintf(COLOR_GREEN, "[==========] ");
  3924. printf("Running %s from %s.\n",
  3925. FormatTestCount(unit_test.test_to_run_count()).c_str(),
  3926. FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str());
  3927. fflush(stdout);
  3928. }
  3929. void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
  3930. const UnitTest& /*unit_test*/) {
  3931. ColoredPrintf(COLOR_GREEN, "[----------] ");
  3932. printf("Global test environment set-up.\n");
  3933. fflush(stdout);
  3934. }
  3935. void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestSuite& test_suite) {
  3936. const std::string counts =
  3937. FormatCountableNoun(test_suite.test_to_run_count(), "test", "tests");
  3938. ColoredPrintf(COLOR_GREEN, "[----------] ");
  3939. printf("%s from %s", counts.c_str(), test_suite.name());
  3940. if (test_suite.type_param() == nullptr) {
  3941. printf("\n");
  3942. } else {
  3943. printf(", where %s = %s\n", kTypeParamLabel, test_suite.type_param());
  3944. }
  3945. fflush(stdout);
  3946. }
  3947. void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
  3948. ColoredPrintf(COLOR_GREEN, "[ RUN ] ");
  3949. PrintTestName(test_info.test_suite_name(), test_info.name());
  3950. printf("\n");
  3951. fflush(stdout);
  3952. }
  3953. // Called after an assertion failure.
  3954. void PrettyUnitTestResultPrinter::OnTestPartResult(
  3955. const TestPartResult& result) {
  3956. switch (result.type()) {
  3957. // If the test part succeeded, or was skipped,
  3958. // we don't need to do anything.
  3959. case TestPartResult::kSkip:
  3960. case TestPartResult::kSuccess:
  3961. return;
  3962. default:
  3963. // Print failure message from the assertion
  3964. // (e.g. expected this and got that).
  3965. PrintTestPartResult(result);
  3966. fflush(stdout);
  3967. }
  3968. }
  3969. void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
  3970. if (test_info.result()->Passed()) {
  3971. ColoredPrintf(COLOR_GREEN, "[ OK ] ");
  3972. } else if (test_info.result()->Skipped()) {
  3973. ColoredPrintf(COLOR_GREEN, "[ SKIPPED ] ");
  3974. } else {
  3975. ColoredPrintf(COLOR_RED, "[ FAILED ] ");
  3976. }
  3977. PrintTestName(test_info.test_suite_name(), test_info.name());
  3978. if (test_info.result()->Failed())
  3979. PrintFullTestCommentIfPresent(test_info);
  3980. if (GTEST_FLAG(print_time)) {
  3981. printf(" (%s ms)\n", internal::StreamableToString(
  3982. test_info.result()->elapsed_time()).c_str());
  3983. } else {
  3984. printf("\n");
  3985. }
  3986. fflush(stdout);
  3987. }
  3988. void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestSuite& test_suite) {
  3989. if (!GTEST_FLAG(print_time)) return;
  3990. const std::string counts =
  3991. FormatCountableNoun(test_suite.test_to_run_count(), "test", "tests");
  3992. ColoredPrintf(COLOR_GREEN, "[----------] ");
  3993. printf("%s from %s (%s ms total)\n\n", counts.c_str(), test_suite.name(),
  3994. internal::StreamableToString(test_suite.elapsed_time()).c_str());
  3995. fflush(stdout);
  3996. }
  3997. void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
  3998. const UnitTest& /*unit_test*/) {
  3999. ColoredPrintf(COLOR_GREEN, "[----------] ");
  4000. printf("Global test environment tear-down\n");
  4001. fflush(stdout);
  4002. }
  4003. // Internal helper for printing the list of failed tests.
  4004. void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
  4005. const int failed_test_count = unit_test.failed_test_count();
  4006. if (failed_test_count == 0) {
  4007. return;
  4008. }
  4009. for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
  4010. const TestSuite& test_suite = *unit_test.GetTestSuite(i);
  4011. if (!test_suite.should_run() || (test_suite.failed_test_count() == 0)) {
  4012. continue;
  4013. }
  4014. for (int j = 0; j < test_suite.total_test_count(); ++j) {
  4015. const TestInfo& test_info = *test_suite.GetTestInfo(j);
  4016. if (!test_info.should_run() || !test_info.result()->Failed()) {
  4017. continue;
  4018. }
  4019. ColoredPrintf(COLOR_RED, "[ FAILED ] ");
  4020. printf("%s.%s", test_suite.name(), test_info.name());
  4021. PrintFullTestCommentIfPresent(test_info);
  4022. printf("\n");
  4023. }
  4024. }
  4025. }
  4026. // Internal helper for printing the list of skipped tests.
  4027. void PrettyUnitTestResultPrinter::PrintSkippedTests(const UnitTest& unit_test) {
  4028. const int skipped_test_count = unit_test.skipped_test_count();
  4029. if (skipped_test_count == 0) {
  4030. return;
  4031. }
  4032. for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
  4033. const TestSuite& test_suite = *unit_test.GetTestSuite(i);
  4034. if (!test_suite.should_run() || (test_suite.skipped_test_count() == 0)) {
  4035. continue;
  4036. }
  4037. for (int j = 0; j < test_suite.total_test_count(); ++j) {
  4038. const TestInfo& test_info = *test_suite.GetTestInfo(j);
  4039. if (!test_info.should_run() || !test_info.result()->Skipped()) {
  4040. continue;
  4041. }
  4042. ColoredPrintf(COLOR_GREEN, "[ SKIPPED ] ");
  4043. printf("%s.%s", test_suite.name(), test_info.name());
  4044. printf("\n");
  4045. }
  4046. }
  4047. }
  4048. void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
  4049. int /*iteration*/) {
  4050. ColoredPrintf(COLOR_GREEN, "[==========] ");
  4051. printf("%s from %s ran.",
  4052. FormatTestCount(unit_test.test_to_run_count()).c_str(),
  4053. FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str());
  4054. if (GTEST_FLAG(print_time)) {
  4055. printf(" (%s ms total)",
  4056. internal::StreamableToString(unit_test.elapsed_time()).c_str());
  4057. }
  4058. printf("\n");
  4059. ColoredPrintf(COLOR_GREEN, "[ PASSED ] ");
  4060. printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
  4061. const int skipped_test_count = unit_test.skipped_test_count();
  4062. if (skipped_test_count > 0) {
  4063. ColoredPrintf(COLOR_GREEN, "[ SKIPPED ] ");
  4064. printf("%s, listed below:\n", FormatTestCount(skipped_test_count).c_str());
  4065. PrintSkippedTests(unit_test);
  4066. }
  4067. int num_failures = unit_test.failed_test_count();
  4068. if (!unit_test.Passed()) {
  4069. const int failed_test_count = unit_test.failed_test_count();
  4070. ColoredPrintf(COLOR_RED, "[ FAILED ] ");
  4071. printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
  4072. PrintFailedTests(unit_test);
  4073. printf("\n%2d FAILED %s\n", num_failures,
  4074. num_failures == 1 ? "TEST" : "TESTS");
  4075. }
  4076. int num_disabled = unit_test.reportable_disabled_test_count();
  4077. if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
  4078. if (!num_failures) {
  4079. printf("\n"); // Add a spacer if no FAILURE banner is displayed.
  4080. }
  4081. ColoredPrintf(COLOR_YELLOW,
  4082. " YOU HAVE %d DISABLED %s\n\n",
  4083. num_disabled,
  4084. num_disabled == 1 ? "TEST" : "TESTS");
  4085. }
  4086. // Ensure that Google Test output is printed before, e.g., heapchecker output.
  4087. fflush(stdout);
  4088. }
  4089. // End PrettyUnitTestResultPrinter
  4090. // class TestEventRepeater
  4091. //
  4092. // This class forwards events to other event listeners.
  4093. class TestEventRepeater : public TestEventListener {
  4094. public:
  4095. TestEventRepeater() : forwarding_enabled_(true) {}
  4096. ~TestEventRepeater() override;
  4097. void Append(TestEventListener *listener);
  4098. TestEventListener* Release(TestEventListener* listener);
  4099. // Controls whether events will be forwarded to listeners_. Set to false
  4100. // in death test child processes.
  4101. bool forwarding_enabled() const { return forwarding_enabled_; }
  4102. void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }
  4103. void OnTestProgramStart(const UnitTest& unit_test) override;
  4104. void OnTestIterationStart(const UnitTest& unit_test, int iteration) override;
  4105. void OnEnvironmentsSetUpStart(const UnitTest& unit_test) override;
  4106. void OnEnvironmentsSetUpEnd(const UnitTest& unit_test) override;
  4107. // Legacy API is deprecated but still available
  4108. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI
  4109. void OnTestCaseStart(const TestSuite& parameter) override;
  4110. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI
  4111. void OnTestSuiteStart(const TestSuite& parameter) override;
  4112. void OnTestStart(const TestInfo& test_info) override;
  4113. void OnTestPartResult(const TestPartResult& result) override;
  4114. void OnTestEnd(const TestInfo& test_info) override;
  4115. // Legacy API is deprecated but still available
  4116. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI
  4117. void OnTestCaseEnd(const TestSuite& parameter) override;
  4118. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI
  4119. void OnTestSuiteEnd(const TestSuite& parameter) override;
  4120. void OnEnvironmentsTearDownStart(const UnitTest& unit_test) override;
  4121. void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) override;
  4122. void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
  4123. void OnTestProgramEnd(const UnitTest& unit_test) override;
  4124. private:
  4125. // Controls whether events will be forwarded to listeners_. Set to false
  4126. // in death test child processes.
  4127. bool forwarding_enabled_;
  4128. // The list of listeners that receive events.
  4129. std::vector<TestEventListener*> listeners_;
  4130. GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater);
  4131. };
  4132. TestEventRepeater::~TestEventRepeater() {
  4133. ForEach(listeners_, Delete<TestEventListener>);
  4134. }
  4135. void TestEventRepeater::Append(TestEventListener *listener) {
  4136. listeners_.push_back(listener);
  4137. }
  4138. TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {
  4139. for (size_t i = 0; i < listeners_.size(); ++i) {
  4140. if (listeners_[i] == listener) {
  4141. listeners_.erase(listeners_.begin() + i);
  4142. return listener;
  4143. }
  4144. }
  4145. return nullptr;
  4146. }
  4147. // Since most methods are very similar, use macros to reduce boilerplate.
  4148. // This defines a member that forwards the call to all listeners.
  4149. #define GTEST_REPEATER_METHOD_(Name, Type) \
  4150. void TestEventRepeater::Name(const Type& parameter) { \
  4151. if (forwarding_enabled_) { \
  4152. for (size_t i = 0; i < listeners_.size(); i++) { \
  4153. listeners_[i]->Name(parameter); \
  4154. } \
  4155. } \
  4156. }
  4157. // This defines a member that forwards the call to all listeners in reverse
  4158. // order.
  4159. #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
  4160. void TestEventRepeater::Name(const Type& parameter) { \
  4161. if (forwarding_enabled_) { \
  4162. for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \
  4163. listeners_[i]->Name(parameter); \
  4164. } \
  4165. } \
  4166. }
  4167. GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)
  4168. GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)
  4169. // Legacy API is deprecated but still available
  4170. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  4171. GTEST_REPEATER_METHOD_(OnTestCaseStart, TestSuite)
  4172. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  4173. GTEST_REPEATER_METHOD_(OnTestSuiteStart, TestSuite)
  4174. GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
  4175. GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)
  4176. GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)
  4177. GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)
  4178. GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)
  4179. GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)
  4180. // Legacy API is deprecated but still available
  4181. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  4182. GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestSuite)
  4183. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  4184. GTEST_REVERSE_REPEATER_METHOD_(OnTestSuiteEnd, TestSuite)
  4185. GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)
  4186. #undef GTEST_REPEATER_METHOD_
  4187. #undef GTEST_REVERSE_REPEATER_METHOD_
  4188. void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,
  4189. int iteration) {
  4190. if (forwarding_enabled_) {
  4191. for (size_t i = 0; i < listeners_.size(); i++) {
  4192. listeners_[i]->OnTestIterationStart(unit_test, iteration);
  4193. }
  4194. }
  4195. }
  4196. void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,
  4197. int iteration) {
  4198. if (forwarding_enabled_) {
  4199. for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) {
  4200. listeners_[i]->OnTestIterationEnd(unit_test, iteration);
  4201. }
  4202. }
  4203. }
  4204. // End TestEventRepeater
  4205. // This class generates an XML output file.
  4206. class XmlUnitTestResultPrinter : public EmptyTestEventListener {
  4207. public:
  4208. explicit XmlUnitTestResultPrinter(const char* output_file);
  4209. void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
  4210. void ListTestsMatchingFilter(const std::vector<TestSuite*>& test_suites);
  4211. // Prints an XML summary of all unit tests.
  4212. static void PrintXmlTestsList(std::ostream* stream,
  4213. const std::vector<TestSuite*>& test_suites);
  4214. private:
  4215. // Is c a whitespace character that is normalized to a space character
  4216. // when it appears in an XML attribute value?
  4217. static bool IsNormalizableWhitespace(char c) {
  4218. return c == 0x9 || c == 0xA || c == 0xD;
  4219. }
  4220. // May c appear in a well-formed XML document?
  4221. static bool IsValidXmlCharacter(char c) {
  4222. return IsNormalizableWhitespace(c) || c >= 0x20;
  4223. }
  4224. // Returns an XML-escaped copy of the input string str. If
  4225. // is_attribute is true, the text is meant to appear as an attribute
  4226. // value, and normalizable whitespace is preserved by replacing it
  4227. // with character references.
  4228. static std::string EscapeXml(const std::string& str, bool is_attribute);
  4229. // Returns the given string with all characters invalid in XML removed.
  4230. static std::string RemoveInvalidXmlCharacters(const std::string& str);
  4231. // Convenience wrapper around EscapeXml when str is an attribute value.
  4232. static std::string EscapeXmlAttribute(const std::string& str) {
  4233. return EscapeXml(str, true);
  4234. }
  4235. // Convenience wrapper around EscapeXml when str is not an attribute value.
  4236. static std::string EscapeXmlText(const char* str) {
  4237. return EscapeXml(str, false);
  4238. }
  4239. // Verifies that the given attribute belongs to the given element and
  4240. // streams the attribute as XML.
  4241. static void OutputXmlAttribute(std::ostream* stream,
  4242. const std::string& element_name,
  4243. const std::string& name,
  4244. const std::string& value);
  4245. // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
  4246. static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
  4247. // Streams an XML representation of a TestInfo object.
  4248. static void OutputXmlTestInfo(::std::ostream* stream,
  4249. const char* test_suite_name,
  4250. const TestInfo& test_info);
  4251. // Prints an XML representation of a TestSuite object
  4252. static void PrintXmlTestSuite(::std::ostream* stream,
  4253. const TestSuite& test_suite);
  4254. // Prints an XML summary of unit_test to output stream out.
  4255. static void PrintXmlUnitTest(::std::ostream* stream,
  4256. const UnitTest& unit_test);
  4257. // Produces a string representing the test properties in a result as space
  4258. // delimited XML attributes based on the property key="value" pairs.
  4259. // When the std::string is not empty, it includes a space at the beginning,
  4260. // to delimit this attribute from prior attributes.
  4261. static std::string TestPropertiesAsXmlAttributes(const TestResult& result);
  4262. // Streams an XML representation of the test properties of a TestResult
  4263. // object.
  4264. static void OutputXmlTestProperties(std::ostream* stream,
  4265. const TestResult& result);
  4266. // The output file.
  4267. const std::string output_file_;
  4268. GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);
  4269. };
  4270. // Creates a new XmlUnitTestResultPrinter.
  4271. XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
  4272. : output_file_(output_file) {
  4273. if (output_file_.empty()) {
  4274. GTEST_LOG_(FATAL) << "XML output file may not be null";
  4275. }
  4276. }
  4277. // Called after the unit test ends.
  4278. void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
  4279. int /*iteration*/) {
  4280. FILE* xmlout = OpenFileForWriting(output_file_);
  4281. std::stringstream stream;
  4282. PrintXmlUnitTest(&stream, unit_test);
  4283. fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
  4284. fclose(xmlout);
  4285. }
  4286. void XmlUnitTestResultPrinter::ListTestsMatchingFilter(
  4287. const std::vector<TestSuite*>& test_suites) {
  4288. FILE* xmlout = OpenFileForWriting(output_file_);
  4289. std::stringstream stream;
  4290. PrintXmlTestsList(&stream, test_suites);
  4291. fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
  4292. fclose(xmlout);
  4293. }
  4294. // Returns an XML-escaped copy of the input string str. If is_attribute
  4295. // is true, the text is meant to appear as an attribute value, and
  4296. // normalizable whitespace is preserved by replacing it with character
  4297. // references.
  4298. //
  4299. // Invalid XML characters in str, if any, are stripped from the output.
  4300. // It is expected that most, if not all, of the text processed by this
  4301. // module will consist of ordinary English text.
  4302. // If this module is ever modified to produce version 1.1 XML output,
  4303. // most invalid characters can be retained using character references.
  4304. std::string XmlUnitTestResultPrinter::EscapeXml(
  4305. const std::string& str, bool is_attribute) {
  4306. Message m;
  4307. for (size_t i = 0; i < str.size(); ++i) {
  4308. const char ch = str[i];
  4309. switch (ch) {
  4310. case '<':
  4311. m << "&lt;";
  4312. break;
  4313. case '>':
  4314. m << "&gt;";
  4315. break;
  4316. case '&':
  4317. m << "&amp;";
  4318. break;
  4319. case '\'':
  4320. if (is_attribute)
  4321. m << "&apos;";
  4322. else
  4323. m << '\'';
  4324. break;
  4325. case '"':
  4326. if (is_attribute)
  4327. m << "&quot;";
  4328. else
  4329. m << '"';
  4330. break;
  4331. default:
  4332. if (IsValidXmlCharacter(ch)) {
  4333. if (is_attribute && IsNormalizableWhitespace(ch))
  4334. m << "&#x" << String::FormatByte(static_cast<unsigned char>(ch))
  4335. << ";";
  4336. else
  4337. m << ch;
  4338. }
  4339. break;
  4340. }
  4341. }
  4342. return m.GetString();
  4343. }
  4344. // Returns the given string with all characters invalid in XML removed.
  4345. // Currently invalid characters are dropped from the string. An
  4346. // alternative is to replace them with certain characters such as . or ?.
  4347. std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(
  4348. const std::string& str) {
  4349. std::string output;
  4350. output.reserve(str.size());
  4351. for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
  4352. if (IsValidXmlCharacter(*it))
  4353. output.push_back(*it);
  4354. return output;
  4355. }
  4356. // The following routines generate an XML representation of a UnitTest
  4357. // object.
  4358. // GOOGLETEST_CM0009 DO NOT DELETE
  4359. //
  4360. // This is how Google Test concepts map to the DTD:
  4361. //
  4362. // <testsuites name="AllTests"> <-- corresponds to a UnitTest object
  4363. // <testsuite name="testcase-name"> <-- corresponds to a TestSuite object
  4364. // <testcase name="test-name"> <-- corresponds to a TestInfo object
  4365. // <failure message="...">...</failure>
  4366. // <failure message="...">...</failure>
  4367. // <failure message="...">...</failure>
  4368. // <-- individual assertion failures
  4369. // </testcase>
  4370. // </testsuite>
  4371. // </testsuites>
  4372. // Formats the given time in milliseconds as seconds.
  4373. std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {
  4374. ::std::stringstream ss;
  4375. ss << (static_cast<double>(ms) * 1e-3);
  4376. return ss.str();
  4377. }
  4378. static bool PortableLocaltime(time_t seconds, struct tm* out) {
  4379. #if defined(_MSC_VER)
  4380. return localtime_s(out, &seconds) == 0;
  4381. #elif defined(__MINGW32__) || defined(__MINGW64__)
  4382. // MINGW <time.h> provides neither localtime_r nor localtime_s, but uses
  4383. // Windows' localtime(), which has a thread-local tm buffer.
  4384. struct tm* tm_ptr = localtime(&seconds); // NOLINT
  4385. if (tm_ptr == nullptr) return false;
  4386. *out = *tm_ptr;
  4387. return true;
  4388. #else
  4389. return localtime_r(&seconds, out) != nullptr;
  4390. #endif
  4391. }
  4392. // Converts the given epoch time in milliseconds to a date string in the ISO
  4393. // 8601 format, without the timezone information.
  4394. std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) {
  4395. struct tm time_struct;
  4396. if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))
  4397. return "";
  4398. // YYYY-MM-DDThh:mm:ss
  4399. return StreamableToString(time_struct.tm_year + 1900) + "-" +
  4400. String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +
  4401. String::FormatIntWidth2(time_struct.tm_mday) + "T" +
  4402. String::FormatIntWidth2(time_struct.tm_hour) + ":" +
  4403. String::FormatIntWidth2(time_struct.tm_min) + ":" +
  4404. String::FormatIntWidth2(time_struct.tm_sec);
  4405. }
  4406. // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
  4407. void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
  4408. const char* data) {
  4409. const char* segment = data;
  4410. *stream << "<![CDATA[";
  4411. for (;;) {
  4412. const char* const next_segment = strstr(segment, "]]>");
  4413. if (next_segment != nullptr) {
  4414. stream->write(
  4415. segment, static_cast<std::streamsize>(next_segment - segment));
  4416. *stream << "]]>]]&gt;<![CDATA[";
  4417. segment = next_segment + strlen("]]>");
  4418. } else {
  4419. *stream << segment;
  4420. break;
  4421. }
  4422. }
  4423. *stream << "]]>";
  4424. }
  4425. void XmlUnitTestResultPrinter::OutputXmlAttribute(
  4426. std::ostream* stream,
  4427. const std::string& element_name,
  4428. const std::string& name,
  4429. const std::string& value) {
  4430. const std::vector<std::string>& allowed_names =
  4431. GetReservedAttributesForElement(element_name);
  4432. GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
  4433. allowed_names.end())
  4434. << "Attribute " << name << " is not allowed for element <" << element_name
  4435. << ">.";
  4436. *stream << " " << name << "=\"" << EscapeXmlAttribute(value) << "\"";
  4437. }
  4438. // Prints an XML representation of a TestInfo object.
  4439. void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
  4440. const char* test_suite_name,
  4441. const TestInfo& test_info) {
  4442. const TestResult& result = *test_info.result();
  4443. const std::string kTestsuite = "testcase";
  4444. if (test_info.is_in_another_shard()) {
  4445. return;
  4446. }
  4447. *stream << " <testcase";
  4448. OutputXmlAttribute(stream, kTestsuite, "name", test_info.name());
  4449. if (test_info.value_param() != nullptr) {
  4450. OutputXmlAttribute(stream, kTestsuite, "value_param",
  4451. test_info.value_param());
  4452. }
  4453. if (test_info.type_param() != nullptr) {
  4454. OutputXmlAttribute(stream, kTestsuite, "type_param",
  4455. test_info.type_param());
  4456. }
  4457. if (GTEST_FLAG(list_tests)) {
  4458. OutputXmlAttribute(stream, kTestsuite, "file", test_info.file());
  4459. OutputXmlAttribute(stream, kTestsuite, "line",
  4460. StreamableToString(test_info.line()));
  4461. *stream << " />\n";
  4462. return;
  4463. }
  4464. OutputXmlAttribute(
  4465. stream, kTestsuite, "status",
  4466. result.Skipped() ? "skipped" : test_info.should_run() ? "run" : "notrun");
  4467. OutputXmlAttribute(stream, kTestsuite, "time",
  4468. FormatTimeInMillisAsSeconds(result.elapsed_time()));
  4469. OutputXmlAttribute(stream, kTestsuite, "classname", test_suite_name);
  4470. int failures = 0;
  4471. for (int i = 0; i < result.total_part_count(); ++i) {
  4472. const TestPartResult& part = result.GetTestPartResult(i);
  4473. if (part.failed()) {
  4474. if (++failures == 1) {
  4475. *stream << ">\n";
  4476. }
  4477. const std::string location =
  4478. internal::FormatCompilerIndependentFileLocation(part.file_name(),
  4479. part.line_number());
  4480. const std::string summary = location + "\n" + part.summary();
  4481. *stream << " <failure message=\""
  4482. << EscapeXmlAttribute(summary.c_str())
  4483. << "\" type=\"\">";
  4484. const std::string detail = location + "\n" + part.message();
  4485. OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
  4486. *stream << "</failure>\n";
  4487. }
  4488. }
  4489. if (failures == 0 && result.test_property_count() == 0) {
  4490. *stream << " />\n";
  4491. } else {
  4492. if (failures == 0) {
  4493. *stream << ">\n";
  4494. }
  4495. OutputXmlTestProperties(stream, result);
  4496. *stream << " </testcase>\n";
  4497. }
  4498. }
  4499. // Prints an XML representation of a TestSuite object
  4500. void XmlUnitTestResultPrinter::PrintXmlTestSuite(std::ostream* stream,
  4501. const TestSuite& test_suite) {
  4502. const std::string kTestsuite = "testsuite";
  4503. *stream << " <" << kTestsuite;
  4504. OutputXmlAttribute(stream, kTestsuite, "name", test_suite.name());
  4505. OutputXmlAttribute(stream, kTestsuite, "tests",
  4506. StreamableToString(test_suite.reportable_test_count()));
  4507. if (!GTEST_FLAG(list_tests)) {
  4508. OutputXmlAttribute(stream, kTestsuite, "failures",
  4509. StreamableToString(test_suite.failed_test_count()));
  4510. OutputXmlAttribute(
  4511. stream, kTestsuite, "disabled",
  4512. StreamableToString(test_suite.reportable_disabled_test_count()));
  4513. OutputXmlAttribute(stream, kTestsuite, "errors", "0");
  4514. OutputXmlAttribute(stream, kTestsuite, "time",
  4515. FormatTimeInMillisAsSeconds(test_suite.elapsed_time()));
  4516. *stream << TestPropertiesAsXmlAttributes(test_suite.ad_hoc_test_result());
  4517. }
  4518. *stream << ">\n";
  4519. for (int i = 0; i < test_suite.total_test_count(); ++i) {
  4520. if (test_suite.GetTestInfo(i)->is_reportable())
  4521. OutputXmlTestInfo(stream, test_suite.name(), *test_suite.GetTestInfo(i));
  4522. }
  4523. *stream << " </" << kTestsuite << ">\n";
  4524. }
  4525. // Prints an XML summary of unit_test to output stream out.
  4526. void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream,
  4527. const UnitTest& unit_test) {
  4528. const std::string kTestsuites = "testsuites";
  4529. *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
  4530. *stream << "<" << kTestsuites;
  4531. OutputXmlAttribute(stream, kTestsuites, "tests",
  4532. StreamableToString(unit_test.reportable_test_count()));
  4533. OutputXmlAttribute(stream, kTestsuites, "failures",
  4534. StreamableToString(unit_test.failed_test_count()));
  4535. OutputXmlAttribute(
  4536. stream, kTestsuites, "disabled",
  4537. StreamableToString(unit_test.reportable_disabled_test_count()));
  4538. OutputXmlAttribute(stream, kTestsuites, "errors", "0");
  4539. OutputXmlAttribute(
  4540. stream, kTestsuites, "timestamp",
  4541. FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp()));
  4542. OutputXmlAttribute(stream, kTestsuites, "time",
  4543. FormatTimeInMillisAsSeconds(unit_test.elapsed_time()));
  4544. if (GTEST_FLAG(shuffle)) {
  4545. OutputXmlAttribute(stream, kTestsuites, "random_seed",
  4546. StreamableToString(unit_test.random_seed()));
  4547. }
  4548. *stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result());
  4549. OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
  4550. *stream << ">\n";
  4551. for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
  4552. if (unit_test.GetTestSuite(i)->reportable_test_count() > 0)
  4553. PrintXmlTestSuite(stream, *unit_test.GetTestSuite(i));
  4554. }
  4555. *stream << "</" << kTestsuites << ">\n";
  4556. }
  4557. void XmlUnitTestResultPrinter::PrintXmlTestsList(
  4558. std::ostream* stream, const std::vector<TestSuite*>& test_suites) {
  4559. const std::string kTestsuites = "testsuites";
  4560. *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
  4561. *stream << "<" << kTestsuites;
  4562. int total_tests = 0;
  4563. for (auto test_suite : test_suites) {
  4564. total_tests += test_suite->total_test_count();
  4565. }
  4566. OutputXmlAttribute(stream, kTestsuites, "tests",
  4567. StreamableToString(total_tests));
  4568. OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
  4569. *stream << ">\n";
  4570. for (auto test_suite : test_suites) {
  4571. PrintXmlTestSuite(stream, *test_suite);
  4572. }
  4573. *stream << "</" << kTestsuites << ">\n";
  4574. }
  4575. // Produces a string representing the test properties in a result as space
  4576. // delimited XML attributes based on the property key="value" pairs.
  4577. std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
  4578. const TestResult& result) {
  4579. Message attributes;
  4580. for (int i = 0; i < result.test_property_count(); ++i) {
  4581. const TestProperty& property = result.GetTestProperty(i);
  4582. attributes << " " << property.key() << "="
  4583. << "\"" << EscapeXmlAttribute(property.value()) << "\"";
  4584. }
  4585. return attributes.GetString();
  4586. }
  4587. void XmlUnitTestResultPrinter::OutputXmlTestProperties(
  4588. std::ostream* stream, const TestResult& result) {
  4589. const std::string kProperties = "properties";
  4590. const std::string kProperty = "property";
  4591. if (result.test_property_count() <= 0) {
  4592. return;
  4593. }
  4594. *stream << "<" << kProperties << ">\n";
  4595. for (int i = 0; i < result.test_property_count(); ++i) {
  4596. const TestProperty& property = result.GetTestProperty(i);
  4597. *stream << "<" << kProperty;
  4598. *stream << " name=\"" << EscapeXmlAttribute(property.key()) << "\"";
  4599. *stream << " value=\"" << EscapeXmlAttribute(property.value()) << "\"";
  4600. *stream << "/>\n";
  4601. }
  4602. *stream << "</" << kProperties << ">\n";
  4603. }
  4604. // End XmlUnitTestResultPrinter
  4605. // This class generates an JSON output file.
  4606. class JsonUnitTestResultPrinter : public EmptyTestEventListener {
  4607. public:
  4608. explicit JsonUnitTestResultPrinter(const char* output_file);
  4609. void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
  4610. // Prints an JSON summary of all unit tests.
  4611. static void PrintJsonTestList(::std::ostream* stream,
  4612. const std::vector<TestSuite*>& test_suites);
  4613. private:
  4614. // Returns an JSON-escaped copy of the input string str.
  4615. static std::string EscapeJson(const std::string& str);
  4616. //// Verifies that the given attribute belongs to the given element and
  4617. //// streams the attribute as JSON.
  4618. static void OutputJsonKey(std::ostream* stream,
  4619. const std::string& element_name,
  4620. const std::string& name,
  4621. const std::string& value,
  4622. const std::string& indent,
  4623. bool comma = true);
  4624. static void OutputJsonKey(std::ostream* stream,
  4625. const std::string& element_name,
  4626. const std::string& name,
  4627. int value,
  4628. const std::string& indent,
  4629. bool comma = true);
  4630. // Streams a JSON representation of a TestInfo object.
  4631. static void OutputJsonTestInfo(::std::ostream* stream,
  4632. const char* test_suite_name,
  4633. const TestInfo& test_info);
  4634. // Prints a JSON representation of a TestSuite object
  4635. static void PrintJsonTestSuite(::std::ostream* stream,
  4636. const TestSuite& test_suite);
  4637. // Prints a JSON summary of unit_test to output stream out.
  4638. static void PrintJsonUnitTest(::std::ostream* stream,
  4639. const UnitTest& unit_test);
  4640. // Produces a string representing the test properties in a result as
  4641. // a JSON dictionary.
  4642. static std::string TestPropertiesAsJson(const TestResult& result,
  4643. const std::string& indent);
  4644. // The output file.
  4645. const std::string output_file_;
  4646. GTEST_DISALLOW_COPY_AND_ASSIGN_(JsonUnitTestResultPrinter);
  4647. };
  4648. // Creates a new JsonUnitTestResultPrinter.
  4649. JsonUnitTestResultPrinter::JsonUnitTestResultPrinter(const char* output_file)
  4650. : output_file_(output_file) {
  4651. if (output_file_.empty()) {
  4652. GTEST_LOG_(FATAL) << "JSON output file may not be null";
  4653. }
  4654. }
  4655. void JsonUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
  4656. int /*iteration*/) {
  4657. FILE* jsonout = OpenFileForWriting(output_file_);
  4658. std::stringstream stream;
  4659. PrintJsonUnitTest(&stream, unit_test);
  4660. fprintf(jsonout, "%s", StringStreamToString(&stream).c_str());
  4661. fclose(jsonout);
  4662. }
  4663. // Returns an JSON-escaped copy of the input string str.
  4664. std::string JsonUnitTestResultPrinter::EscapeJson(const std::string& str) {
  4665. Message m;
  4666. for (size_t i = 0; i < str.size(); ++i) {
  4667. const char ch = str[i];
  4668. switch (ch) {
  4669. case '\\':
  4670. case '"':
  4671. case '/':
  4672. m << '\\' << ch;
  4673. break;
  4674. case '\b':
  4675. m << "\\b";
  4676. break;
  4677. case '\t':
  4678. m << "\\t";
  4679. break;
  4680. case '\n':
  4681. m << "\\n";
  4682. break;
  4683. case '\f':
  4684. m << "\\f";
  4685. break;
  4686. case '\r':
  4687. m << "\\r";
  4688. break;
  4689. default:
  4690. if (ch < ' ') {
  4691. m << "\\u00" << String::FormatByte(static_cast<unsigned char>(ch));
  4692. } else {
  4693. m << ch;
  4694. }
  4695. break;
  4696. }
  4697. }
  4698. return m.GetString();
  4699. }
  4700. // The following routines generate an JSON representation of a UnitTest
  4701. // object.
  4702. // Formats the given time in milliseconds as seconds.
  4703. static std::string FormatTimeInMillisAsDuration(TimeInMillis ms) {
  4704. ::std::stringstream ss;
  4705. ss << (static_cast<double>(ms) * 1e-3) << "s";
  4706. return ss.str();
  4707. }
  4708. // Converts the given epoch time in milliseconds to a date string in the
  4709. // RFC3339 format, without the timezone information.
  4710. static std::string FormatEpochTimeInMillisAsRFC3339(TimeInMillis ms) {
  4711. struct tm time_struct;
  4712. if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))
  4713. return "";
  4714. // YYYY-MM-DDThh:mm:ss
  4715. return StreamableToString(time_struct.tm_year + 1900) + "-" +
  4716. String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +
  4717. String::FormatIntWidth2(time_struct.tm_mday) + "T" +
  4718. String::FormatIntWidth2(time_struct.tm_hour) + ":" +
  4719. String::FormatIntWidth2(time_struct.tm_min) + ":" +
  4720. String::FormatIntWidth2(time_struct.tm_sec) + "Z";
  4721. }
  4722. static inline std::string Indent(int width) {
  4723. return std::string(width, ' ');
  4724. }
  4725. void JsonUnitTestResultPrinter::OutputJsonKey(
  4726. std::ostream* stream,
  4727. const std::string& element_name,
  4728. const std::string& name,
  4729. const std::string& value,
  4730. const std::string& indent,
  4731. bool comma) {
  4732. const std::vector<std::string>& allowed_names =
  4733. GetReservedAttributesForElement(element_name);
  4734. GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
  4735. allowed_names.end())
  4736. << "Key \"" << name << "\" is not allowed for value \"" << element_name
  4737. << "\".";
  4738. *stream << indent << "\"" << name << "\": \"" << EscapeJson(value) << "\"";
  4739. if (comma)
  4740. *stream << ",\n";
  4741. }
  4742. void JsonUnitTestResultPrinter::OutputJsonKey(
  4743. std::ostream* stream,
  4744. const std::string& element_name,
  4745. const std::string& name,
  4746. int value,
  4747. const std::string& indent,
  4748. bool comma) {
  4749. const std::vector<std::string>& allowed_names =
  4750. GetReservedAttributesForElement(element_name);
  4751. GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
  4752. allowed_names.end())
  4753. << "Key \"" << name << "\" is not allowed for value \"" << element_name
  4754. << "\".";
  4755. *stream << indent << "\"" << name << "\": " << StreamableToString(value);
  4756. if (comma)
  4757. *stream << ",\n";
  4758. }
  4759. // Prints a JSON representation of a TestInfo object.
  4760. void JsonUnitTestResultPrinter::OutputJsonTestInfo(::std::ostream* stream,
  4761. const char* test_suite_name,
  4762. const TestInfo& test_info) {
  4763. const TestResult& result = *test_info.result();
  4764. const std::string kTestsuite = "testcase";
  4765. const std::string kIndent = Indent(10);
  4766. *stream << Indent(8) << "{\n";
  4767. OutputJsonKey(stream, kTestsuite, "name", test_info.name(), kIndent);
  4768. if (test_info.value_param() != nullptr) {
  4769. OutputJsonKey(stream, kTestsuite, "value_param", test_info.value_param(),
  4770. kIndent);
  4771. }
  4772. if (test_info.type_param() != nullptr) {
  4773. OutputJsonKey(stream, kTestsuite, "type_param", test_info.type_param(),
  4774. kIndent);
  4775. }
  4776. if (GTEST_FLAG(list_tests)) {
  4777. OutputJsonKey(stream, kTestsuite, "file", test_info.file(), kIndent);
  4778. OutputJsonKey(stream, kTestsuite, "line", test_info.line(), kIndent, false);
  4779. *stream << "\n" << Indent(8) << "}";
  4780. return;
  4781. }
  4782. OutputJsonKey(
  4783. stream, kTestsuite, "status",
  4784. result.Skipped() ? "SKIPPED" : test_info.should_run() ? "RUN" : "NOTRUN",
  4785. kIndent);
  4786. OutputJsonKey(stream, kTestsuite, "time",
  4787. FormatTimeInMillisAsDuration(result.elapsed_time()), kIndent);
  4788. OutputJsonKey(stream, kTestsuite, "classname", test_suite_name, kIndent,
  4789. false);
  4790. *stream << TestPropertiesAsJson(result, kIndent);
  4791. int failures = 0;
  4792. for (int i = 0; i < result.total_part_count(); ++i) {
  4793. const TestPartResult& part = result.GetTestPartResult(i);
  4794. if (part.failed()) {
  4795. *stream << ",\n";
  4796. if (++failures == 1) {
  4797. *stream << kIndent << "\"" << "failures" << "\": [\n";
  4798. }
  4799. const std::string location =
  4800. internal::FormatCompilerIndependentFileLocation(part.file_name(),
  4801. part.line_number());
  4802. const std::string message = EscapeJson(location + "\n" + part.message());
  4803. *stream << kIndent << " {\n"
  4804. << kIndent << " \"failure\": \"" << message << "\",\n"
  4805. << kIndent << " \"type\": \"\"\n"
  4806. << kIndent << " }";
  4807. }
  4808. }
  4809. if (failures > 0)
  4810. *stream << "\n" << kIndent << "]";
  4811. *stream << "\n" << Indent(8) << "}";
  4812. }
  4813. // Prints an JSON representation of a TestSuite object
  4814. void JsonUnitTestResultPrinter::PrintJsonTestSuite(
  4815. std::ostream* stream, const TestSuite& test_suite) {
  4816. const std::string kTestsuite = "testsuite";
  4817. const std::string kIndent = Indent(6);
  4818. *stream << Indent(4) << "{\n";
  4819. OutputJsonKey(stream, kTestsuite, "name", test_suite.name(), kIndent);
  4820. OutputJsonKey(stream, kTestsuite, "tests", test_suite.reportable_test_count(),
  4821. kIndent);
  4822. if (!GTEST_FLAG(list_tests)) {
  4823. OutputJsonKey(stream, kTestsuite, "failures",
  4824. test_suite.failed_test_count(), kIndent);
  4825. OutputJsonKey(stream, kTestsuite, "disabled",
  4826. test_suite.reportable_disabled_test_count(), kIndent);
  4827. OutputJsonKey(stream, kTestsuite, "errors", 0, kIndent);
  4828. OutputJsonKey(stream, kTestsuite, "time",
  4829. FormatTimeInMillisAsDuration(test_suite.elapsed_time()),
  4830. kIndent, false);
  4831. *stream << TestPropertiesAsJson(test_suite.ad_hoc_test_result(), kIndent)
  4832. << ",\n";
  4833. }
  4834. *stream << kIndent << "\"" << kTestsuite << "\": [\n";
  4835. bool comma = false;
  4836. for (int i = 0; i < test_suite.total_test_count(); ++i) {
  4837. if (test_suite.GetTestInfo(i)->is_reportable()) {
  4838. if (comma) {
  4839. *stream << ",\n";
  4840. } else {
  4841. comma = true;
  4842. }
  4843. OutputJsonTestInfo(stream, test_suite.name(), *test_suite.GetTestInfo(i));
  4844. }
  4845. }
  4846. *stream << "\n" << kIndent << "]\n" << Indent(4) << "}";
  4847. }
  4848. // Prints a JSON summary of unit_test to output stream out.
  4849. void JsonUnitTestResultPrinter::PrintJsonUnitTest(std::ostream* stream,
  4850. const UnitTest& unit_test) {
  4851. const std::string kTestsuites = "testsuites";
  4852. const std::string kIndent = Indent(2);
  4853. *stream << "{\n";
  4854. OutputJsonKey(stream, kTestsuites, "tests", unit_test.reportable_test_count(),
  4855. kIndent);
  4856. OutputJsonKey(stream, kTestsuites, "failures", unit_test.failed_test_count(),
  4857. kIndent);
  4858. OutputJsonKey(stream, kTestsuites, "disabled",
  4859. unit_test.reportable_disabled_test_count(), kIndent);
  4860. OutputJsonKey(stream, kTestsuites, "errors", 0, kIndent);
  4861. if (GTEST_FLAG(shuffle)) {
  4862. OutputJsonKey(stream, kTestsuites, "random_seed", unit_test.random_seed(),
  4863. kIndent);
  4864. }
  4865. OutputJsonKey(stream, kTestsuites, "timestamp",
  4866. FormatEpochTimeInMillisAsRFC3339(unit_test.start_timestamp()),
  4867. kIndent);
  4868. OutputJsonKey(stream, kTestsuites, "time",
  4869. FormatTimeInMillisAsDuration(unit_test.elapsed_time()), kIndent,
  4870. false);
  4871. *stream << TestPropertiesAsJson(unit_test.ad_hoc_test_result(), kIndent)
  4872. << ",\n";
  4873. OutputJsonKey(stream, kTestsuites, "name", "AllTests", kIndent);
  4874. *stream << kIndent << "\"" << kTestsuites << "\": [\n";
  4875. bool comma = false;
  4876. for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
  4877. if (unit_test.GetTestSuite(i)->reportable_test_count() > 0) {
  4878. if (comma) {
  4879. *stream << ",\n";
  4880. } else {
  4881. comma = true;
  4882. }
  4883. PrintJsonTestSuite(stream, *unit_test.GetTestSuite(i));
  4884. }
  4885. }
  4886. *stream << "\n" << kIndent << "]\n" << "}\n";
  4887. }
  4888. void JsonUnitTestResultPrinter::PrintJsonTestList(
  4889. std::ostream* stream, const std::vector<TestSuite*>& test_suites) {
  4890. const std::string kTestsuites = "testsuites";
  4891. const std::string kIndent = Indent(2);
  4892. *stream << "{\n";
  4893. int total_tests = 0;
  4894. for (auto test_suite : test_suites) {
  4895. total_tests += test_suite->total_test_count();
  4896. }
  4897. OutputJsonKey(stream, kTestsuites, "tests", total_tests, kIndent);
  4898. OutputJsonKey(stream, kTestsuites, "name", "AllTests", kIndent);
  4899. *stream << kIndent << "\"" << kTestsuites << "\": [\n";
  4900. for (size_t i = 0; i < test_suites.size(); ++i) {
  4901. if (i != 0) {
  4902. *stream << ",\n";
  4903. }
  4904. PrintJsonTestSuite(stream, *test_suites[i]);
  4905. }
  4906. *stream << "\n"
  4907. << kIndent << "]\n"
  4908. << "}\n";
  4909. }
  4910. // Produces a string representing the test properties in a result as
  4911. // a JSON dictionary.
  4912. std::string JsonUnitTestResultPrinter::TestPropertiesAsJson(
  4913. const TestResult& result, const std::string& indent) {
  4914. Message attributes;
  4915. for (int i = 0; i < result.test_property_count(); ++i) {
  4916. const TestProperty& property = result.GetTestProperty(i);
  4917. attributes << ",\n" << indent << "\"" << property.key() << "\": "
  4918. << "\"" << EscapeJson(property.value()) << "\"";
  4919. }
  4920. return attributes.GetString();
  4921. }
  4922. // End JsonUnitTestResultPrinter
  4923. #if GTEST_CAN_STREAM_RESULTS_
  4924. // Checks if str contains '=', '&', '%' or '\n' characters. If yes,
  4925. // replaces them by "%xx" where xx is their hexadecimal value. For
  4926. // example, replaces "=" with "%3D". This algorithm is O(strlen(str))
  4927. // in both time and space -- important as the input str may contain an
  4928. // arbitrarily long test failure message and stack trace.
  4929. std::string StreamingListener::UrlEncode(const char* str) {
  4930. std::string result;
  4931. result.reserve(strlen(str) + 1);
  4932. for (char ch = *str; ch != '\0'; ch = *++str) {
  4933. switch (ch) {
  4934. case '%':
  4935. case '=':
  4936. case '&':
  4937. case '\n':
  4938. result.append("%" + String::FormatByte(static_cast<unsigned char>(ch)));
  4939. break;
  4940. default:
  4941. result.push_back(ch);
  4942. break;
  4943. }
  4944. }
  4945. return result;
  4946. }
  4947. void StreamingListener::SocketWriter::MakeConnection() {
  4948. GTEST_CHECK_(sockfd_ == -1)
  4949. << "MakeConnection() can't be called when there is already a connection.";
  4950. addrinfo hints;
  4951. memset(&hints, 0, sizeof(hints));
  4952. hints.ai_family = AF_UNSPEC; // To allow both IPv4 and IPv6 addresses.
  4953. hints.ai_socktype = SOCK_STREAM;
  4954. addrinfo* servinfo = nullptr;
  4955. // Use the getaddrinfo() to get a linked list of IP addresses for
  4956. // the given host name.
  4957. const int error_num = getaddrinfo(
  4958. host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
  4959. if (error_num != 0) {
  4960. GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: "
  4961. << gai_strerror(error_num);
  4962. }
  4963. // Loop through all the results and connect to the first we can.
  4964. for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != nullptr;
  4965. cur_addr = cur_addr->ai_next) {
  4966. sockfd_ = socket(
  4967. cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol);
  4968. if (sockfd_ != -1) {
  4969. // Connect the client socket to the server socket.
  4970. if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
  4971. close(sockfd_);
  4972. sockfd_ = -1;
  4973. }
  4974. }
  4975. }
  4976. freeaddrinfo(servinfo); // all done with this structure
  4977. if (sockfd_ == -1) {
  4978. GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to "
  4979. << host_name_ << ":" << port_num_;
  4980. }
  4981. }
  4982. // End of class Streaming Listener
  4983. #endif // GTEST_CAN_STREAM_RESULTS__
  4984. // class OsStackTraceGetter
  4985. const char* const OsStackTraceGetterInterface::kElidedFramesMarker =
  4986. "... " GTEST_NAME_ " internal frames ...";
  4987. std::string OsStackTraceGetter::CurrentStackTrace(int max_depth, int skip_count)
  4988. GTEST_LOCK_EXCLUDED_(mutex_) {
  4989. #if GTEST_HAS_ABSL
  4990. std::string result;
  4991. if (max_depth <= 0) {
  4992. return result;
  4993. }
  4994. max_depth = std::min(max_depth, kMaxStackTraceDepth);
  4995. std::vector<void*> raw_stack(max_depth);
  4996. // Skips the frames requested by the caller, plus this function.
  4997. const int raw_stack_size =
  4998. absl::GetStackTrace(&raw_stack[0], max_depth, skip_count + 1);
  4999. void* caller_frame = nullptr;
  5000. {
  5001. MutexLock lock(&mutex_);
  5002. caller_frame = caller_frame_;
  5003. }
  5004. for (int i = 0; i < raw_stack_size; ++i) {
  5005. if (raw_stack[i] == caller_frame &&
  5006. !GTEST_FLAG(show_internal_stack_frames)) {
  5007. // Add a marker to the trace and stop adding frames.
  5008. absl::StrAppend(&result, kElidedFramesMarker, "\n");
  5009. break;
  5010. }
  5011. char tmp[1024];
  5012. const char* symbol = "(unknown)";
  5013. if (absl::Symbolize(raw_stack[i], tmp, sizeof(tmp))) {
  5014. symbol = tmp;
  5015. }
  5016. char line[1024];
  5017. snprintf(line, sizeof(line), " %p: %s\n", raw_stack[i], symbol);
  5018. result += line;
  5019. }
  5020. return result;
  5021. #else // !GTEST_HAS_ABSL
  5022. static_cast<void>(max_depth);
  5023. static_cast<void>(skip_count);
  5024. return "";
  5025. #endif // GTEST_HAS_ABSL
  5026. }
  5027. void OsStackTraceGetter::UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_) {
  5028. #if GTEST_HAS_ABSL
  5029. void* caller_frame = nullptr;
  5030. if (absl::GetStackTrace(&caller_frame, 1, 3) <= 0) {
  5031. caller_frame = nullptr;
  5032. }
  5033. MutexLock lock(&mutex_);
  5034. caller_frame_ = caller_frame;
  5035. #endif // GTEST_HAS_ABSL
  5036. }
  5037. // A helper class that creates the premature-exit file in its
  5038. // constructor and deletes the file in its destructor.
  5039. class ScopedPrematureExitFile {
  5040. public:
  5041. explicit ScopedPrematureExitFile(const char* premature_exit_filepath)
  5042. : premature_exit_filepath_(premature_exit_filepath ?
  5043. premature_exit_filepath : "") {
  5044. // If a path to the premature-exit file is specified...
  5045. if (!premature_exit_filepath_.empty()) {
  5046. // create the file with a single "0" character in it. I/O
  5047. // errors are ignored as there's nothing better we can do and we
  5048. // don't want to fail the test because of this.
  5049. FILE* pfile = posix::FOpen(premature_exit_filepath, "w");
  5050. fwrite("0", 1, 1, pfile);
  5051. fclose(pfile);
  5052. }
  5053. }
  5054. ~ScopedPrematureExitFile() {
  5055. if (!premature_exit_filepath_.empty()) {
  5056. int retval = remove(premature_exit_filepath_.c_str());
  5057. if (retval) {
  5058. GTEST_LOG_(ERROR) << "Failed to remove premature exit filepath \""
  5059. << premature_exit_filepath_ << "\" with error "
  5060. << retval;
  5061. }
  5062. }
  5063. }
  5064. private:
  5065. const std::string premature_exit_filepath_;
  5066. GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedPrematureExitFile);
  5067. };
  5068. } // namespace internal
  5069. // class TestEventListeners
  5070. TestEventListeners::TestEventListeners()
  5071. : repeater_(new internal::TestEventRepeater()),
  5072. default_result_printer_(nullptr),
  5073. default_xml_generator_(nullptr) {}
  5074. TestEventListeners::~TestEventListeners() { delete repeater_; }
  5075. // Returns the standard listener responsible for the default console
  5076. // output. Can be removed from the listeners list to shut down default
  5077. // console output. Note that removing this object from the listener list
  5078. // with Release transfers its ownership to the user.
  5079. void TestEventListeners::Append(TestEventListener* listener) {
  5080. repeater_->Append(listener);
  5081. }
  5082. // Removes the given event listener from the list and returns it. It then
  5083. // becomes the caller's responsibility to delete the listener. Returns
  5084. // NULL if the listener is not found in the list.
  5085. TestEventListener* TestEventListeners::Release(TestEventListener* listener) {
  5086. if (listener == default_result_printer_)
  5087. default_result_printer_ = nullptr;
  5088. else if (listener == default_xml_generator_)
  5089. default_xml_generator_ = nullptr;
  5090. return repeater_->Release(listener);
  5091. }
  5092. // Returns repeater that broadcasts the TestEventListener events to all
  5093. // subscribers.
  5094. TestEventListener* TestEventListeners::repeater() { return repeater_; }
  5095. // Sets the default_result_printer attribute to the provided listener.
  5096. // The listener is also added to the listener list and previous
  5097. // default_result_printer is removed from it and deleted. The listener can
  5098. // also be NULL in which case it will not be added to the list. Does
  5099. // nothing if the previous and the current listener objects are the same.
  5100. void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
  5101. if (default_result_printer_ != listener) {
  5102. // It is an error to pass this method a listener that is already in the
  5103. // list.
  5104. delete Release(default_result_printer_);
  5105. default_result_printer_ = listener;
  5106. if (listener != nullptr) Append(listener);
  5107. }
  5108. }
  5109. // Sets the default_xml_generator attribute to the provided listener. The
  5110. // listener is also added to the listener list and previous
  5111. // default_xml_generator is removed from it and deleted. The listener can
  5112. // also be NULL in which case it will not be added to the list. Does
  5113. // nothing if the previous and the current listener objects are the same.
  5114. void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
  5115. if (default_xml_generator_ != listener) {
  5116. // It is an error to pass this method a listener that is already in the
  5117. // list.
  5118. delete Release(default_xml_generator_);
  5119. default_xml_generator_ = listener;
  5120. if (listener != nullptr) Append(listener);
  5121. }
  5122. }
  5123. // Controls whether events will be forwarded by the repeater to the
  5124. // listeners in the list.
  5125. bool TestEventListeners::EventForwardingEnabled() const {
  5126. return repeater_->forwarding_enabled();
  5127. }
  5128. void TestEventListeners::SuppressEventForwarding() {
  5129. repeater_->set_forwarding_enabled(false);
  5130. }
  5131. // class UnitTest
  5132. // Gets the singleton UnitTest object. The first time this method is
  5133. // called, a UnitTest object is constructed and returned. Consecutive
  5134. // calls will return the same object.
  5135. //
  5136. // We don't protect this under mutex_ as a user is not supposed to
  5137. // call this before main() starts, from which point on the return
  5138. // value will never change.
  5139. UnitTest* UnitTest::GetInstance() {
  5140. // CodeGear C++Builder insists on a public destructor for the
  5141. // default implementation. Use this implementation to keep good OO
  5142. // design with private destructor.
  5143. #if defined(__BORLANDC__)
  5144. static UnitTest* const instance = new UnitTest;
  5145. return instance;
  5146. #else
  5147. static UnitTest instance;
  5148. return &instance;
  5149. #endif // defined(__BORLANDC__)
  5150. }
  5151. // Gets the number of successful test suites.
  5152. int UnitTest::successful_test_suite_count() const {
  5153. return impl()->successful_test_suite_count();
  5154. }
  5155. // Gets the number of failed test suites.
  5156. int UnitTest::failed_test_suite_count() const {
  5157. return impl()->failed_test_suite_count();
  5158. }
  5159. // Gets the number of all test suites.
  5160. int UnitTest::total_test_suite_count() const {
  5161. return impl()->total_test_suite_count();
  5162. }
  5163. // Gets the number of all test suites that contain at least one test
  5164. // that should run.
  5165. int UnitTest::test_suite_to_run_count() const {
  5166. return impl()->test_suite_to_run_count();
  5167. }
  5168. // Legacy API is deprecated but still available
  5169. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  5170. int UnitTest::successful_test_case_count() const {
  5171. return impl()->successful_test_suite_count();
  5172. }
  5173. int UnitTest::failed_test_case_count() const {
  5174. return impl()->failed_test_suite_count();
  5175. }
  5176. int UnitTest::total_test_case_count() const {
  5177. return impl()->total_test_suite_count();
  5178. }
  5179. int UnitTest::test_case_to_run_count() const {
  5180. return impl()->test_suite_to_run_count();
  5181. }
  5182. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  5183. // Gets the number of successful tests.
  5184. int UnitTest::successful_test_count() const {
  5185. return impl()->successful_test_count();
  5186. }
  5187. // Gets the number of skipped tests.
  5188. int UnitTest::skipped_test_count() const {
  5189. return impl()->skipped_test_count();
  5190. }
  5191. // Gets the number of failed tests.
  5192. int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
  5193. // Gets the number of disabled tests that will be reported in the XML report.
  5194. int UnitTest::reportable_disabled_test_count() const {
  5195. return impl()->reportable_disabled_test_count();
  5196. }
  5197. // Gets the number of disabled tests.
  5198. int UnitTest::disabled_test_count() const {
  5199. return impl()->disabled_test_count();
  5200. }
  5201. // Gets the number of tests to be printed in the XML report.
  5202. int UnitTest::reportable_test_count() const {
  5203. return impl()->reportable_test_count();
  5204. }
  5205. // Gets the number of all tests.
  5206. int UnitTest::total_test_count() const { return impl()->total_test_count(); }
  5207. // Gets the number of tests that should run.
  5208. int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
  5209. // Gets the time of the test program start, in ms from the start of the
  5210. // UNIX epoch.
  5211. internal::TimeInMillis UnitTest::start_timestamp() const {
  5212. return impl()->start_timestamp();
  5213. }
  5214. // Gets the elapsed time, in milliseconds.
  5215. internal::TimeInMillis UnitTest::elapsed_time() const {
  5216. return impl()->elapsed_time();
  5217. }
  5218. // Returns true iff the unit test passed (i.e. all test suites passed).
  5219. bool UnitTest::Passed() const { return impl()->Passed(); }
  5220. // Returns true iff the unit test failed (i.e. some test suite failed
  5221. // or something outside of all tests failed).
  5222. bool UnitTest::Failed() const { return impl()->Failed(); }
  5223. // Gets the i-th test suite among all the test suites. i can range from 0 to
  5224. // total_test_suite_count() - 1. If i is not in that range, returns NULL.
  5225. const TestSuite* UnitTest::GetTestSuite(int i) const {
  5226. return impl()->GetTestSuite(i);
  5227. }
  5228. // Legacy API is deprecated but still available
  5229. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  5230. const TestCase* UnitTest::GetTestCase(int i) const {
  5231. return impl()->GetTestCase(i);
  5232. }
  5233. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  5234. // Returns the TestResult containing information on test failures and
  5235. // properties logged outside of individual test suites.
  5236. const TestResult& UnitTest::ad_hoc_test_result() const {
  5237. return *impl()->ad_hoc_test_result();
  5238. }
  5239. // Gets the i-th test suite among all the test suites. i can range from 0 to
  5240. // total_test_suite_count() - 1. If i is not in that range, returns NULL.
  5241. TestSuite* UnitTest::GetMutableTestSuite(int i) {
  5242. return impl()->GetMutableSuiteCase(i);
  5243. }
  5244. // Returns the list of event listeners that can be used to track events
  5245. // inside Google Test.
  5246. TestEventListeners& UnitTest::listeners() {
  5247. return *impl()->listeners();
  5248. }
  5249. // Registers and returns a global test environment. When a test
  5250. // program is run, all global test environments will be set-up in the
  5251. // order they were registered. After all tests in the program have
  5252. // finished, all global test environments will be torn-down in the
  5253. // *reverse* order they were registered.
  5254. //
  5255. // The UnitTest object takes ownership of the given environment.
  5256. //
  5257. // We don't protect this under mutex_, as we only support calling it
  5258. // from the main thread.
  5259. Environment* UnitTest::AddEnvironment(Environment* env) {
  5260. if (env == nullptr) {
  5261. return nullptr;
  5262. }
  5263. impl_->environments().push_back(env);
  5264. return env;
  5265. }
  5266. // Adds a TestPartResult to the current TestResult object. All Google Test
  5267. // assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
  5268. // this to report their results. The user code should use the
  5269. // assertion macros instead of calling this directly.
  5270. void UnitTest::AddTestPartResult(
  5271. TestPartResult::Type result_type,
  5272. const char* file_name,
  5273. int line_number,
  5274. const std::string& message,
  5275. const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_) {
  5276. Message msg;
  5277. msg << message;
  5278. internal::MutexLock lock(&mutex_);
  5279. if (impl_->gtest_trace_stack().size() > 0) {
  5280. msg << "\n" << GTEST_NAME_ << " trace:";
  5281. for (int i = static_cast<int>(impl_->gtest_trace_stack().size());
  5282. i > 0; --i) {
  5283. const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
  5284. msg << "\n" << internal::FormatFileLocation(trace.file, trace.line)
  5285. << " " << trace.message;
  5286. }
  5287. }
  5288. if (os_stack_trace.c_str() != nullptr && !os_stack_trace.empty()) {
  5289. msg << internal::kStackTraceMarker << os_stack_trace;
  5290. }
  5291. const TestPartResult result = TestPartResult(
  5292. result_type, file_name, line_number, msg.GetString().c_str());
  5293. impl_->GetTestPartResultReporterForCurrentThread()->
  5294. ReportTestPartResult(result);
  5295. if (result_type != TestPartResult::kSuccess &&
  5296. result_type != TestPartResult::kSkip) {
  5297. // gtest_break_on_failure takes precedence over
  5298. // gtest_throw_on_failure. This allows a user to set the latter
  5299. // in the code (perhaps in order to use Google Test assertions
  5300. // with another testing framework) and specify the former on the
  5301. // command line for debugging.
  5302. if (GTEST_FLAG(break_on_failure)) {
  5303. #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
  5304. // Using DebugBreak on Windows allows gtest to still break into a debugger
  5305. // when a failure happens and both the --gtest_break_on_failure and
  5306. // the --gtest_catch_exceptions flags are specified.
  5307. DebugBreak();
  5308. #elif (!defined(__native_client__)) && \
  5309. ((defined(__clang__) || defined(__GNUC__)) && \
  5310. (defined(__x86_64__) || defined(__i386__)))
  5311. // with clang/gcc we can achieve the same effect on x86 by invoking int3
  5312. asm("int3");
  5313. #else
  5314. // Dereference nullptr through a volatile pointer to prevent the compiler
  5315. // from removing. We use this rather than abort() or __builtin_trap() for
  5316. // portability: some debuggers don't correctly trap abort().
  5317. *static_cast<volatile int*>(nullptr) = 1;
  5318. #endif // GTEST_OS_WINDOWS
  5319. } else if (GTEST_FLAG(throw_on_failure)) {
  5320. #if GTEST_HAS_EXCEPTIONS
  5321. throw internal::GoogleTestFailureException(result);
  5322. #else
  5323. // We cannot call abort() as it generates a pop-up in debug mode
  5324. // that cannot be suppressed in VC 7.1 or below.
  5325. exit(1);
  5326. #endif
  5327. }
  5328. }
  5329. }
  5330. // Adds a TestProperty to the current TestResult object when invoked from
  5331. // inside a test, to current TestSuite's ad_hoc_test_result_ when invoked
  5332. // from SetUpTestSuite or TearDownTestSuite, or to the global property set
  5333. // when invoked elsewhere. If the result already contains a property with
  5334. // the same key, the value will be updated.
  5335. void UnitTest::RecordProperty(const std::string& key,
  5336. const std::string& value) {
  5337. impl_->RecordProperty(TestProperty(key, value));
  5338. }
  5339. // Runs all tests in this UnitTest object and prints the result.
  5340. // Returns 0 if successful, or 1 otherwise.
  5341. //
  5342. // We don't protect this under mutex_, as we only support calling it
  5343. // from the main thread.
  5344. int UnitTest::Run() {
  5345. const bool in_death_test_child_process =
  5346. internal::GTEST_FLAG(internal_run_death_test).length() > 0;
  5347. // Google Test implements this protocol for catching that a test
  5348. // program exits before returning control to Google Test:
  5349. //
  5350. // 1. Upon start, Google Test creates a file whose absolute path
  5351. // is specified by the environment variable
  5352. // TEST_PREMATURE_EXIT_FILE.
  5353. // 2. When Google Test has finished its work, it deletes the file.
  5354. //
  5355. // This allows a test runner to set TEST_PREMATURE_EXIT_FILE before
  5356. // running a Google-Test-based test program and check the existence
  5357. // of the file at the end of the test execution to see if it has
  5358. // exited prematurely.
  5359. // If we are in the child process of a death test, don't
  5360. // create/delete the premature exit file, as doing so is unnecessary
  5361. // and will confuse the parent process. Otherwise, create/delete
  5362. // the file upon entering/leaving this function. If the program
  5363. // somehow exits before this function has a chance to return, the
  5364. // premature-exit file will be left undeleted, causing a test runner
  5365. // that understands the premature-exit-file protocol to report the
  5366. // test as having failed.
  5367. const internal::ScopedPrematureExitFile premature_exit_file(
  5368. in_death_test_child_process
  5369. ? nullptr
  5370. : internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE"));
  5371. // Captures the value of GTEST_FLAG(catch_exceptions). This value will be
  5372. // used for the duration of the program.
  5373. impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions));
  5374. #if GTEST_OS_WINDOWS
  5375. // Either the user wants Google Test to catch exceptions thrown by the
  5376. // tests or this is executing in the context of death test child
  5377. // process. In either case the user does not want to see pop-up dialogs
  5378. // about crashes - they are expected.
  5379. if (impl()->catch_exceptions() || in_death_test_child_process) {
  5380. # if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
  5381. // SetErrorMode doesn't exist on CE.
  5382. SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
  5383. SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
  5384. # endif // !GTEST_OS_WINDOWS_MOBILE
  5385. # if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
  5386. // Death test children can be terminated with _abort(). On Windows,
  5387. // _abort() can show a dialog with a warning message. This forces the
  5388. // abort message to go to stderr instead.
  5389. _set_error_mode(_OUT_TO_STDERR);
  5390. # endif
  5391. # if defined(_MSC_VER) && !GTEST_OS_WINDOWS_MOBILE
  5392. // In the debug version, Visual Studio pops up a separate dialog
  5393. // offering a choice to debug the aborted program. We need to suppress
  5394. // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
  5395. // executed. Google Test will notify the user of any unexpected
  5396. // failure via stderr.
  5397. if (!GTEST_FLAG(break_on_failure))
  5398. _set_abort_behavior(
  5399. 0x0, // Clear the following flags:
  5400. _WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump.
  5401. # endif
  5402. }
  5403. #endif // GTEST_OS_WINDOWS
  5404. return internal::HandleExceptionsInMethodIfSupported(
  5405. impl(),
  5406. &internal::UnitTestImpl::RunAllTests,
  5407. "auxiliary test code (environments or event listeners)") ? 0 : 1;
  5408. }
  5409. // Returns the working directory when the first TEST() or TEST_F() was
  5410. // executed.
  5411. const char* UnitTest::original_working_dir() const {
  5412. return impl_->original_working_dir_.c_str();
  5413. }
  5414. // Returns the TestSuite object for the test that's currently running,
  5415. // or NULL if no test is running.
  5416. const TestSuite* UnitTest::current_test_suite() const
  5417. GTEST_LOCK_EXCLUDED_(mutex_) {
  5418. internal::MutexLock lock(&mutex_);
  5419. return impl_->current_test_suite();
  5420. }
  5421. // Legacy API is still available but deprecated
  5422. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  5423. const TestCase* UnitTest::current_test_case() const
  5424. GTEST_LOCK_EXCLUDED_(mutex_) {
  5425. internal::MutexLock lock(&mutex_);
  5426. return impl_->current_test_suite();
  5427. }
  5428. #endif
  5429. // Returns the TestInfo object for the test that's currently running,
  5430. // or NULL if no test is running.
  5431. const TestInfo* UnitTest::current_test_info() const
  5432. GTEST_LOCK_EXCLUDED_(mutex_) {
  5433. internal::MutexLock lock(&mutex_);
  5434. return impl_->current_test_info();
  5435. }
  5436. // Returns the random seed used at the start of the current test run.
  5437. int UnitTest::random_seed() const { return impl_->random_seed(); }
  5438. // Returns ParameterizedTestSuiteRegistry object used to keep track of
  5439. // value-parameterized tests and instantiate and register them.
  5440. internal::ParameterizedTestSuiteRegistry&
  5441. UnitTest::parameterized_test_registry() GTEST_LOCK_EXCLUDED_(mutex_) {
  5442. return impl_->parameterized_test_registry();
  5443. }
  5444. // Creates an empty UnitTest.
  5445. UnitTest::UnitTest() {
  5446. impl_ = new internal::UnitTestImpl(this);
  5447. }
  5448. // Destructor of UnitTest.
  5449. UnitTest::~UnitTest() {
  5450. delete impl_;
  5451. }
  5452. // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
  5453. // Google Test trace stack.
  5454. void UnitTest::PushGTestTrace(const internal::TraceInfo& trace)
  5455. GTEST_LOCK_EXCLUDED_(mutex_) {
  5456. internal::MutexLock lock(&mutex_);
  5457. impl_->gtest_trace_stack().push_back(trace);
  5458. }
  5459. // Pops a trace from the per-thread Google Test trace stack.
  5460. void UnitTest::PopGTestTrace()
  5461. GTEST_LOCK_EXCLUDED_(mutex_) {
  5462. internal::MutexLock lock(&mutex_);
  5463. impl_->gtest_trace_stack().pop_back();
  5464. }
  5465. namespace internal {
  5466. UnitTestImpl::UnitTestImpl(UnitTest* parent)
  5467. : parent_(parent),
  5468. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355 /* using this in initializer */)
  5469. default_global_test_part_result_reporter_(this),
  5470. default_per_thread_test_part_result_reporter_(this),
  5471. GTEST_DISABLE_MSC_WARNINGS_POP_() global_test_part_result_repoter_(
  5472. &default_global_test_part_result_reporter_),
  5473. per_thread_test_part_result_reporter_(
  5474. &default_per_thread_test_part_result_reporter_),
  5475. parameterized_test_registry_(),
  5476. parameterized_tests_registered_(false),
  5477. last_death_test_suite_(-1),
  5478. current_test_suite_(nullptr),
  5479. current_test_info_(nullptr),
  5480. ad_hoc_test_result_(),
  5481. os_stack_trace_getter_(nullptr),
  5482. post_flag_parse_init_performed_(false),
  5483. random_seed_(0), // Will be overridden by the flag before first use.
  5484. random_(0), // Will be reseeded before first use.
  5485. start_timestamp_(0),
  5486. elapsed_time_(0),
  5487. #if GTEST_HAS_DEATH_TEST
  5488. death_test_factory_(new DefaultDeathTestFactory),
  5489. #endif
  5490. // Will be overridden by the flag before first use.
  5491. catch_exceptions_(false) {
  5492. listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);
  5493. }
  5494. UnitTestImpl::~UnitTestImpl() {
  5495. // Deletes every TestSuite.
  5496. ForEach(test_suites_, internal::Delete<TestSuite>);
  5497. // Deletes every Environment.
  5498. ForEach(environments_, internal::Delete<Environment>);
  5499. delete os_stack_trace_getter_;
  5500. }
  5501. // Adds a TestProperty to the current TestResult object when invoked in a
  5502. // context of a test, to current test suite's ad_hoc_test_result when invoke
  5503. // from SetUpTestSuite/TearDownTestSuite, or to the global property set
  5504. // otherwise. If the result already contains a property with the same key,
  5505. // the value will be updated.
  5506. void UnitTestImpl::RecordProperty(const TestProperty& test_property) {
  5507. std::string xml_element;
  5508. TestResult* test_result; // TestResult appropriate for property recording.
  5509. if (current_test_info_ != nullptr) {
  5510. xml_element = "testcase";
  5511. test_result = &(current_test_info_->result_);
  5512. } else if (current_test_suite_ != nullptr) {
  5513. xml_element = "testsuite";
  5514. test_result = &(current_test_suite_->ad_hoc_test_result_);
  5515. } else {
  5516. xml_element = "testsuites";
  5517. test_result = &ad_hoc_test_result_;
  5518. }
  5519. test_result->RecordProperty(xml_element, test_property);
  5520. }
  5521. #if GTEST_HAS_DEATH_TEST
  5522. // Disables event forwarding if the control is currently in a death test
  5523. // subprocess. Must not be called before InitGoogleTest.
  5524. void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
  5525. if (internal_run_death_test_flag_.get() != nullptr)
  5526. listeners()->SuppressEventForwarding();
  5527. }
  5528. #endif // GTEST_HAS_DEATH_TEST
  5529. // Initializes event listeners performing XML output as specified by
  5530. // UnitTestOptions. Must not be called before InitGoogleTest.
  5531. void UnitTestImpl::ConfigureXmlOutput() {
  5532. const std::string& output_format = UnitTestOptions::GetOutputFormat();
  5533. if (output_format == "xml") {
  5534. listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
  5535. UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
  5536. } else if (output_format == "json") {
  5537. listeners()->SetDefaultXmlGenerator(new JsonUnitTestResultPrinter(
  5538. UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
  5539. } else if (output_format != "") {
  5540. GTEST_LOG_(WARNING) << "WARNING: unrecognized output format \""
  5541. << output_format << "\" ignored.";
  5542. }
  5543. }
  5544. #if GTEST_CAN_STREAM_RESULTS_
  5545. // Initializes event listeners for streaming test results in string form.
  5546. // Must not be called before InitGoogleTest.
  5547. void UnitTestImpl::ConfigureStreamingOutput() {
  5548. const std::string& target = GTEST_FLAG(stream_result_to);
  5549. if (!target.empty()) {
  5550. const size_t pos = target.find(':');
  5551. if (pos != std::string::npos) {
  5552. listeners()->Append(new StreamingListener(target.substr(0, pos),
  5553. target.substr(pos+1)));
  5554. } else {
  5555. GTEST_LOG_(WARNING) << "unrecognized streaming target \"" << target
  5556. << "\" ignored.";
  5557. }
  5558. }
  5559. }
  5560. #endif // GTEST_CAN_STREAM_RESULTS_
  5561. // Performs initialization dependent upon flag values obtained in
  5562. // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
  5563. // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
  5564. // this function is also called from RunAllTests. Since this function can be
  5565. // called more than once, it has to be idempotent.
  5566. void UnitTestImpl::PostFlagParsingInit() {
  5567. // Ensures that this function does not execute more than once.
  5568. if (!post_flag_parse_init_performed_) {
  5569. post_flag_parse_init_performed_ = true;
  5570. #if defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
  5571. // Register to send notifications about key process state changes.
  5572. listeners()->Append(new GTEST_CUSTOM_TEST_EVENT_LISTENER_());
  5573. #endif // defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
  5574. #if GTEST_HAS_DEATH_TEST
  5575. InitDeathTestSubprocessControlInfo();
  5576. SuppressTestEventsIfInSubprocess();
  5577. #endif // GTEST_HAS_DEATH_TEST
  5578. // Registers parameterized tests. This makes parameterized tests
  5579. // available to the UnitTest reflection API without running
  5580. // RUN_ALL_TESTS.
  5581. RegisterParameterizedTests();
  5582. // Configures listeners for XML output. This makes it possible for users
  5583. // to shut down the default XML output before invoking RUN_ALL_TESTS.
  5584. ConfigureXmlOutput();
  5585. #if GTEST_CAN_STREAM_RESULTS_
  5586. // Configures listeners for streaming test results to the specified server.
  5587. ConfigureStreamingOutput();
  5588. #endif // GTEST_CAN_STREAM_RESULTS_
  5589. #if GTEST_HAS_ABSL
  5590. if (GTEST_FLAG(install_failure_signal_handler)) {
  5591. absl::FailureSignalHandlerOptions options;
  5592. absl::InstallFailureSignalHandler(options);
  5593. }
  5594. #endif // GTEST_HAS_ABSL
  5595. }
  5596. }
  5597. // A predicate that checks the name of a TestSuite against a known
  5598. // value.
  5599. //
  5600. // This is used for implementation of the UnitTest class only. We put
  5601. // it in the anonymous namespace to prevent polluting the outer
  5602. // namespace.
  5603. //
  5604. // TestSuiteNameIs is copyable.
  5605. class TestSuiteNameIs {
  5606. public:
  5607. // Constructor.
  5608. explicit TestSuiteNameIs(const std::string& name) : name_(name) {}
  5609. // Returns true iff the name of test_suite matches name_.
  5610. bool operator()(const TestSuite* test_suite) const {
  5611. return test_suite != nullptr &&
  5612. strcmp(test_suite->name(), name_.c_str()) == 0;
  5613. }
  5614. private:
  5615. std::string name_;
  5616. };
  5617. // Finds and returns a TestSuite with the given name. If one doesn't
  5618. // exist, creates one and returns it. It's the CALLER'S
  5619. // RESPONSIBILITY to ensure that this function is only called WHEN THE
  5620. // TESTS ARE NOT SHUFFLED.
  5621. //
  5622. // Arguments:
  5623. //
  5624. // test_suite_name: name of the test suite
  5625. // type_param: the name of the test suite's type parameter, or NULL if
  5626. // this is not a typed or a type-parameterized test suite.
  5627. // set_up_tc: pointer to the function that sets up the test suite
  5628. // tear_down_tc: pointer to the function that tears down the test suite
  5629. TestSuite* UnitTestImpl::GetTestSuite(
  5630. const char* test_suite_name, const char* type_param,
  5631. internal::SetUpTestSuiteFunc set_up_tc,
  5632. internal::TearDownTestSuiteFunc tear_down_tc) {
  5633. // Can we find a TestSuite with the given name?
  5634. const auto test_suite =
  5635. std::find_if(test_suites_.rbegin(), test_suites_.rend(),
  5636. TestSuiteNameIs(test_suite_name));
  5637. if (test_suite != test_suites_.rend()) return *test_suite;
  5638. // No. Let's create one.
  5639. auto* const new_test_suite =
  5640. new TestSuite(test_suite_name, type_param, set_up_tc, tear_down_tc);
  5641. // Is this a death test suite?
  5642. if (internal::UnitTestOptions::MatchesFilter(test_suite_name,
  5643. kDeathTestSuiteFilter)) {
  5644. // Yes. Inserts the test suite after the last death test suite
  5645. // defined so far. This only works when the test suites haven't
  5646. // been shuffled. Otherwise we may end up running a death test
  5647. // after a non-death test.
  5648. ++last_death_test_suite_;
  5649. test_suites_.insert(test_suites_.begin() + last_death_test_suite_,
  5650. new_test_suite);
  5651. } else {
  5652. // No. Appends to the end of the list.
  5653. test_suites_.push_back(new_test_suite);
  5654. }
  5655. test_suite_indices_.push_back(static_cast<int>(test_suite_indices_.size()));
  5656. return new_test_suite;
  5657. }
  5658. // Helpers for setting up / tearing down the given environment. They
  5659. // are for use in the ForEach() function.
  5660. static void SetUpEnvironment(Environment* env) { env->SetUp(); }
  5661. static void TearDownEnvironment(Environment* env) { env->TearDown(); }
  5662. // Runs all tests in this UnitTest object, prints the result, and
  5663. // returns true if all tests are successful. If any exception is
  5664. // thrown during a test, the test is considered to be failed, but the
  5665. // rest of the tests will still be run.
  5666. //
  5667. // When parameterized tests are enabled, it expands and registers
  5668. // parameterized tests first in RegisterParameterizedTests().
  5669. // All other functions called from RunAllTests() may safely assume that
  5670. // parameterized tests are ready to be counted and run.
  5671. bool UnitTestImpl::RunAllTests() {
  5672. // True iff Google Test is initialized before RUN_ALL_TESTS() is called.
  5673. const bool gtest_is_initialized_before_run_all_tests = GTestIsInitialized();
  5674. // Do not run any test if the --help flag was specified.
  5675. if (g_help_flag)
  5676. return true;
  5677. // Repeats the call to the post-flag parsing initialization in case the
  5678. // user didn't call InitGoogleTest.
  5679. PostFlagParsingInit();
  5680. // Even if sharding is not on, test runners may want to use the
  5681. // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
  5682. // protocol.
  5683. internal::WriteToShardStatusFileIfNeeded();
  5684. // True iff we are in a subprocess for running a thread-safe-style
  5685. // death test.
  5686. bool in_subprocess_for_death_test = false;
  5687. #if GTEST_HAS_DEATH_TEST
  5688. in_subprocess_for_death_test =
  5689. (internal_run_death_test_flag_.get() != nullptr);
  5690. # if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
  5691. if (in_subprocess_for_death_test) {
  5692. GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_();
  5693. }
  5694. # endif // defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
  5695. #endif // GTEST_HAS_DEATH_TEST
  5696. const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
  5697. in_subprocess_for_death_test);
  5698. // Compares the full test names with the filter to decide which
  5699. // tests to run.
  5700. const bool has_tests_to_run = FilterTests(should_shard
  5701. ? HONOR_SHARDING_PROTOCOL
  5702. : IGNORE_SHARDING_PROTOCOL) > 0;
  5703. // Lists the tests and exits if the --gtest_list_tests flag was specified.
  5704. if (GTEST_FLAG(list_tests)) {
  5705. // This must be called *after* FilterTests() has been called.
  5706. ListTestsMatchingFilter();
  5707. return true;
  5708. }
  5709. random_seed_ = GTEST_FLAG(shuffle) ?
  5710. GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;
  5711. // True iff at least one test has failed.
  5712. bool failed = false;
  5713. TestEventListener* repeater = listeners()->repeater();
  5714. start_timestamp_ = GetTimeInMillis();
  5715. repeater->OnTestProgramStart(*parent_);
  5716. // How many times to repeat the tests? We don't want to repeat them
  5717. // when we are inside the subprocess of a death test.
  5718. const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);
  5719. // Repeats forever if the repeat count is negative.
  5720. const bool forever = repeat < 0;
  5721. for (int i = 0; forever || i != repeat; i++) {
  5722. // We want to preserve failures generated by ad-hoc test
  5723. // assertions executed before RUN_ALL_TESTS().
  5724. ClearNonAdHocTestResult();
  5725. const TimeInMillis start = GetTimeInMillis();
  5726. // Shuffles test suites and tests if requested.
  5727. if (has_tests_to_run && GTEST_FLAG(shuffle)) {
  5728. random()->Reseed(random_seed_);
  5729. // This should be done before calling OnTestIterationStart(),
  5730. // such that a test event listener can see the actual test order
  5731. // in the event.
  5732. ShuffleTests();
  5733. }
  5734. // Tells the unit test event listeners that the tests are about to start.
  5735. repeater->OnTestIterationStart(*parent_, i);
  5736. // Runs each test suite if there is at least one test to run.
  5737. if (has_tests_to_run) {
  5738. // Sets up all environments beforehand.
  5739. repeater->OnEnvironmentsSetUpStart(*parent_);
  5740. ForEach(environments_, SetUpEnvironment);
  5741. repeater->OnEnvironmentsSetUpEnd(*parent_);
  5742. // Runs the tests only if there was no fatal failure during global
  5743. // set-up.
  5744. if (!Test::HasFatalFailure()) {
  5745. for (int test_index = 0; test_index < total_test_suite_count();
  5746. test_index++) {
  5747. GetMutableSuiteCase(test_index)->Run();
  5748. }
  5749. }
  5750. // Tears down all environments in reverse order afterwards.
  5751. repeater->OnEnvironmentsTearDownStart(*parent_);
  5752. std::for_each(environments_.rbegin(), environments_.rend(),
  5753. TearDownEnvironment);
  5754. repeater->OnEnvironmentsTearDownEnd(*parent_);
  5755. }
  5756. elapsed_time_ = GetTimeInMillis() - start;
  5757. // Tells the unit test event listener that the tests have just finished.
  5758. repeater->OnTestIterationEnd(*parent_, i);
  5759. // Gets the result and clears it.
  5760. if (!Passed()) {
  5761. failed = true;
  5762. }
  5763. // Restores the original test order after the iteration. This
  5764. // allows the user to quickly repro a failure that happens in the
  5765. // N-th iteration without repeating the first (N - 1) iterations.
  5766. // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in
  5767. // case the user somehow changes the value of the flag somewhere
  5768. // (it's always safe to unshuffle the tests).
  5769. UnshuffleTests();
  5770. if (GTEST_FLAG(shuffle)) {
  5771. // Picks a new random seed for each iteration.
  5772. random_seed_ = GetNextRandomSeed(random_seed_);
  5773. }
  5774. }
  5775. repeater->OnTestProgramEnd(*parent_);
  5776. if (!gtest_is_initialized_before_run_all_tests) {
  5777. ColoredPrintf(
  5778. COLOR_RED,
  5779. "\nIMPORTANT NOTICE - DO NOT IGNORE:\n"
  5780. "This test program did NOT call " GTEST_INIT_GOOGLE_TEST_NAME_
  5781. "() before calling RUN_ALL_TESTS(). This is INVALID. Soon " GTEST_NAME_
  5782. " will start to enforce the valid usage. "
  5783. "Please fix it ASAP, or IT WILL START TO FAIL.\n"); // NOLINT
  5784. #if GTEST_FOR_GOOGLE_
  5785. ColoredPrintf(COLOR_RED,
  5786. "For more details, see http://wiki/Main/ValidGUnitMain.\n");
  5787. #endif // GTEST_FOR_GOOGLE_
  5788. }
  5789. return !failed;
  5790. }
  5791. // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
  5792. // if the variable is present. If a file already exists at this location, this
  5793. // function will write over it. If the variable is present, but the file cannot
  5794. // be created, prints an error and exits.
  5795. void WriteToShardStatusFileIfNeeded() {
  5796. const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);
  5797. if (test_shard_file != nullptr) {
  5798. FILE* const file = posix::FOpen(test_shard_file, "w");
  5799. if (file == nullptr) {
  5800. ColoredPrintf(COLOR_RED,
  5801. "Could not write to the test shard status file \"%s\" "
  5802. "specified by the %s environment variable.\n",
  5803. test_shard_file, kTestShardStatusFile);
  5804. fflush(stdout);
  5805. exit(EXIT_FAILURE);
  5806. }
  5807. fclose(file);
  5808. }
  5809. }
  5810. // Checks whether sharding is enabled by examining the relevant
  5811. // environment variable values. If the variables are present,
  5812. // but inconsistent (i.e., shard_index >= total_shards), prints
  5813. // an error and exits. If in_subprocess_for_death_test, sharding is
  5814. // disabled because it must only be applied to the original test
  5815. // process. Otherwise, we could filter out death tests we intended to execute.
  5816. bool ShouldShard(const char* total_shards_env,
  5817. const char* shard_index_env,
  5818. bool in_subprocess_for_death_test) {
  5819. if (in_subprocess_for_death_test) {
  5820. return false;
  5821. }
  5822. const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1);
  5823. const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1);
  5824. if (total_shards == -1 && shard_index == -1) {
  5825. return false;
  5826. } else if (total_shards == -1 && shard_index != -1) {
  5827. const Message msg = Message()
  5828. << "Invalid environment variables: you have "
  5829. << kTestShardIndex << " = " << shard_index
  5830. << ", but have left " << kTestTotalShards << " unset.\n";
  5831. ColoredPrintf(COLOR_RED, "%s", msg.GetString().c_str());
  5832. fflush(stdout);
  5833. exit(EXIT_FAILURE);
  5834. } else if (total_shards != -1 && shard_index == -1) {
  5835. const Message msg = Message()
  5836. << "Invalid environment variables: you have "
  5837. << kTestTotalShards << " = " << total_shards
  5838. << ", but have left " << kTestShardIndex << " unset.\n";
  5839. ColoredPrintf(COLOR_RED, "%s", msg.GetString().c_str());
  5840. fflush(stdout);
  5841. exit(EXIT_FAILURE);
  5842. } else if (shard_index < 0 || shard_index >= total_shards) {
  5843. const Message msg = Message()
  5844. << "Invalid environment variables: we require 0 <= "
  5845. << kTestShardIndex << " < " << kTestTotalShards
  5846. << ", but you have " << kTestShardIndex << "=" << shard_index
  5847. << ", " << kTestTotalShards << "=" << total_shards << ".\n";
  5848. ColoredPrintf(COLOR_RED, "%s", msg.GetString().c_str());
  5849. fflush(stdout);
  5850. exit(EXIT_FAILURE);
  5851. }
  5852. return total_shards > 1;
  5853. }
  5854. // Parses the environment variable var as an Int32. If it is unset,
  5855. // returns default_val. If it is not an Int32, prints an error
  5856. // and aborts.
  5857. Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) {
  5858. const char* str_val = posix::GetEnv(var);
  5859. if (str_val == nullptr) {
  5860. return default_val;
  5861. }
  5862. Int32 result;
  5863. if (!ParseInt32(Message() << "The value of environment variable " << var,
  5864. str_val, &result)) {
  5865. exit(EXIT_FAILURE);
  5866. }
  5867. return result;
  5868. }
  5869. // Given the total number of shards, the shard index, and the test id,
  5870. // returns true iff the test should be run on this shard. The test id is
  5871. // some arbitrary but unique non-negative integer assigned to each test
  5872. // method. Assumes that 0 <= shard_index < total_shards.
  5873. bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
  5874. return (test_id % total_shards) == shard_index;
  5875. }
  5876. // Compares the name of each test with the user-specified filter to
  5877. // decide whether the test should be run, then records the result in
  5878. // each TestSuite and TestInfo object.
  5879. // If shard_tests == true, further filters tests based on sharding
  5880. // variables in the environment - see
  5881. // https://github.com/google/googletest/blob/master/googletest/docs/advanced.md
  5882. // . Returns the number of tests that should run.
  5883. int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
  5884. const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?
  5885. Int32FromEnvOrDie(kTestTotalShards, -1) : -1;
  5886. const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?
  5887. Int32FromEnvOrDie(kTestShardIndex, -1) : -1;
  5888. // num_runnable_tests are the number of tests that will
  5889. // run across all shards (i.e., match filter and are not disabled).
  5890. // num_selected_tests are the number of tests to be run on
  5891. // this shard.
  5892. int num_runnable_tests = 0;
  5893. int num_selected_tests = 0;
  5894. for (auto* test_suite : test_suites_) {
  5895. const std::string& test_suite_name = test_suite->name();
  5896. test_suite->set_should_run(false);
  5897. for (size_t j = 0; j < test_suite->test_info_list().size(); j++) {
  5898. TestInfo* const test_info = test_suite->test_info_list()[j];
  5899. const std::string test_name(test_info->name());
  5900. // A test is disabled if test suite name or test name matches
  5901. // kDisableTestFilter.
  5902. const bool is_disabled = internal::UnitTestOptions::MatchesFilter(
  5903. test_suite_name, kDisableTestFilter) ||
  5904. internal::UnitTestOptions::MatchesFilter(
  5905. test_name, kDisableTestFilter);
  5906. test_info->is_disabled_ = is_disabled;
  5907. const bool matches_filter = internal::UnitTestOptions::FilterMatchesTest(
  5908. test_suite_name, test_name);
  5909. test_info->matches_filter_ = matches_filter;
  5910. const bool is_runnable =
  5911. (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
  5912. matches_filter;
  5913. const bool is_in_another_shard =
  5914. shard_tests != IGNORE_SHARDING_PROTOCOL &&
  5915. !ShouldRunTestOnShard(total_shards, shard_index, num_runnable_tests);
  5916. test_info->is_in_another_shard_ = is_in_another_shard;
  5917. const bool is_selected = is_runnable && !is_in_another_shard;
  5918. num_runnable_tests += is_runnable;
  5919. num_selected_tests += is_selected;
  5920. test_info->should_run_ = is_selected;
  5921. test_suite->set_should_run(test_suite->should_run() || is_selected);
  5922. }
  5923. }
  5924. return num_selected_tests;
  5925. }
  5926. // Prints the given C-string on a single line by replacing all '\n'
  5927. // characters with string "\\n". If the output takes more than
  5928. // max_length characters, only prints the first max_length characters
  5929. // and "...".
  5930. static void PrintOnOneLine(const char* str, int max_length) {
  5931. if (str != nullptr) {
  5932. for (int i = 0; *str != '\0'; ++str) {
  5933. if (i >= max_length) {
  5934. printf("...");
  5935. break;
  5936. }
  5937. if (*str == '\n') {
  5938. printf("\\n");
  5939. i += 2;
  5940. } else {
  5941. printf("%c", *str);
  5942. ++i;
  5943. }
  5944. }
  5945. }
  5946. }
  5947. // Prints the names of the tests matching the user-specified filter flag.
  5948. void UnitTestImpl::ListTestsMatchingFilter() {
  5949. // Print at most this many characters for each type/value parameter.
  5950. const int kMaxParamLength = 250;
  5951. for (auto* test_suite : test_suites_) {
  5952. bool printed_test_suite_name = false;
  5953. for (size_t j = 0; j < test_suite->test_info_list().size(); j++) {
  5954. const TestInfo* const test_info = test_suite->test_info_list()[j];
  5955. if (test_info->matches_filter_) {
  5956. if (!printed_test_suite_name) {
  5957. printed_test_suite_name = true;
  5958. printf("%s.", test_suite->name());
  5959. if (test_suite->type_param() != nullptr) {
  5960. printf(" # %s = ", kTypeParamLabel);
  5961. // We print the type parameter on a single line to make
  5962. // the output easy to parse by a program.
  5963. PrintOnOneLine(test_suite->type_param(), kMaxParamLength);
  5964. }
  5965. printf("\n");
  5966. }
  5967. printf(" %s", test_info->name());
  5968. if (test_info->value_param() != nullptr) {
  5969. printf(" # %s = ", kValueParamLabel);
  5970. // We print the value parameter on a single line to make the
  5971. // output easy to parse by a program.
  5972. PrintOnOneLine(test_info->value_param(), kMaxParamLength);
  5973. }
  5974. printf("\n");
  5975. }
  5976. }
  5977. }
  5978. fflush(stdout);
  5979. const std::string& output_format = UnitTestOptions::GetOutputFormat();
  5980. if (output_format == "xml" || output_format == "json") {
  5981. FILE* fileout = OpenFileForWriting(
  5982. UnitTestOptions::GetAbsolutePathToOutputFile().c_str());
  5983. std::stringstream stream;
  5984. if (output_format == "xml") {
  5985. XmlUnitTestResultPrinter(
  5986. UnitTestOptions::GetAbsolutePathToOutputFile().c_str())
  5987. .PrintXmlTestsList(&stream, test_suites_);
  5988. } else if (output_format == "json") {
  5989. JsonUnitTestResultPrinter(
  5990. UnitTestOptions::GetAbsolutePathToOutputFile().c_str())
  5991. .PrintJsonTestList(&stream, test_suites_);
  5992. }
  5993. fprintf(fileout, "%s", StringStreamToString(&stream).c_str());
  5994. fclose(fileout);
  5995. }
  5996. }
  5997. // Sets the OS stack trace getter.
  5998. //
  5999. // Does nothing if the input and the current OS stack trace getter are
  6000. // the same; otherwise, deletes the old getter and makes the input the
  6001. // current getter.
  6002. void UnitTestImpl::set_os_stack_trace_getter(
  6003. OsStackTraceGetterInterface* getter) {
  6004. if (os_stack_trace_getter_ != getter) {
  6005. delete os_stack_trace_getter_;
  6006. os_stack_trace_getter_ = getter;
  6007. }
  6008. }
  6009. // Returns the current OS stack trace getter if it is not NULL;
  6010. // otherwise, creates an OsStackTraceGetter, makes it the current
  6011. // getter, and returns it.
  6012. OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
  6013. if (os_stack_trace_getter_ == nullptr) {
  6014. #ifdef GTEST_OS_STACK_TRACE_GETTER_
  6015. os_stack_trace_getter_ = new GTEST_OS_STACK_TRACE_GETTER_;
  6016. #else
  6017. os_stack_trace_getter_ = new OsStackTraceGetter;
  6018. #endif // GTEST_OS_STACK_TRACE_GETTER_
  6019. }
  6020. return os_stack_trace_getter_;
  6021. }
  6022. // Returns the most specific TestResult currently running.
  6023. TestResult* UnitTestImpl::current_test_result() {
  6024. if (current_test_info_ != nullptr) {
  6025. return &current_test_info_->result_;
  6026. }
  6027. if (current_test_suite_ != nullptr) {
  6028. return &current_test_suite_->ad_hoc_test_result_;
  6029. }
  6030. return &ad_hoc_test_result_;
  6031. }
  6032. // Shuffles all test suites, and the tests within each test suite,
  6033. // making sure that death tests are still run first.
  6034. void UnitTestImpl::ShuffleTests() {
  6035. // Shuffles the death test suites.
  6036. ShuffleRange(random(), 0, last_death_test_suite_ + 1, &test_suite_indices_);
  6037. // Shuffles the non-death test suites.
  6038. ShuffleRange(random(), last_death_test_suite_ + 1,
  6039. static_cast<int>(test_suites_.size()), &test_suite_indices_);
  6040. // Shuffles the tests inside each test suite.
  6041. for (auto& test_suite : test_suites_) {
  6042. test_suite->ShuffleTests(random());
  6043. }
  6044. }
  6045. // Restores the test suites and tests to their order before the first shuffle.
  6046. void UnitTestImpl::UnshuffleTests() {
  6047. for (size_t i = 0; i < test_suites_.size(); i++) {
  6048. // Unshuffles the tests in each test suite.
  6049. test_suites_[i]->UnshuffleTests();
  6050. // Resets the index of each test suite.
  6051. test_suite_indices_[i] = static_cast<int>(i);
  6052. }
  6053. }
  6054. // Returns the current OS stack trace as an std::string.
  6055. //
  6056. // The maximum number of stack frames to be included is specified by
  6057. // the gtest_stack_trace_depth flag. The skip_count parameter
  6058. // specifies the number of top frames to be skipped, which doesn't
  6059. // count against the number of frames to be included.
  6060. //
  6061. // For example, if Foo() calls Bar(), which in turn calls
  6062. // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
  6063. // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
  6064. std::string GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/,
  6065. int skip_count) {
  6066. // We pass skip_count + 1 to skip this wrapper function in addition
  6067. // to what the user really wants to skip.
  6068. return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
  6069. }
  6070. // Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to
  6071. // suppress unreachable code warnings.
  6072. namespace {
  6073. class ClassUniqueToAlwaysTrue {};
  6074. }
  6075. bool IsTrue(bool condition) { return condition; }
  6076. bool AlwaysTrue() {
  6077. #if GTEST_HAS_EXCEPTIONS
  6078. // This condition is always false so AlwaysTrue() never actually throws,
  6079. // but it makes the compiler think that it may throw.
  6080. if (IsTrue(false))
  6081. throw ClassUniqueToAlwaysTrue();
  6082. #endif // GTEST_HAS_EXCEPTIONS
  6083. return true;
  6084. }
  6085. // If *pstr starts with the given prefix, modifies *pstr to be right
  6086. // past the prefix and returns true; otherwise leaves *pstr unchanged
  6087. // and returns false. None of pstr, *pstr, and prefix can be NULL.
  6088. bool SkipPrefix(const char* prefix, const char** pstr) {
  6089. const size_t prefix_len = strlen(prefix);
  6090. if (strncmp(*pstr, prefix, prefix_len) == 0) {
  6091. *pstr += prefix_len;
  6092. return true;
  6093. }
  6094. return false;
  6095. }
  6096. // Parses a string as a command line flag. The string should have
  6097. // the format "--flag=value". When def_optional is true, the "=value"
  6098. // part can be omitted.
  6099. //
  6100. // Returns the value of the flag, or NULL if the parsing failed.
  6101. static const char* ParseFlagValue(const char* str, const char* flag,
  6102. bool def_optional) {
  6103. // str and flag must not be NULL.
  6104. if (str == nullptr || flag == nullptr) return nullptr;
  6105. // The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
  6106. const std::string flag_str = std::string("--") + GTEST_FLAG_PREFIX_ + flag;
  6107. const size_t flag_len = flag_str.length();
  6108. if (strncmp(str, flag_str.c_str(), flag_len) != 0) return nullptr;
  6109. // Skips the flag name.
  6110. const char* flag_end = str + flag_len;
  6111. // When def_optional is true, it's OK to not have a "=value" part.
  6112. if (def_optional && (flag_end[0] == '\0')) {
  6113. return flag_end;
  6114. }
  6115. // If def_optional is true and there are more characters after the
  6116. // flag name, or if def_optional is false, there must be a '=' after
  6117. // the flag name.
  6118. if (flag_end[0] != '=') return nullptr;
  6119. // Returns the string after "=".
  6120. return flag_end + 1;
  6121. }
  6122. // Parses a string for a bool flag, in the form of either
  6123. // "--flag=value" or "--flag".
  6124. //
  6125. // In the former case, the value is taken as true as long as it does
  6126. // not start with '0', 'f', or 'F'.
  6127. //
  6128. // In the latter case, the value is taken as true.
  6129. //
  6130. // On success, stores the value of the flag in *value, and returns
  6131. // true. On failure, returns false without changing *value.
  6132. static bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
  6133. // Gets the value of the flag as a string.
  6134. const char* const value_str = ParseFlagValue(str, flag, true);
  6135. // Aborts if the parsing failed.
  6136. if (value_str == nullptr) return false;
  6137. // Converts the string value to a bool.
  6138. *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
  6139. return true;
  6140. }
  6141. // Parses a string for an Int32 flag, in the form of
  6142. // "--flag=value".
  6143. //
  6144. // On success, stores the value of the flag in *value, and returns
  6145. // true. On failure, returns false without changing *value.
  6146. bool ParseInt32Flag(const char* str, const char* flag, Int32* value) {
  6147. // Gets the value of the flag as a string.
  6148. const char* const value_str = ParseFlagValue(str, flag, false);
  6149. // Aborts if the parsing failed.
  6150. if (value_str == nullptr) return false;
  6151. // Sets *value to the value of the flag.
  6152. return ParseInt32(Message() << "The value of flag --" << flag,
  6153. value_str, value);
  6154. }
  6155. // Parses a string for a string flag, in the form of
  6156. // "--flag=value".
  6157. //
  6158. // On success, stores the value of the flag in *value, and returns
  6159. // true. On failure, returns false without changing *value.
  6160. template <typename String>
  6161. static bool ParseStringFlag(const char* str, const char* flag, String* value) {
  6162. // Gets the value of the flag as a string.
  6163. const char* const value_str = ParseFlagValue(str, flag, false);
  6164. // Aborts if the parsing failed.
  6165. if (value_str == nullptr) return false;
  6166. // Sets *value to the value of the flag.
  6167. *value = value_str;
  6168. return true;
  6169. }
  6170. // Determines whether a string has a prefix that Google Test uses for its
  6171. // flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.
  6172. // If Google Test detects that a command line flag has its prefix but is not
  6173. // recognized, it will print its help message. Flags starting with
  6174. // GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
  6175. // internal flags and do not trigger the help message.
  6176. static bool HasGoogleTestFlagPrefix(const char* str) {
  6177. return (SkipPrefix("--", &str) ||
  6178. SkipPrefix("-", &str) ||
  6179. SkipPrefix("/", &str)) &&
  6180. !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
  6181. (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
  6182. SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str));
  6183. }
  6184. // Prints a string containing code-encoded text. The following escape
  6185. // sequences can be used in the string to control the text color:
  6186. //
  6187. // @@ prints a single '@' character.
  6188. // @R changes the color to red.
  6189. // @G changes the color to green.
  6190. // @Y changes the color to yellow.
  6191. // @D changes to the default terminal text color.
  6192. //
  6193. static void PrintColorEncoded(const char* str) {
  6194. GTestColor color = COLOR_DEFAULT; // The current color.
  6195. // Conceptually, we split the string into segments divided by escape
  6196. // sequences. Then we print one segment at a time. At the end of
  6197. // each iteration, the str pointer advances to the beginning of the
  6198. // next segment.
  6199. for (;;) {
  6200. const char* p = strchr(str, '@');
  6201. if (p == nullptr) {
  6202. ColoredPrintf(color, "%s", str);
  6203. return;
  6204. }
  6205. ColoredPrintf(color, "%s", std::string(str, p).c_str());
  6206. const char ch = p[1];
  6207. str = p + 2;
  6208. if (ch == '@') {
  6209. ColoredPrintf(color, "@");
  6210. } else if (ch == 'D') {
  6211. color = COLOR_DEFAULT;
  6212. } else if (ch == 'R') {
  6213. color = COLOR_RED;
  6214. } else if (ch == 'G') {
  6215. color = COLOR_GREEN;
  6216. } else if (ch == 'Y') {
  6217. color = COLOR_YELLOW;
  6218. } else {
  6219. --str;
  6220. }
  6221. }
  6222. }
  6223. static const char kColorEncodedHelpMessage[] =
  6224. "This program contains tests written using " GTEST_NAME_ ". You can use the\n"
  6225. "following command line flags to control its behavior:\n"
  6226. "\n"
  6227. "Test Selection:\n"
  6228. " @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n"
  6229. " List the names of all tests instead of running them. The name of\n"
  6230. " TEST(Foo, Bar) is \"Foo.Bar\".\n"
  6231. " @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS"
  6232. "[@G-@YNEGATIVE_PATTERNS]@D\n"
  6233. " Run only the tests whose name matches one of the positive patterns but\n"
  6234. " none of the negative patterns. '?' matches any single character; '*'\n"
  6235. " matches any substring; ':' separates two patterns.\n"
  6236. " @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n"
  6237. " Run all disabled tests too.\n"
  6238. "\n"
  6239. "Test Execution:\n"
  6240. " @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n"
  6241. " Run the tests repeatedly; use a negative count to repeat forever.\n"
  6242. " @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n"
  6243. " Randomize tests' orders on every iteration.\n"
  6244. " @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n"
  6245. " Random number seed to use for shuffling test orders (between 1 and\n"
  6246. " 99999, or 0 to use a seed based on the current time).\n"
  6247. "\n"
  6248. "Test Output:\n"
  6249. " @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
  6250. " Enable/disable colored output. The default is @Gauto@D.\n"
  6251. " -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n"
  6252. " Don't print the elapsed time of each test.\n"
  6253. " @G--" GTEST_FLAG_PREFIX_ "output=@Y(@Gjson@Y|@Gxml@Y)[@G:@YDIRECTORY_PATH@G"
  6254. GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n"
  6255. " Generate a JSON or XML report in the given directory or with the given\n"
  6256. " file name. @YFILE_PATH@D defaults to @Gtest_detail.xml@D.\n"
  6257. # if GTEST_CAN_STREAM_RESULTS_
  6258. " @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n"
  6259. " Stream test results to the given server.\n"
  6260. # endif // GTEST_CAN_STREAM_RESULTS_
  6261. "\n"
  6262. "Assertion Behavior:\n"
  6263. # if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
  6264. " @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
  6265. " Set the default death test style.\n"
  6266. # endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
  6267. " @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n"
  6268. " Turn assertion failures into debugger break-points.\n"
  6269. " @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n"
  6270. " Turn assertion failures into C++ exceptions for use by an external\n"
  6271. " test framework.\n"
  6272. " @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n"
  6273. " Do not report exceptions as test failures. Instead, allow them\n"
  6274. " to crash the program or throw a pop-up (on Windows).\n"
  6275. "\n"
  6276. "Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set "
  6277. "the corresponding\n"
  6278. "environment variable of a flag (all letters in upper-case). For example, to\n"
  6279. "disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_
  6280. "color=no@D or set\n"
  6281. "the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n"
  6282. "\n"
  6283. "For more information, please read the " GTEST_NAME_ " documentation at\n"
  6284. "@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n"
  6285. "(not one in your own code or tests), please report it to\n"
  6286. "@G<" GTEST_DEV_EMAIL_ ">@D.\n";
  6287. static bool ParseGoogleTestFlag(const char* const arg) {
  6288. return ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,
  6289. &GTEST_FLAG(also_run_disabled_tests)) ||
  6290. ParseBoolFlag(arg, kBreakOnFailureFlag,
  6291. &GTEST_FLAG(break_on_failure)) ||
  6292. ParseBoolFlag(arg, kCatchExceptionsFlag,
  6293. &GTEST_FLAG(catch_exceptions)) ||
  6294. ParseStringFlag(arg, kColorFlag, &GTEST_FLAG(color)) ||
  6295. ParseStringFlag(arg, kDeathTestStyleFlag,
  6296. &GTEST_FLAG(death_test_style)) ||
  6297. ParseBoolFlag(arg, kDeathTestUseFork,
  6298. &GTEST_FLAG(death_test_use_fork)) ||
  6299. ParseStringFlag(arg, kFilterFlag, &GTEST_FLAG(filter)) ||
  6300. ParseStringFlag(arg, kInternalRunDeathTestFlag,
  6301. &GTEST_FLAG(internal_run_death_test)) ||
  6302. ParseBoolFlag(arg, kListTestsFlag, &GTEST_FLAG(list_tests)) ||
  6303. ParseStringFlag(arg, kOutputFlag, &GTEST_FLAG(output)) ||
  6304. ParseBoolFlag(arg, kPrintTimeFlag, &GTEST_FLAG(print_time)) ||
  6305. ParseBoolFlag(arg, kPrintUTF8Flag, &GTEST_FLAG(print_utf8)) ||
  6306. ParseInt32Flag(arg, kRandomSeedFlag, &GTEST_FLAG(random_seed)) ||
  6307. ParseInt32Flag(arg, kRepeatFlag, &GTEST_FLAG(repeat)) ||
  6308. ParseBoolFlag(arg, kShuffleFlag, &GTEST_FLAG(shuffle)) ||
  6309. ParseInt32Flag(arg, kStackTraceDepthFlag,
  6310. &GTEST_FLAG(stack_trace_depth)) ||
  6311. ParseStringFlag(arg, kStreamResultToFlag,
  6312. &GTEST_FLAG(stream_result_to)) ||
  6313. ParseBoolFlag(arg, kThrowOnFailureFlag,
  6314. &GTEST_FLAG(throw_on_failure));
  6315. }
  6316. #if GTEST_USE_OWN_FLAGFILE_FLAG_
  6317. static void LoadFlagsFromFile(const std::string& path) {
  6318. FILE* flagfile = posix::FOpen(path.c_str(), "r");
  6319. if (!flagfile) {
  6320. GTEST_LOG_(FATAL) << "Unable to open file \"" << GTEST_FLAG(flagfile)
  6321. << "\"";
  6322. }
  6323. std::string contents(ReadEntireFile(flagfile));
  6324. posix::FClose(flagfile);
  6325. std::vector<std::string> lines;
  6326. SplitString(contents, '\n', &lines);
  6327. for (size_t i = 0; i < lines.size(); ++i) {
  6328. if (lines[i].empty())
  6329. continue;
  6330. if (!ParseGoogleTestFlag(lines[i].c_str()))
  6331. g_help_flag = true;
  6332. }
  6333. }
  6334. #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
  6335. // Parses the command line for Google Test flags, without initializing
  6336. // other parts of Google Test. The type parameter CharType can be
  6337. // instantiated to either char or wchar_t.
  6338. template <typename CharType>
  6339. void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
  6340. for (int i = 1; i < *argc; i++) {
  6341. const std::string arg_string = StreamableToString(argv[i]);
  6342. const char* const arg = arg_string.c_str();
  6343. using internal::ParseBoolFlag;
  6344. using internal::ParseInt32Flag;
  6345. using internal::ParseStringFlag;
  6346. bool remove_flag = false;
  6347. if (ParseGoogleTestFlag(arg)) {
  6348. remove_flag = true;
  6349. #if GTEST_USE_OWN_FLAGFILE_FLAG_
  6350. } else if (ParseStringFlag(arg, kFlagfileFlag, &GTEST_FLAG(flagfile))) {
  6351. LoadFlagsFromFile(GTEST_FLAG(flagfile));
  6352. remove_flag = true;
  6353. #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
  6354. } else if (arg_string == "--help" || arg_string == "-h" ||
  6355. arg_string == "-?" || arg_string == "/?" ||
  6356. HasGoogleTestFlagPrefix(arg)) {
  6357. // Both help flag and unrecognized Google Test flags (excluding
  6358. // internal ones) trigger help display.
  6359. g_help_flag = true;
  6360. }
  6361. if (remove_flag) {
  6362. // Shift the remainder of the argv list left by one. Note
  6363. // that argv has (*argc + 1) elements, the last one always being
  6364. // NULL. The following loop moves the trailing NULL element as
  6365. // well.
  6366. for (int j = i; j != *argc; j++) {
  6367. argv[j] = argv[j + 1];
  6368. }
  6369. // Decrements the argument count.
  6370. (*argc)--;
  6371. // We also need to decrement the iterator as we just removed
  6372. // an element.
  6373. i--;
  6374. }
  6375. }
  6376. if (g_help_flag) {
  6377. // We print the help here instead of in RUN_ALL_TESTS(), as the
  6378. // latter may not be called at all if the user is using Google
  6379. // Test with another testing framework.
  6380. PrintColorEncoded(kColorEncodedHelpMessage);
  6381. }
  6382. }
  6383. // Parses the command line for Google Test flags, without initializing
  6384. // other parts of Google Test.
  6385. void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
  6386. ParseGoogleTestFlagsOnlyImpl(argc, argv);
  6387. // Fix the value of *_NSGetArgc() on macOS, but iff
  6388. // *_NSGetArgv() == argv
  6389. // Only applicable to char** version of argv
  6390. #if GTEST_OS_MAC
  6391. #ifndef GTEST_OS_IOS
  6392. if (*_NSGetArgv() == argv) {
  6393. *_NSGetArgc() = *argc;
  6394. }
  6395. #endif
  6396. #endif
  6397. }
  6398. void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {
  6399. ParseGoogleTestFlagsOnlyImpl(argc, argv);
  6400. }
  6401. // The internal implementation of InitGoogleTest().
  6402. //
  6403. // The type parameter CharType can be instantiated to either char or
  6404. // wchar_t.
  6405. template <typename CharType>
  6406. void InitGoogleTestImpl(int* argc, CharType** argv) {
  6407. // We don't want to run the initialization code twice.
  6408. if (GTestIsInitialized()) return;
  6409. if (*argc <= 0) return;
  6410. g_argvs.clear();
  6411. for (int i = 0; i != *argc; i++) {
  6412. g_argvs.push_back(StreamableToString(argv[i]));
  6413. }
  6414. #if GTEST_HAS_ABSL
  6415. absl::InitializeSymbolizer(g_argvs[0].c_str());
  6416. #endif // GTEST_HAS_ABSL
  6417. ParseGoogleTestFlagsOnly(argc, argv);
  6418. GetUnitTestImpl()->PostFlagParsingInit();
  6419. }
  6420. } // namespace internal
  6421. // Initializes Google Test. This must be called before calling
  6422. // RUN_ALL_TESTS(). In particular, it parses a command line for the
  6423. // flags that Google Test recognizes. Whenever a Google Test flag is
  6424. // seen, it is removed from argv, and *argc is decremented.
  6425. //
  6426. // No value is returned. Instead, the Google Test flag variables are
  6427. // updated.
  6428. //
  6429. // Calling the function for the second time has no user-visible effect.
  6430. void InitGoogleTest(int* argc, char** argv) {
  6431. #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
  6432. GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
  6433. #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
  6434. internal::InitGoogleTestImpl(argc, argv);
  6435. #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
  6436. }
  6437. // This overloaded version can be used in Windows programs compiled in
  6438. // UNICODE mode.
  6439. void InitGoogleTest(int* argc, wchar_t** argv) {
  6440. #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
  6441. GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
  6442. #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
  6443. internal::InitGoogleTestImpl(argc, argv);
  6444. #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
  6445. }
  6446. std::string TempDir() {
  6447. #if defined(GTEST_CUSTOM_TEMPDIR_FUNCTION_)
  6448. return GTEST_CUSTOM_TEMPDIR_FUNCTION_();
  6449. #endif
  6450. #if GTEST_OS_WINDOWS_MOBILE
  6451. return "\\temp\\";
  6452. #elif GTEST_OS_WINDOWS
  6453. const char* temp_dir = internal::posix::GetEnv("TEMP");
  6454. if (temp_dir == nullptr || temp_dir[0] == '\0')
  6455. return "\\temp\\";
  6456. else if (temp_dir[strlen(temp_dir) - 1] == '\\')
  6457. return temp_dir;
  6458. else
  6459. return std::string(temp_dir) + "\\";
  6460. #elif GTEST_OS_LINUX_ANDROID
  6461. return "/sdcard/";
  6462. #else
  6463. return "/tmp/";
  6464. #endif // GTEST_OS_WINDOWS_MOBILE
  6465. }
  6466. // Class ScopedTrace
  6467. // Pushes the given source file location and message onto a per-thread
  6468. // trace stack maintained by Google Test.
  6469. void ScopedTrace::PushTrace(const char* file, int line, std::string message) {
  6470. internal::TraceInfo trace;
  6471. trace.file = file;
  6472. trace.line = line;
  6473. trace.message.swap(message);
  6474. UnitTest::GetInstance()->PushGTestTrace(trace);
  6475. }
  6476. // Pops the info pushed by the c'tor.
  6477. ScopedTrace::~ScopedTrace()
  6478. GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
  6479. UnitTest::GetInstance()->PopGTestTrace();
  6480. }
  6481. } // namespace testing
  6482. // Copyright 2005, Google Inc.
  6483. // All rights reserved.
  6484. //
  6485. // Redistribution and use in source and binary forms, with or without
  6486. // modification, are permitted provided that the following conditions are
  6487. // met:
  6488. //
  6489. // * Redistributions of source code must retain the above copyright
  6490. // notice, this list of conditions and the following disclaimer.
  6491. // * Redistributions in binary form must reproduce the above
  6492. // copyright notice, this list of conditions and the following disclaimer
  6493. // in the documentation and/or other materials provided with the
  6494. // distribution.
  6495. // * Neither the name of Google Inc. nor the names of its
  6496. // contributors may be used to endorse or promote products derived from
  6497. // this software without specific prior written permission.
  6498. //
  6499. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  6500. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  6501. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  6502. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  6503. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  6504. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  6505. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  6506. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  6507. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  6508. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  6509. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  6510. //
  6511. // This file implements death tests.
  6512. #include <utility>
  6513. #if GTEST_HAS_DEATH_TEST
  6514. # if GTEST_OS_MAC
  6515. # include <crt_externs.h>
  6516. # endif // GTEST_OS_MAC
  6517. # include <errno.h>
  6518. # include <fcntl.h>
  6519. # include <limits.h>
  6520. # if GTEST_OS_LINUX
  6521. # include <signal.h>
  6522. # endif // GTEST_OS_LINUX
  6523. # include <stdarg.h>
  6524. # if GTEST_OS_WINDOWS
  6525. # include <windows.h>
  6526. # else
  6527. # include <sys/mman.h>
  6528. # include <sys/wait.h>
  6529. # endif // GTEST_OS_WINDOWS
  6530. # if GTEST_OS_QNX
  6531. # include <spawn.h>
  6532. # endif // GTEST_OS_QNX
  6533. # if GTEST_OS_FUCHSIA
  6534. # include <lib/fdio/io.h>
  6535. # include <lib/fdio/spawn.h>
  6536. # include <lib/fdio/util.h>
  6537. # include <lib/zx/socket.h>
  6538. # include <lib/zx/port.h>
  6539. # include <lib/zx/process.h>
  6540. # include <zircon/processargs.h>
  6541. # include <zircon/syscalls.h>
  6542. # include <zircon/syscalls/policy.h>
  6543. # include <zircon/syscalls/port.h>
  6544. # endif // GTEST_OS_FUCHSIA
  6545. #endif // GTEST_HAS_DEATH_TEST
  6546. namespace testing {
  6547. // Constants.
  6548. // The default death test style.
  6549. //
  6550. // This is defined in internal/gtest-port.h as "fast", but can be overridden by
  6551. // a definition in internal/custom/gtest-port.h. The recommended value, which is
  6552. // used internally at Google, is "threadsafe".
  6553. static const char kDefaultDeathTestStyle[] = GTEST_DEFAULT_DEATH_TEST_STYLE;
  6554. GTEST_DEFINE_string_(
  6555. death_test_style,
  6556. internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle),
  6557. "Indicates how to run a death test in a forked child process: "
  6558. "\"threadsafe\" (child process re-executes the test binary "
  6559. "from the beginning, running only the specific death test) or "
  6560. "\"fast\" (child process runs the death test immediately "
  6561. "after forking).");
  6562. GTEST_DEFINE_bool_(
  6563. death_test_use_fork,
  6564. internal::BoolFromGTestEnv("death_test_use_fork", false),
  6565. "Instructs to use fork()/_exit() instead of clone() in death tests. "
  6566. "Ignored and always uses fork() on POSIX systems where clone() is not "
  6567. "implemented. Useful when running under valgrind or similar tools if "
  6568. "those do not support clone(). Valgrind 3.3.1 will just fail if "
  6569. "it sees an unsupported combination of clone() flags. "
  6570. "It is not recommended to use this flag w/o valgrind though it will "
  6571. "work in 99% of the cases. Once valgrind is fixed, this flag will "
  6572. "most likely be removed.");
  6573. namespace internal {
  6574. GTEST_DEFINE_string_(
  6575. internal_run_death_test, "",
  6576. "Indicates the file, line number, temporal index of "
  6577. "the single death test to run, and a file descriptor to "
  6578. "which a success code may be sent, all separated by "
  6579. "the '|' characters. This flag is specified if and only if the current "
  6580. "process is a sub-process launched for running a thread-safe "
  6581. "death test. FOR INTERNAL USE ONLY.");
  6582. } // namespace internal
  6583. #if GTEST_HAS_DEATH_TEST
  6584. namespace internal {
  6585. // Valid only for fast death tests. Indicates the code is running in the
  6586. // child process of a fast style death test.
  6587. # if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
  6588. static bool g_in_fast_death_test_child = false;
  6589. # endif
  6590. // Returns a Boolean value indicating whether the caller is currently
  6591. // executing in the context of the death test child process. Tools such as
  6592. // Valgrind heap checkers may need this to modify their behavior in death
  6593. // tests. IMPORTANT: This is an internal utility. Using it may break the
  6594. // implementation of death tests. User code MUST NOT use it.
  6595. bool InDeathTestChild() {
  6596. # if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
  6597. // On Windows and Fuchsia, death tests are thread-safe regardless of the value
  6598. // of the death_test_style flag.
  6599. return !GTEST_FLAG(internal_run_death_test).empty();
  6600. # else
  6601. if (GTEST_FLAG(death_test_style) == "threadsafe")
  6602. return !GTEST_FLAG(internal_run_death_test).empty();
  6603. else
  6604. return g_in_fast_death_test_child;
  6605. #endif
  6606. }
  6607. } // namespace internal
  6608. // ExitedWithCode constructor.
  6609. ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {
  6610. }
  6611. // ExitedWithCode function-call operator.
  6612. bool ExitedWithCode::operator()(int exit_status) const {
  6613. # if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
  6614. return exit_status == exit_code_;
  6615. # else
  6616. return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;
  6617. # endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
  6618. }
  6619. # if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
  6620. // KilledBySignal constructor.
  6621. KilledBySignal::KilledBySignal(int signum) : signum_(signum) {
  6622. }
  6623. // KilledBySignal function-call operator.
  6624. bool KilledBySignal::operator()(int exit_status) const {
  6625. # if defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)
  6626. {
  6627. bool result;
  6628. if (GTEST_KILLED_BY_SIGNAL_OVERRIDE_(signum_, exit_status, &result)) {
  6629. return result;
  6630. }
  6631. }
  6632. # endif // defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)
  6633. return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;
  6634. }
  6635. # endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
  6636. namespace internal {
  6637. // Utilities needed for death tests.
  6638. // Generates a textual description of a given exit code, in the format
  6639. // specified by wait(2).
  6640. static std::string ExitSummary(int exit_code) {
  6641. Message m;
  6642. # if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
  6643. m << "Exited with exit status " << exit_code;
  6644. # else
  6645. if (WIFEXITED(exit_code)) {
  6646. m << "Exited with exit status " << WEXITSTATUS(exit_code);
  6647. } else if (WIFSIGNALED(exit_code)) {
  6648. m << "Terminated by signal " << WTERMSIG(exit_code);
  6649. }
  6650. # ifdef WCOREDUMP
  6651. if (WCOREDUMP(exit_code)) {
  6652. m << " (core dumped)";
  6653. }
  6654. # endif
  6655. # endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
  6656. return m.GetString();
  6657. }
  6658. // Returns true if exit_status describes a process that was terminated
  6659. // by a signal, or exited normally with a nonzero exit code.
  6660. bool ExitedUnsuccessfully(int exit_status) {
  6661. return !ExitedWithCode(0)(exit_status);
  6662. }
  6663. # if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
  6664. // Generates a textual failure message when a death test finds more than
  6665. // one thread running, or cannot determine the number of threads, prior
  6666. // to executing the given statement. It is the responsibility of the
  6667. // caller not to pass a thread_count of 1.
  6668. static std::string DeathTestThreadWarning(size_t thread_count) {
  6669. Message msg;
  6670. msg << "Death tests use fork(), which is unsafe particularly"
  6671. << " in a threaded context. For this test, " << GTEST_NAME_ << " ";
  6672. if (thread_count == 0) {
  6673. msg << "couldn't detect the number of threads.";
  6674. } else {
  6675. msg << "detected " << thread_count << " threads.";
  6676. }
  6677. msg << " See "
  6678. "https://github.com/google/googletest/blob/master/googletest/docs/"
  6679. "advanced.md#death-tests-and-threads"
  6680. << " for more explanation and suggested solutions, especially if"
  6681. << " this is the last message you see before your test times out.";
  6682. return msg.GetString();
  6683. }
  6684. # endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
  6685. // Flag characters for reporting a death test that did not die.
  6686. static const char kDeathTestLived = 'L';
  6687. static const char kDeathTestReturned = 'R';
  6688. static const char kDeathTestThrew = 'T';
  6689. static const char kDeathTestInternalError = 'I';
  6690. #if GTEST_OS_FUCHSIA
  6691. // File descriptor used for the pipe in the child process.
  6692. static const int kFuchsiaReadPipeFd = 3;
  6693. #endif
  6694. // An enumeration describing all of the possible ways that a death test can
  6695. // conclude. DIED means that the process died while executing the test
  6696. // code; LIVED means that process lived beyond the end of the test code;
  6697. // RETURNED means that the test statement attempted to execute a return
  6698. // statement, which is not allowed; THREW means that the test statement
  6699. // returned control by throwing an exception. IN_PROGRESS means the test
  6700. // has not yet concluded.
  6701. enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW };
  6702. // Routine for aborting the program which is safe to call from an
  6703. // exec-style death test child process, in which case the error
  6704. // message is propagated back to the parent process. Otherwise, the
  6705. // message is simply printed to stderr. In either case, the program
  6706. // then exits with status 1.
  6707. static void DeathTestAbort(const std::string& message) {
  6708. // On a POSIX system, this function may be called from a threadsafe-style
  6709. // death test child process, which operates on a very small stack. Use
  6710. // the heap for any additional non-minuscule memory requirements.
  6711. const InternalRunDeathTestFlag* const flag =
  6712. GetUnitTestImpl()->internal_run_death_test_flag();
  6713. if (flag != nullptr) {
  6714. FILE* parent = posix::FDOpen(flag->write_fd(), "w");
  6715. fputc(kDeathTestInternalError, parent);
  6716. fprintf(parent, "%s", message.c_str());
  6717. fflush(parent);
  6718. _exit(1);
  6719. } else {
  6720. fprintf(stderr, "%s", message.c_str());
  6721. fflush(stderr);
  6722. posix::Abort();
  6723. }
  6724. }
  6725. // A replacement for CHECK that calls DeathTestAbort if the assertion
  6726. // fails.
  6727. # define GTEST_DEATH_TEST_CHECK_(expression) \
  6728. do { \
  6729. if (!::testing::internal::IsTrue(expression)) { \
  6730. DeathTestAbort( \
  6731. ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
  6732. + ::testing::internal::StreamableToString(__LINE__) + ": " \
  6733. + #expression); \
  6734. } \
  6735. } while (::testing::internal::AlwaysFalse())
  6736. // This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for
  6737. // evaluating any system call that fulfills two conditions: it must return
  6738. // -1 on failure, and set errno to EINTR when it is interrupted and
  6739. // should be tried again. The macro expands to a loop that repeatedly
  6740. // evaluates the expression as long as it evaluates to -1 and sets
  6741. // errno to EINTR. If the expression evaluates to -1 but errno is
  6742. // something other than EINTR, DeathTestAbort is called.
  6743. # define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
  6744. do { \
  6745. int gtest_retval; \
  6746. do { \
  6747. gtest_retval = (expression); \
  6748. } while (gtest_retval == -1 && errno == EINTR); \
  6749. if (gtest_retval == -1) { \
  6750. DeathTestAbort( \
  6751. ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
  6752. + ::testing::internal::StreamableToString(__LINE__) + ": " \
  6753. + #expression + " != -1"); \
  6754. } \
  6755. } while (::testing::internal::AlwaysFalse())
  6756. // Returns the message describing the last system error in errno.
  6757. std::string GetLastErrnoDescription() {
  6758. return errno == 0 ? "" : posix::StrError(errno);
  6759. }
  6760. // This is called from a death test parent process to read a failure
  6761. // message from the death test child process and log it with the FATAL
  6762. // severity. On Windows, the message is read from a pipe handle. On other
  6763. // platforms, it is read from a file descriptor.
  6764. static void FailFromInternalError(int fd) {
  6765. Message error;
  6766. char buffer[256];
  6767. int num_read;
  6768. do {
  6769. while ((num_read = posix::Read(fd, buffer, 255)) > 0) {
  6770. buffer[num_read] = '\0';
  6771. error << buffer;
  6772. }
  6773. } while (num_read == -1 && errno == EINTR);
  6774. if (num_read == 0) {
  6775. GTEST_LOG_(FATAL) << error.GetString();
  6776. } else {
  6777. const int last_error = errno;
  6778. GTEST_LOG_(FATAL) << "Error while reading death test internal: "
  6779. << GetLastErrnoDescription() << " [" << last_error << "]";
  6780. }
  6781. }
  6782. // Death test constructor. Increments the running death test count
  6783. // for the current test.
  6784. DeathTest::DeathTest() {
  6785. TestInfo* const info = GetUnitTestImpl()->current_test_info();
  6786. if (info == nullptr) {
  6787. DeathTestAbort("Cannot run a death test outside of a TEST or "
  6788. "TEST_F construct");
  6789. }
  6790. }
  6791. // Creates and returns a death test by dispatching to the current
  6792. // death test factory.
  6793. bool DeathTest::Create(const char* statement,
  6794. Matcher<const std::string&> matcher, const char* file,
  6795. int line, DeathTest** test) {
  6796. return GetUnitTestImpl()->death_test_factory()->Create(
  6797. statement, std::move(matcher), file, line, test);
  6798. }
  6799. const char* DeathTest::LastMessage() {
  6800. return last_death_test_message_.c_str();
  6801. }
  6802. void DeathTest::set_last_death_test_message(const std::string& message) {
  6803. last_death_test_message_ = message;
  6804. }
  6805. std::string DeathTest::last_death_test_message_;
  6806. // Provides cross platform implementation for some death functionality.
  6807. class DeathTestImpl : public DeathTest {
  6808. protected:
  6809. DeathTestImpl(const char* a_statement, Matcher<const std::string&> matcher)
  6810. : statement_(a_statement),
  6811. matcher_(std::move(matcher)),
  6812. spawned_(false),
  6813. status_(-1),
  6814. outcome_(IN_PROGRESS),
  6815. read_fd_(-1),
  6816. write_fd_(-1) {}
  6817. // read_fd_ is expected to be closed and cleared by a derived class.
  6818. ~DeathTestImpl() override { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); }
  6819. void Abort(AbortReason reason) override;
  6820. bool Passed(bool status_ok) override;
  6821. const char* statement() const { return statement_; }
  6822. bool spawned() const { return spawned_; }
  6823. void set_spawned(bool is_spawned) { spawned_ = is_spawned; }
  6824. int status() const { return status_; }
  6825. void set_status(int a_status) { status_ = a_status; }
  6826. DeathTestOutcome outcome() const { return outcome_; }
  6827. void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; }
  6828. int read_fd() const { return read_fd_; }
  6829. void set_read_fd(int fd) { read_fd_ = fd; }
  6830. int write_fd() const { return write_fd_; }
  6831. void set_write_fd(int fd) { write_fd_ = fd; }
  6832. // Called in the parent process only. Reads the result code of the death
  6833. // test child process via a pipe, interprets it to set the outcome_
  6834. // member, and closes read_fd_. Outputs diagnostics and terminates in
  6835. // case of unexpected codes.
  6836. void ReadAndInterpretStatusByte();
  6837. // Returns stderr output from the child process.
  6838. virtual std::string GetErrorLogs();
  6839. private:
  6840. // The textual content of the code this object is testing. This class
  6841. // doesn't own this string and should not attempt to delete it.
  6842. const char* const statement_;
  6843. // A matcher that's expected to match the stderr output by the child process.
  6844. Matcher<const std::string&> matcher_;
  6845. // True if the death test child process has been successfully spawned.
  6846. bool spawned_;
  6847. // The exit status of the child process.
  6848. int status_;
  6849. // How the death test concluded.
  6850. DeathTestOutcome outcome_;
  6851. // Descriptor to the read end of the pipe to the child process. It is
  6852. // always -1 in the child process. The child keeps its write end of the
  6853. // pipe in write_fd_.
  6854. int read_fd_;
  6855. // Descriptor to the child's write end of the pipe to the parent process.
  6856. // It is always -1 in the parent process. The parent keeps its end of the
  6857. // pipe in read_fd_.
  6858. int write_fd_;
  6859. };
  6860. // Called in the parent process only. Reads the result code of the death
  6861. // test child process via a pipe, interprets it to set the outcome_
  6862. // member, and closes read_fd_. Outputs diagnostics and terminates in
  6863. // case of unexpected codes.
  6864. void DeathTestImpl::ReadAndInterpretStatusByte() {
  6865. char flag;
  6866. int bytes_read;
  6867. // The read() here blocks until data is available (signifying the
  6868. // failure of the death test) or until the pipe is closed (signifying
  6869. // its success), so it's okay to call this in the parent before
  6870. // the child process has exited.
  6871. do {
  6872. bytes_read = posix::Read(read_fd(), &flag, 1);
  6873. } while (bytes_read == -1 && errno == EINTR);
  6874. if (bytes_read == 0) {
  6875. set_outcome(DIED);
  6876. } else if (bytes_read == 1) {
  6877. switch (flag) {
  6878. case kDeathTestReturned:
  6879. set_outcome(RETURNED);
  6880. break;
  6881. case kDeathTestThrew:
  6882. set_outcome(THREW);
  6883. break;
  6884. case kDeathTestLived:
  6885. set_outcome(LIVED);
  6886. break;
  6887. case kDeathTestInternalError:
  6888. FailFromInternalError(read_fd()); // Does not return.
  6889. break;
  6890. default:
  6891. GTEST_LOG_(FATAL) << "Death test child process reported "
  6892. << "unexpected status byte ("
  6893. << static_cast<unsigned int>(flag) << ")";
  6894. }
  6895. } else {
  6896. GTEST_LOG_(FATAL) << "Read from death test child process failed: "
  6897. << GetLastErrnoDescription();
  6898. }
  6899. GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd()));
  6900. set_read_fd(-1);
  6901. }
  6902. std::string DeathTestImpl::GetErrorLogs() {
  6903. return GetCapturedStderr();
  6904. }
  6905. // Signals that the death test code which should have exited, didn't.
  6906. // Should be called only in a death test child process.
  6907. // Writes a status byte to the child's status file descriptor, then
  6908. // calls _exit(1).
  6909. void DeathTestImpl::Abort(AbortReason reason) {
  6910. // The parent process considers the death test to be a failure if
  6911. // it finds any data in our pipe. So, here we write a single flag byte
  6912. // to the pipe, then exit.
  6913. const char status_ch =
  6914. reason == TEST_DID_NOT_DIE ? kDeathTestLived :
  6915. reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned;
  6916. GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1));
  6917. // We are leaking the descriptor here because on some platforms (i.e.,
  6918. // when built as Windows DLL), destructors of global objects will still
  6919. // run after calling _exit(). On such systems, write_fd_ will be
  6920. // indirectly closed from the destructor of UnitTestImpl, causing double
  6921. // close if it is also closed here. On debug configurations, double close
  6922. // may assert. As there are no in-process buffers to flush here, we are
  6923. // relying on the OS to close the descriptor after the process terminates
  6924. // when the destructors are not run.
  6925. _exit(1); // Exits w/o any normal exit hooks (we were supposed to crash)
  6926. }
  6927. // Returns an indented copy of stderr output for a death test.
  6928. // This makes distinguishing death test output lines from regular log lines
  6929. // much easier.
  6930. static ::std::string FormatDeathTestOutput(const ::std::string& output) {
  6931. ::std::string ret;
  6932. for (size_t at = 0; ; ) {
  6933. const size_t line_end = output.find('\n', at);
  6934. ret += "[ DEATH ] ";
  6935. if (line_end == ::std::string::npos) {
  6936. ret += output.substr(at);
  6937. break;
  6938. }
  6939. ret += output.substr(at, line_end + 1 - at);
  6940. at = line_end + 1;
  6941. }
  6942. return ret;
  6943. }
  6944. // Assesses the success or failure of a death test, using both private
  6945. // members which have previously been set, and one argument:
  6946. //
  6947. // Private data members:
  6948. // outcome: An enumeration describing how the death test
  6949. // concluded: DIED, LIVED, THREW, or RETURNED. The death test
  6950. // fails in the latter three cases.
  6951. // status: The exit status of the child process. On *nix, it is in the
  6952. // in the format specified by wait(2). On Windows, this is the
  6953. // value supplied to the ExitProcess() API or a numeric code
  6954. // of the exception that terminated the program.
  6955. // matcher_: A matcher that's expected to match the stderr output by the child
  6956. // process.
  6957. //
  6958. // Argument:
  6959. // status_ok: true if exit_status is acceptable in the context of
  6960. // this particular death test, which fails if it is false
  6961. //
  6962. // Returns true iff all of the above conditions are met. Otherwise, the
  6963. // first failing condition, in the order given above, is the one that is
  6964. // reported. Also sets the last death test message string.
  6965. bool DeathTestImpl::Passed(bool status_ok) {
  6966. if (!spawned())
  6967. return false;
  6968. const std::string error_message = GetErrorLogs();
  6969. bool success = false;
  6970. Message buffer;
  6971. buffer << "Death test: " << statement() << "\n";
  6972. switch (outcome()) {
  6973. case LIVED:
  6974. buffer << " Result: failed to die.\n"
  6975. << " Error msg:\n" << FormatDeathTestOutput(error_message);
  6976. break;
  6977. case THREW:
  6978. buffer << " Result: threw an exception.\n"
  6979. << " Error msg:\n" << FormatDeathTestOutput(error_message);
  6980. break;
  6981. case RETURNED:
  6982. buffer << " Result: illegal return in test statement.\n"
  6983. << " Error msg:\n" << FormatDeathTestOutput(error_message);
  6984. break;
  6985. case DIED:
  6986. if (status_ok) {
  6987. if (matcher_.Matches(error_message)) {
  6988. success = true;
  6989. } else {
  6990. std::ostringstream stream;
  6991. matcher_.DescribeTo(&stream);
  6992. buffer << " Result: died but not with expected error.\n"
  6993. << " Expected: " << stream.str() << "\n"
  6994. << "Actual msg:\n"
  6995. << FormatDeathTestOutput(error_message);
  6996. }
  6997. } else {
  6998. buffer << " Result: died but not with expected exit code:\n"
  6999. << " " << ExitSummary(status()) << "\n"
  7000. << "Actual msg:\n" << FormatDeathTestOutput(error_message);
  7001. }
  7002. break;
  7003. case IN_PROGRESS:
  7004. default:
  7005. GTEST_LOG_(FATAL)
  7006. << "DeathTest::Passed somehow called before conclusion of test";
  7007. }
  7008. DeathTest::set_last_death_test_message(buffer.GetString());
  7009. return success;
  7010. }
  7011. # if GTEST_OS_WINDOWS
  7012. // WindowsDeathTest implements death tests on Windows. Due to the
  7013. // specifics of starting new processes on Windows, death tests there are
  7014. // always threadsafe, and Google Test considers the
  7015. // --gtest_death_test_style=fast setting to be equivalent to
  7016. // --gtest_death_test_style=threadsafe there.
  7017. //
  7018. // A few implementation notes: Like the Linux version, the Windows
  7019. // implementation uses pipes for child-to-parent communication. But due to
  7020. // the specifics of pipes on Windows, some extra steps are required:
  7021. //
  7022. // 1. The parent creates a communication pipe and stores handles to both
  7023. // ends of it.
  7024. // 2. The parent starts the child and provides it with the information
  7025. // necessary to acquire the handle to the write end of the pipe.
  7026. // 3. The child acquires the write end of the pipe and signals the parent
  7027. // using a Windows event.
  7028. // 4. Now the parent can release the write end of the pipe on its side. If
  7029. // this is done before step 3, the object's reference count goes down to
  7030. // 0 and it is destroyed, preventing the child from acquiring it. The
  7031. // parent now has to release it, or read operations on the read end of
  7032. // the pipe will not return when the child terminates.
  7033. // 5. The parent reads child's output through the pipe (outcome code and
  7034. // any possible error messages) from the pipe, and its stderr and then
  7035. // determines whether to fail the test.
  7036. //
  7037. // Note: to distinguish Win32 API calls from the local method and function
  7038. // calls, the former are explicitly resolved in the global namespace.
  7039. //
  7040. class WindowsDeathTest : public DeathTestImpl {
  7041. public:
  7042. WindowsDeathTest(const char* a_statement, Matcher<const std::string&> matcher,
  7043. const char* file, int line)
  7044. : DeathTestImpl(a_statement, std::move(matcher)),
  7045. file_(file),
  7046. line_(line) {}
  7047. // All of these virtual functions are inherited from DeathTest.
  7048. virtual int Wait();
  7049. virtual TestRole AssumeRole();
  7050. private:
  7051. // The name of the file in which the death test is located.
  7052. const char* const file_;
  7053. // The line number on which the death test is located.
  7054. const int line_;
  7055. // Handle to the write end of the pipe to the child process.
  7056. AutoHandle write_handle_;
  7057. // Child process handle.
  7058. AutoHandle child_handle_;
  7059. // Event the child process uses to signal the parent that it has
  7060. // acquired the handle to the write end of the pipe. After seeing this
  7061. // event the parent can release its own handles to make sure its
  7062. // ReadFile() calls return when the child terminates.
  7063. AutoHandle event_handle_;
  7064. };
  7065. // Waits for the child in a death test to exit, returning its exit
  7066. // status, or 0 if no child process exists. As a side effect, sets the
  7067. // outcome data member.
  7068. int WindowsDeathTest::Wait() {
  7069. if (!spawned())
  7070. return 0;
  7071. // Wait until the child either signals that it has acquired the write end
  7072. // of the pipe or it dies.
  7073. const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() };
  7074. switch (::WaitForMultipleObjects(2,
  7075. wait_handles,
  7076. FALSE, // Waits for any of the handles.
  7077. INFINITE)) {
  7078. case WAIT_OBJECT_0:
  7079. case WAIT_OBJECT_0 + 1:
  7080. break;
  7081. default:
  7082. GTEST_DEATH_TEST_CHECK_(false); // Should not get here.
  7083. }
  7084. // The child has acquired the write end of the pipe or exited.
  7085. // We release the handle on our side and continue.
  7086. write_handle_.Reset();
  7087. event_handle_.Reset();
  7088. ReadAndInterpretStatusByte();
  7089. // Waits for the child process to exit if it haven't already. This
  7090. // returns immediately if the child has already exited, regardless of
  7091. // whether previous calls to WaitForMultipleObjects synchronized on this
  7092. // handle or not.
  7093. GTEST_DEATH_TEST_CHECK_(
  7094. WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(),
  7095. INFINITE));
  7096. DWORD status_code;
  7097. GTEST_DEATH_TEST_CHECK_(
  7098. ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE);
  7099. child_handle_.Reset();
  7100. set_status(static_cast<int>(status_code));
  7101. return status();
  7102. }
  7103. // The AssumeRole process for a Windows death test. It creates a child
  7104. // process with the same executable as the current process to run the
  7105. // death test. The child process is given the --gtest_filter and
  7106. // --gtest_internal_run_death_test flags such that it knows to run the
  7107. // current death test only.
  7108. DeathTest::TestRole WindowsDeathTest::AssumeRole() {
  7109. const UnitTestImpl* const impl = GetUnitTestImpl();
  7110. const InternalRunDeathTestFlag* const flag =
  7111. impl->internal_run_death_test_flag();
  7112. const TestInfo* const info = impl->current_test_info();
  7113. const int death_test_index = info->result()->death_test_count();
  7114. if (flag != nullptr) {
  7115. // ParseInternalRunDeathTestFlag() has performed all the necessary
  7116. // processing.
  7117. set_write_fd(flag->write_fd());
  7118. return EXECUTE_TEST;
  7119. }
  7120. // WindowsDeathTest uses an anonymous pipe to communicate results of
  7121. // a death test.
  7122. SECURITY_ATTRIBUTES handles_are_inheritable = {sizeof(SECURITY_ATTRIBUTES),
  7123. nullptr, TRUE};
  7124. HANDLE read_handle, write_handle;
  7125. GTEST_DEATH_TEST_CHECK_(
  7126. ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable,
  7127. 0) // Default buffer size.
  7128. != FALSE);
  7129. set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle),
  7130. O_RDONLY));
  7131. write_handle_.Reset(write_handle);
  7132. event_handle_.Reset(::CreateEvent(
  7133. &handles_are_inheritable,
  7134. TRUE, // The event will automatically reset to non-signaled state.
  7135. FALSE, // The initial state is non-signalled.
  7136. nullptr)); // The even is unnamed.
  7137. GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != nullptr);
  7138. const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ +
  7139. kFilterFlag + "=" + info->test_suite_name() +
  7140. "." + info->name();
  7141. const std::string internal_flag =
  7142. std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag +
  7143. "=" + file_ + "|" + StreamableToString(line_) + "|" +
  7144. StreamableToString(death_test_index) + "|" +
  7145. StreamableToString(static_cast<unsigned int>(::GetCurrentProcessId())) +
  7146. // size_t has the same width as pointers on both 32-bit and 64-bit
  7147. // Windows platforms.
  7148. // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx.
  7149. "|" + StreamableToString(reinterpret_cast<size_t>(write_handle)) +
  7150. "|" + StreamableToString(reinterpret_cast<size_t>(event_handle_.Get()));
  7151. char executable_path[_MAX_PATH + 1]; // NOLINT
  7152. GTEST_DEATH_TEST_CHECK_(_MAX_PATH + 1 != ::GetModuleFileNameA(nullptr,
  7153. executable_path,
  7154. _MAX_PATH));
  7155. std::string command_line =
  7156. std::string(::GetCommandLineA()) + " " + filter_flag + " \"" +
  7157. internal_flag + "\"";
  7158. DeathTest::set_last_death_test_message("");
  7159. CaptureStderr();
  7160. // Flush the log buffers since the log streams are shared with the child.
  7161. FlushInfoLog();
  7162. // The child process will share the standard handles with the parent.
  7163. STARTUPINFOA startup_info;
  7164. memset(&startup_info, 0, sizeof(STARTUPINFO));
  7165. startup_info.dwFlags = STARTF_USESTDHANDLES;
  7166. startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE);
  7167. startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE);
  7168. startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE);
  7169. PROCESS_INFORMATION process_info;
  7170. GTEST_DEATH_TEST_CHECK_(
  7171. ::CreateProcessA(
  7172. executable_path, const_cast<char*>(command_line.c_str()),
  7173. nullptr, // Retuned process handle is not inheritable.
  7174. nullptr, // Retuned thread handle is not inheritable.
  7175. TRUE, // Child inherits all inheritable handles (for write_handle_).
  7176. 0x0, // Default creation flags.
  7177. nullptr, // Inherit the parent's environment.
  7178. UnitTest::GetInstance()->original_working_dir(), &startup_info,
  7179. &process_info) != FALSE);
  7180. child_handle_.Reset(process_info.hProcess);
  7181. ::CloseHandle(process_info.hThread);
  7182. set_spawned(true);
  7183. return OVERSEE_TEST;
  7184. }
  7185. # elif GTEST_OS_FUCHSIA
  7186. class FuchsiaDeathTest : public DeathTestImpl {
  7187. public:
  7188. FuchsiaDeathTest(const char* a_statement, Matcher<const std::string&> matcher,
  7189. const char* file, int line)
  7190. : DeathTestImpl(a_statement, std::move(matcher)),
  7191. file_(file),
  7192. line_(line) {}
  7193. // All of these virtual functions are inherited from DeathTest.
  7194. int Wait() override;
  7195. TestRole AssumeRole() override;
  7196. std::string GetErrorLogs() override;
  7197. private:
  7198. // The name of the file in which the death test is located.
  7199. const char* const file_;
  7200. // The line number on which the death test is located.
  7201. const int line_;
  7202. // The stderr data captured by the child process.
  7203. std::string captured_stderr_;
  7204. zx::process child_process_;
  7205. zx::port port_;
  7206. zx::socket stderr_socket_;
  7207. };
  7208. // Utility class for accumulating command-line arguments.
  7209. class Arguments {
  7210. public:
  7211. Arguments() { args_.push_back(nullptr); }
  7212. ~Arguments() {
  7213. for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
  7214. ++i) {
  7215. free(*i);
  7216. }
  7217. }
  7218. void AddArgument(const char* argument) {
  7219. args_.insert(args_.end() - 1, posix::StrDup(argument));
  7220. }
  7221. template <typename Str>
  7222. void AddArguments(const ::std::vector<Str>& arguments) {
  7223. for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
  7224. i != arguments.end();
  7225. ++i) {
  7226. args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
  7227. }
  7228. }
  7229. char* const* Argv() {
  7230. return &args_[0];
  7231. }
  7232. int size() {
  7233. return args_.size() - 1;
  7234. }
  7235. private:
  7236. std::vector<char*> args_;
  7237. };
  7238. // Waits for the child in a death test to exit, returning its exit
  7239. // status, or 0 if no child process exists. As a side effect, sets the
  7240. // outcome data member.
  7241. int FuchsiaDeathTest::Wait() {
  7242. const int kProcessKey = 0;
  7243. const int kSocketKey = 1;
  7244. if (!spawned())
  7245. return 0;
  7246. // Register to wait for the child process to terminate.
  7247. zx_status_t status_zx;
  7248. status_zx = child_process_.wait_async(
  7249. port_, kProcessKey, ZX_PROCESS_TERMINATED, ZX_WAIT_ASYNC_ONCE);
  7250. GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
  7251. // Register to wait for the socket to be readable or closed.
  7252. status_zx = stderr_socket_.wait_async(
  7253. port_, kSocketKey, ZX_SOCKET_READABLE | ZX_SOCKET_PEER_CLOSED,
  7254. ZX_WAIT_ASYNC_REPEATING);
  7255. GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
  7256. bool process_terminated = false;
  7257. bool socket_closed = false;
  7258. do {
  7259. zx_port_packet_t packet = {};
  7260. status_zx = port_.wait(zx::time::infinite(), &packet);
  7261. GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
  7262. if (packet.key == kProcessKey) {
  7263. if (ZX_PKT_IS_EXCEPTION(packet.type)) {
  7264. // Process encountered an exception. Kill it directly rather than
  7265. // letting other handlers process the event. We will get a second
  7266. // kProcessKey event when the process actually terminates.
  7267. status_zx = child_process_.kill();
  7268. GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
  7269. } else {
  7270. // Process terminated.
  7271. GTEST_DEATH_TEST_CHECK_(ZX_PKT_IS_SIGNAL_ONE(packet.type));
  7272. GTEST_DEATH_TEST_CHECK_(packet.signal.observed & ZX_PROCESS_TERMINATED);
  7273. process_terminated = true;
  7274. }
  7275. } else if (packet.key == kSocketKey) {
  7276. GTEST_DEATH_TEST_CHECK_(ZX_PKT_IS_SIGNAL_REP(packet.type));
  7277. if (packet.signal.observed & ZX_SOCKET_READABLE) {
  7278. // Read data from the socket.
  7279. constexpr size_t kBufferSize = 1024;
  7280. do {
  7281. size_t old_length = captured_stderr_.length();
  7282. size_t bytes_read = 0;
  7283. captured_stderr_.resize(old_length + kBufferSize);
  7284. status_zx = stderr_socket_.read(
  7285. 0, &captured_stderr_.front() + old_length, kBufferSize,
  7286. &bytes_read);
  7287. captured_stderr_.resize(old_length + bytes_read);
  7288. } while (status_zx == ZX_OK);
  7289. if (status_zx == ZX_ERR_PEER_CLOSED) {
  7290. socket_closed = true;
  7291. } else {
  7292. GTEST_DEATH_TEST_CHECK_(status_zx == ZX_ERR_SHOULD_WAIT);
  7293. }
  7294. } else {
  7295. GTEST_DEATH_TEST_CHECK_(packet.signal.observed & ZX_SOCKET_PEER_CLOSED);
  7296. socket_closed = true;
  7297. }
  7298. }
  7299. } while (!process_terminated && !socket_closed);
  7300. ReadAndInterpretStatusByte();
  7301. zx_info_process_t buffer;
  7302. status_zx = child_process_.get_info(
  7303. ZX_INFO_PROCESS, &buffer, sizeof(buffer), nullptr, nullptr);
  7304. GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
  7305. GTEST_DEATH_TEST_CHECK_(buffer.exited);
  7306. set_status(buffer.return_code);
  7307. return status();
  7308. }
  7309. // The AssumeRole process for a Fuchsia death test. It creates a child
  7310. // process with the same executable as the current process to run the
  7311. // death test. The child process is given the --gtest_filter and
  7312. // --gtest_internal_run_death_test flags such that it knows to run the
  7313. // current death test only.
  7314. DeathTest::TestRole FuchsiaDeathTest::AssumeRole() {
  7315. const UnitTestImpl* const impl = GetUnitTestImpl();
  7316. const InternalRunDeathTestFlag* const flag =
  7317. impl->internal_run_death_test_flag();
  7318. const TestInfo* const info = impl->current_test_info();
  7319. const int death_test_index = info->result()->death_test_count();
  7320. if (flag != nullptr) {
  7321. // ParseInternalRunDeathTestFlag() has performed all the necessary
  7322. // processing.
  7323. set_write_fd(kFuchsiaReadPipeFd);
  7324. return EXECUTE_TEST;
  7325. }
  7326. // Flush the log buffers since the log streams are shared with the child.
  7327. FlushInfoLog();
  7328. // Build the child process command line.
  7329. const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ +
  7330. kFilterFlag + "=" + info->test_suite_name() +
  7331. "." + info->name();
  7332. const std::string internal_flag =
  7333. std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "="
  7334. + file_ + "|"
  7335. + StreamableToString(line_) + "|"
  7336. + StreamableToString(death_test_index);
  7337. Arguments args;
  7338. args.AddArguments(GetInjectableArgvs());
  7339. args.AddArgument(filter_flag.c_str());
  7340. args.AddArgument(internal_flag.c_str());
  7341. // Build the pipe for communication with the child.
  7342. zx_status_t status;
  7343. zx_handle_t child_pipe_handle;
  7344. uint32_t type;
  7345. status = fdio_pipe_half(&child_pipe_handle, &type);
  7346. GTEST_DEATH_TEST_CHECK_(status >= 0);
  7347. set_read_fd(status);
  7348. // Set the pipe handle for the child.
  7349. fdio_spawn_action_t spawn_actions[2] = {};
  7350. fdio_spawn_action_t* add_handle_action = &spawn_actions[0];
  7351. add_handle_action->action = FDIO_SPAWN_ACTION_ADD_HANDLE;
  7352. add_handle_action->h.id = PA_HND(type, kFuchsiaReadPipeFd);
  7353. add_handle_action->h.handle = child_pipe_handle;
  7354. // Create a socket pair will be used to receive the child process' stderr.
  7355. zx::socket stderr_producer_socket;
  7356. status =
  7357. zx::socket::create(0, &stderr_producer_socket, &stderr_socket_);
  7358. GTEST_DEATH_TEST_CHECK_(status >= 0);
  7359. int stderr_producer_fd = -1;
  7360. zx_handle_t producer_handle[1] = { stderr_producer_socket.release() };
  7361. uint32_t producer_handle_type[1] = { PA_FDIO_SOCKET };
  7362. status = fdio_create_fd(
  7363. producer_handle, producer_handle_type, 1, &stderr_producer_fd);
  7364. GTEST_DEATH_TEST_CHECK_(status >= 0);
  7365. // Make the stderr socket nonblocking.
  7366. GTEST_DEATH_TEST_CHECK_(fcntl(stderr_producer_fd, F_SETFL, 0) == 0);
  7367. fdio_spawn_action_t* add_stderr_action = &spawn_actions[1];
  7368. add_stderr_action->action = FDIO_SPAWN_ACTION_CLONE_FD;
  7369. add_stderr_action->fd.local_fd = stderr_producer_fd;
  7370. add_stderr_action->fd.target_fd = STDERR_FILENO;
  7371. // Create a child job.
  7372. zx_handle_t child_job = ZX_HANDLE_INVALID;
  7373. status = zx_job_create(zx_job_default(), 0, & child_job);
  7374. GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
  7375. zx_policy_basic_t policy;
  7376. policy.condition = ZX_POL_NEW_ANY;
  7377. policy.policy = ZX_POL_ACTION_ALLOW;
  7378. status = zx_job_set_policy(
  7379. child_job, ZX_JOB_POL_RELATIVE, ZX_JOB_POL_BASIC, &policy, 1);
  7380. GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
  7381. // Create an exception port and attach it to the |child_job|, to allow
  7382. // us to suppress the system default exception handler from firing.
  7383. status = zx::port::create(0, &port_);
  7384. GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
  7385. status = zx_task_bind_exception_port(
  7386. child_job, port_.get(), 0 /* key */, 0 /*options */);
  7387. GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
  7388. // Spawn the child process.
  7389. status = fdio_spawn_etc(
  7390. child_job, FDIO_SPAWN_CLONE_ALL, args.Argv()[0], args.Argv(), nullptr,
  7391. 2, spawn_actions, child_process_.reset_and_get_address(), nullptr);
  7392. GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
  7393. set_spawned(true);
  7394. return OVERSEE_TEST;
  7395. }
  7396. std::string FuchsiaDeathTest::GetErrorLogs() {
  7397. return captured_stderr_;
  7398. }
  7399. #else // We are neither on Windows, nor on Fuchsia.
  7400. // ForkingDeathTest provides implementations for most of the abstract
  7401. // methods of the DeathTest interface. Only the AssumeRole method is
  7402. // left undefined.
  7403. class ForkingDeathTest : public DeathTestImpl {
  7404. public:
  7405. ForkingDeathTest(const char* statement, Matcher<const std::string&> matcher);
  7406. // All of these virtual functions are inherited from DeathTest.
  7407. int Wait() override;
  7408. protected:
  7409. void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; }
  7410. private:
  7411. // PID of child process during death test; 0 in the child process itself.
  7412. pid_t child_pid_;
  7413. };
  7414. // Constructs a ForkingDeathTest.
  7415. ForkingDeathTest::ForkingDeathTest(const char* a_statement,
  7416. Matcher<const std::string&> matcher)
  7417. : DeathTestImpl(a_statement, std::move(matcher)), child_pid_(-1) {}
  7418. // Waits for the child in a death test to exit, returning its exit
  7419. // status, or 0 if no child process exists. As a side effect, sets the
  7420. // outcome data member.
  7421. int ForkingDeathTest::Wait() {
  7422. if (!spawned())
  7423. return 0;
  7424. ReadAndInterpretStatusByte();
  7425. int status_value;
  7426. GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0));
  7427. set_status(status_value);
  7428. return status_value;
  7429. }
  7430. // A concrete death test class that forks, then immediately runs the test
  7431. // in the child process.
  7432. class NoExecDeathTest : public ForkingDeathTest {
  7433. public:
  7434. NoExecDeathTest(const char* a_statement, Matcher<const std::string&> matcher)
  7435. : ForkingDeathTest(a_statement, std::move(matcher)) {}
  7436. TestRole AssumeRole() override;
  7437. };
  7438. // The AssumeRole process for a fork-and-run death test. It implements a
  7439. // straightforward fork, with a simple pipe to transmit the status byte.
  7440. DeathTest::TestRole NoExecDeathTest::AssumeRole() {
  7441. const size_t thread_count = GetThreadCount();
  7442. if (thread_count != 1) {
  7443. GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count);
  7444. }
  7445. int pipe_fd[2];
  7446. GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
  7447. DeathTest::set_last_death_test_message("");
  7448. CaptureStderr();
  7449. // When we fork the process below, the log file buffers are copied, but the
  7450. // file descriptors are shared. We flush all log files here so that closing
  7451. // the file descriptors in the child process doesn't throw off the
  7452. // synchronization between descriptors and buffers in the parent process.
  7453. // This is as close to the fork as possible to avoid a race condition in case
  7454. // there are multiple threads running before the death test, and another
  7455. // thread writes to the log file.
  7456. FlushInfoLog();
  7457. const pid_t child_pid = fork();
  7458. GTEST_DEATH_TEST_CHECK_(child_pid != -1);
  7459. set_child_pid(child_pid);
  7460. if (child_pid == 0) {
  7461. GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0]));
  7462. set_write_fd(pipe_fd[1]);
  7463. // Redirects all logging to stderr in the child process to prevent
  7464. // concurrent writes to the log files. We capture stderr in the parent
  7465. // process and append the child process' output to a log.
  7466. LogToStderr();
  7467. // Event forwarding to the listeners of event listener API mush be shut
  7468. // down in death test subprocesses.
  7469. GetUnitTestImpl()->listeners()->SuppressEventForwarding();
  7470. g_in_fast_death_test_child = true;
  7471. return EXECUTE_TEST;
  7472. } else {
  7473. GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
  7474. set_read_fd(pipe_fd[0]);
  7475. set_spawned(true);
  7476. return OVERSEE_TEST;
  7477. }
  7478. }
  7479. // A concrete death test class that forks and re-executes the main
  7480. // program from the beginning, with command-line flags set that cause
  7481. // only this specific death test to be run.
  7482. class ExecDeathTest : public ForkingDeathTest {
  7483. public:
  7484. ExecDeathTest(const char* a_statement, Matcher<const std::string&> matcher,
  7485. const char* file, int line)
  7486. : ForkingDeathTest(a_statement, std::move(matcher)),
  7487. file_(file),
  7488. line_(line) {}
  7489. TestRole AssumeRole() override;
  7490. private:
  7491. static ::std::vector<std::string> GetArgvsForDeathTestChildProcess() {
  7492. ::std::vector<std::string> args = GetInjectableArgvs();
  7493. # if defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)
  7494. ::std::vector<std::string> extra_args =
  7495. GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_();
  7496. args.insert(args.end(), extra_args.begin(), extra_args.end());
  7497. # endif // defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)
  7498. return args;
  7499. }
  7500. // The name of the file in which the death test is located.
  7501. const char* const file_;
  7502. // The line number on which the death test is located.
  7503. const int line_;
  7504. };
  7505. // Utility class for accumulating command-line arguments.
  7506. class Arguments {
  7507. public:
  7508. Arguments() { args_.push_back(nullptr); }
  7509. ~Arguments() {
  7510. for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
  7511. ++i) {
  7512. free(*i);
  7513. }
  7514. }
  7515. void AddArgument(const char* argument) {
  7516. args_.insert(args_.end() - 1, posix::StrDup(argument));
  7517. }
  7518. template <typename Str>
  7519. void AddArguments(const ::std::vector<Str>& arguments) {
  7520. for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
  7521. i != arguments.end();
  7522. ++i) {
  7523. args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
  7524. }
  7525. }
  7526. char* const* Argv() {
  7527. return &args_[0];
  7528. }
  7529. private:
  7530. std::vector<char*> args_;
  7531. };
  7532. // A struct that encompasses the arguments to the child process of a
  7533. // threadsafe-style death test process.
  7534. struct ExecDeathTestArgs {
  7535. char* const* argv; // Command-line arguments for the child's call to exec
  7536. int close_fd; // File descriptor to close; the read end of a pipe
  7537. };
  7538. # if GTEST_OS_MAC
  7539. inline char** GetEnviron() {
  7540. // When Google Test is built as a framework on MacOS X, the environ variable
  7541. // is unavailable. Apple's documentation (man environ) recommends using
  7542. // _NSGetEnviron() instead.
  7543. return *_NSGetEnviron();
  7544. }
  7545. # else
  7546. // Some POSIX platforms expect you to declare environ. extern "C" makes
  7547. // it reside in the global namespace.
  7548. extern "C" char** environ;
  7549. inline char** GetEnviron() { return environ; }
  7550. # endif // GTEST_OS_MAC
  7551. # if !GTEST_OS_QNX
  7552. // The main function for a threadsafe-style death test child process.
  7553. // This function is called in a clone()-ed process and thus must avoid
  7554. // any potentially unsafe operations like malloc or libc functions.
  7555. static int ExecDeathTestChildMain(void* child_arg) {
  7556. ExecDeathTestArgs* const args = static_cast<ExecDeathTestArgs*>(child_arg);
  7557. GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd));
  7558. // We need to execute the test program in the same environment where
  7559. // it was originally invoked. Therefore we change to the original
  7560. // working directory first.
  7561. const char* const original_dir =
  7562. UnitTest::GetInstance()->original_working_dir();
  7563. // We can safely call chdir() as it's a direct system call.
  7564. if (chdir(original_dir) != 0) {
  7565. DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
  7566. GetLastErrnoDescription());
  7567. return EXIT_FAILURE;
  7568. }
  7569. // We can safely call execve() as it's a direct system call. We
  7570. // cannot use execvp() as it's a libc function and thus potentially
  7571. // unsafe. Since execve() doesn't search the PATH, the user must
  7572. // invoke the test program via a valid path that contains at least
  7573. // one path separator.
  7574. execve(args->argv[0], args->argv, GetEnviron());
  7575. DeathTestAbort(std::string("execve(") + args->argv[0] + ", ...) in " +
  7576. original_dir + " failed: " +
  7577. GetLastErrnoDescription());
  7578. return EXIT_FAILURE;
  7579. }
  7580. # endif // !GTEST_OS_QNX
  7581. # if GTEST_HAS_CLONE
  7582. // Two utility routines that together determine the direction the stack
  7583. // grows.
  7584. // This could be accomplished more elegantly by a single recursive
  7585. // function, but we want to guard against the unlikely possibility of
  7586. // a smart compiler optimizing the recursion away.
  7587. //
  7588. // GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining
  7589. // StackLowerThanAddress into StackGrowsDown, which then doesn't give
  7590. // correct answer.
  7591. static void StackLowerThanAddress(const void* ptr,
  7592. bool* result) GTEST_NO_INLINE_;
  7593. static void StackLowerThanAddress(const void* ptr, bool* result) {
  7594. int dummy;
  7595. *result = (&dummy < ptr);
  7596. }
  7597. // Make sure AddressSanitizer does not tamper with the stack here.
  7598. GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
  7599. static bool StackGrowsDown() {
  7600. int dummy;
  7601. bool result;
  7602. StackLowerThanAddress(&dummy, &result);
  7603. return result;
  7604. }
  7605. # endif // GTEST_HAS_CLONE
  7606. // Spawns a child process with the same executable as the current process in
  7607. // a thread-safe manner and instructs it to run the death test. The
  7608. // implementation uses fork(2) + exec. On systems where clone(2) is
  7609. // available, it is used instead, being slightly more thread-safe. On QNX,
  7610. // fork supports only single-threaded environments, so this function uses
  7611. // spawn(2) there instead. The function dies with an error message if
  7612. // anything goes wrong.
  7613. static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
  7614. ExecDeathTestArgs args = { argv, close_fd };
  7615. pid_t child_pid = -1;
  7616. # if GTEST_OS_QNX
  7617. // Obtains the current directory and sets it to be closed in the child
  7618. // process.
  7619. const int cwd_fd = open(".", O_RDONLY);
  7620. GTEST_DEATH_TEST_CHECK_(cwd_fd != -1);
  7621. GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC));
  7622. // We need to execute the test program in the same environment where
  7623. // it was originally invoked. Therefore we change to the original
  7624. // working directory first.
  7625. const char* const original_dir =
  7626. UnitTest::GetInstance()->original_working_dir();
  7627. // We can safely call chdir() as it's a direct system call.
  7628. if (chdir(original_dir) != 0) {
  7629. DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
  7630. GetLastErrnoDescription());
  7631. return EXIT_FAILURE;
  7632. }
  7633. int fd_flags;
  7634. // Set close_fd to be closed after spawn.
  7635. GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD));
  7636. GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD,
  7637. fd_flags | FD_CLOEXEC));
  7638. struct inheritance inherit = {0};
  7639. // spawn is a system call.
  7640. child_pid =
  7641. spawn(args.argv[0], 0, nullptr, &inherit, args.argv, GetEnviron());
  7642. // Restores the current working directory.
  7643. GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1);
  7644. GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));
  7645. # else // GTEST_OS_QNX
  7646. # if GTEST_OS_LINUX
  7647. // When a SIGPROF signal is received while fork() or clone() are executing,
  7648. // the process may hang. To avoid this, we ignore SIGPROF here and re-enable
  7649. // it after the call to fork()/clone() is complete.
  7650. struct sigaction saved_sigprof_action;
  7651. struct sigaction ignore_sigprof_action;
  7652. memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action));
  7653. sigemptyset(&ignore_sigprof_action.sa_mask);
  7654. ignore_sigprof_action.sa_handler = SIG_IGN;
  7655. GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction(
  7656. SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));
  7657. # endif // GTEST_OS_LINUX
  7658. # if GTEST_HAS_CLONE
  7659. const bool use_fork = GTEST_FLAG(death_test_use_fork);
  7660. if (!use_fork) {
  7661. static const bool stack_grows_down = StackGrowsDown();
  7662. const size_t stack_size = getpagesize();
  7663. // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead.
  7664. void* const stack = mmap(nullptr, stack_size, PROT_READ | PROT_WRITE,
  7665. MAP_ANON | MAP_PRIVATE, -1, 0);
  7666. GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED);
  7667. // Maximum stack alignment in bytes: For a downward-growing stack, this
  7668. // amount is subtracted from size of the stack space to get an address
  7669. // that is within the stack space and is aligned on all systems we care
  7670. // about. As far as I know there is no ABI with stack alignment greater
  7671. // than 64. We assume stack and stack_size already have alignment of
  7672. // kMaxStackAlignment.
  7673. const size_t kMaxStackAlignment = 64;
  7674. void* const stack_top =
  7675. static_cast<char*>(stack) +
  7676. (stack_grows_down ? stack_size - kMaxStackAlignment : 0);
  7677. GTEST_DEATH_TEST_CHECK_(stack_size > kMaxStackAlignment &&
  7678. reinterpret_cast<intptr_t>(stack_top) % kMaxStackAlignment == 0);
  7679. child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args);
  7680. GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);
  7681. }
  7682. # else
  7683. const bool use_fork = true;
  7684. # endif // GTEST_HAS_CLONE
  7685. if (use_fork && (child_pid = fork()) == 0) {
  7686. ExecDeathTestChildMain(&args);
  7687. _exit(0);
  7688. }
  7689. # endif // GTEST_OS_QNX
  7690. # if GTEST_OS_LINUX
  7691. GTEST_DEATH_TEST_CHECK_SYSCALL_(
  7692. sigaction(SIGPROF, &saved_sigprof_action, nullptr));
  7693. # endif // GTEST_OS_LINUX
  7694. GTEST_DEATH_TEST_CHECK_(child_pid != -1);
  7695. return child_pid;
  7696. }
  7697. // The AssumeRole process for a fork-and-exec death test. It re-executes the
  7698. // main program from the beginning, setting the --gtest_filter
  7699. // and --gtest_internal_run_death_test flags to cause only the current
  7700. // death test to be re-run.
  7701. DeathTest::TestRole ExecDeathTest::AssumeRole() {
  7702. const UnitTestImpl* const impl = GetUnitTestImpl();
  7703. const InternalRunDeathTestFlag* const flag =
  7704. impl->internal_run_death_test_flag();
  7705. const TestInfo* const info = impl->current_test_info();
  7706. const int death_test_index = info->result()->death_test_count();
  7707. if (flag != nullptr) {
  7708. set_write_fd(flag->write_fd());
  7709. return EXECUTE_TEST;
  7710. }
  7711. int pipe_fd[2];
  7712. GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
  7713. // Clear the close-on-exec flag on the write end of the pipe, lest
  7714. // it be closed when the child process does an exec:
  7715. GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
  7716. const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ +
  7717. kFilterFlag + "=" + info->test_suite_name() +
  7718. "." + info->name();
  7719. const std::string internal_flag =
  7720. std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "="
  7721. + file_ + "|" + StreamableToString(line_) + "|"
  7722. + StreamableToString(death_test_index) + "|"
  7723. + StreamableToString(pipe_fd[1]);
  7724. Arguments args;
  7725. args.AddArguments(GetArgvsForDeathTestChildProcess());
  7726. args.AddArgument(filter_flag.c_str());
  7727. args.AddArgument(internal_flag.c_str());
  7728. DeathTest::set_last_death_test_message("");
  7729. CaptureStderr();
  7730. // See the comment in NoExecDeathTest::AssumeRole for why the next line
  7731. // is necessary.
  7732. FlushInfoLog();
  7733. const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]);
  7734. GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
  7735. set_child_pid(child_pid);
  7736. set_read_fd(pipe_fd[0]);
  7737. set_spawned(true);
  7738. return OVERSEE_TEST;
  7739. }
  7740. # endif // !GTEST_OS_WINDOWS
  7741. // Creates a concrete DeathTest-derived class that depends on the
  7742. // --gtest_death_test_style flag, and sets the pointer pointed to
  7743. // by the "test" argument to its address. If the test should be
  7744. // skipped, sets that pointer to NULL. Returns true, unless the
  7745. // flag is set to an invalid value.
  7746. bool DefaultDeathTestFactory::Create(const char* statement,
  7747. Matcher<const std::string&> matcher,
  7748. const char* file, int line,
  7749. DeathTest** test) {
  7750. UnitTestImpl* const impl = GetUnitTestImpl();
  7751. const InternalRunDeathTestFlag* const flag =
  7752. impl->internal_run_death_test_flag();
  7753. const int death_test_index = impl->current_test_info()
  7754. ->increment_death_test_count();
  7755. if (flag != nullptr) {
  7756. if (death_test_index > flag->index()) {
  7757. DeathTest::set_last_death_test_message(
  7758. "Death test count (" + StreamableToString(death_test_index)
  7759. + ") somehow exceeded expected maximum ("
  7760. + StreamableToString(flag->index()) + ")");
  7761. return false;
  7762. }
  7763. if (!(flag->file() == file && flag->line() == line &&
  7764. flag->index() == death_test_index)) {
  7765. *test = nullptr;
  7766. return true;
  7767. }
  7768. }
  7769. # if GTEST_OS_WINDOWS
  7770. if (GTEST_FLAG(death_test_style) == "threadsafe" ||
  7771. GTEST_FLAG(death_test_style) == "fast") {
  7772. *test = new WindowsDeathTest(statement, std::move(matcher), file, line);
  7773. }
  7774. # elif GTEST_OS_FUCHSIA
  7775. if (GTEST_FLAG(death_test_style) == "threadsafe" ||
  7776. GTEST_FLAG(death_test_style) == "fast") {
  7777. *test = new FuchsiaDeathTest(statement, std::move(matcher), file, line);
  7778. }
  7779. # else
  7780. if (GTEST_FLAG(death_test_style) == "threadsafe") {
  7781. *test = new ExecDeathTest(statement, std::move(matcher), file, line);
  7782. } else if (GTEST_FLAG(death_test_style) == "fast") {
  7783. *test = new NoExecDeathTest(statement, std::move(matcher));
  7784. }
  7785. # endif // GTEST_OS_WINDOWS
  7786. else { // NOLINT - this is more readable than unbalanced brackets inside #if.
  7787. DeathTest::set_last_death_test_message(
  7788. "Unknown death test style \"" + GTEST_FLAG(death_test_style)
  7789. + "\" encountered");
  7790. return false;
  7791. }
  7792. return true;
  7793. }
  7794. # if GTEST_OS_WINDOWS
  7795. // Recreates the pipe and event handles from the provided parameters,
  7796. // signals the event, and returns a file descriptor wrapped around the pipe
  7797. // handle. This function is called in the child process only.
  7798. static int GetStatusFileDescriptor(unsigned int parent_process_id,
  7799. size_t write_handle_as_size_t,
  7800. size_t event_handle_as_size_t) {
  7801. AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,
  7802. FALSE, // Non-inheritable.
  7803. parent_process_id));
  7804. if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {
  7805. DeathTestAbort("Unable to open parent process " +
  7806. StreamableToString(parent_process_id));
  7807. }
  7808. GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t));
  7809. const HANDLE write_handle =
  7810. reinterpret_cast<HANDLE>(write_handle_as_size_t);
  7811. HANDLE dup_write_handle;
  7812. // The newly initialized handle is accessible only in the parent
  7813. // process. To obtain one accessible within the child, we need to use
  7814. // DuplicateHandle.
  7815. if (!::DuplicateHandle(parent_process_handle.Get(), write_handle,
  7816. ::GetCurrentProcess(), &dup_write_handle,
  7817. 0x0, // Requested privileges ignored since
  7818. // DUPLICATE_SAME_ACCESS is used.
  7819. FALSE, // Request non-inheritable handler.
  7820. DUPLICATE_SAME_ACCESS)) {
  7821. DeathTestAbort("Unable to duplicate the pipe handle " +
  7822. StreamableToString(write_handle_as_size_t) +
  7823. " from the parent process " +
  7824. StreamableToString(parent_process_id));
  7825. }
  7826. const HANDLE event_handle = reinterpret_cast<HANDLE>(event_handle_as_size_t);
  7827. HANDLE dup_event_handle;
  7828. if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,
  7829. ::GetCurrentProcess(), &dup_event_handle,
  7830. 0x0,
  7831. FALSE,
  7832. DUPLICATE_SAME_ACCESS)) {
  7833. DeathTestAbort("Unable to duplicate the event handle " +
  7834. StreamableToString(event_handle_as_size_t) +
  7835. " from the parent process " +
  7836. StreamableToString(parent_process_id));
  7837. }
  7838. const int write_fd =
  7839. ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND);
  7840. if (write_fd == -1) {
  7841. DeathTestAbort("Unable to convert pipe handle " +
  7842. StreamableToString(write_handle_as_size_t) +
  7843. " to a file descriptor");
  7844. }
  7845. // Signals the parent that the write end of the pipe has been acquired
  7846. // so the parent can release its own write end.
  7847. ::SetEvent(dup_event_handle);
  7848. return write_fd;
  7849. }
  7850. # endif // GTEST_OS_WINDOWS
  7851. // Returns a newly created InternalRunDeathTestFlag object with fields
  7852. // initialized from the GTEST_FLAG(internal_run_death_test) flag if
  7853. // the flag is specified; otherwise returns NULL.
  7854. InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
  7855. if (GTEST_FLAG(internal_run_death_test) == "") return nullptr;
  7856. // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we
  7857. // can use it here.
  7858. int line = -1;
  7859. int index = -1;
  7860. ::std::vector< ::std::string> fields;
  7861. SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields);
  7862. int write_fd = -1;
  7863. # if GTEST_OS_WINDOWS
  7864. unsigned int parent_process_id = 0;
  7865. size_t write_handle_as_size_t = 0;
  7866. size_t event_handle_as_size_t = 0;
  7867. if (fields.size() != 6
  7868. || !ParseNaturalNumber(fields[1], &line)
  7869. || !ParseNaturalNumber(fields[2], &index)
  7870. || !ParseNaturalNumber(fields[3], &parent_process_id)
  7871. || !ParseNaturalNumber(fields[4], &write_handle_as_size_t)
  7872. || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
  7873. DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
  7874. GTEST_FLAG(internal_run_death_test));
  7875. }
  7876. write_fd = GetStatusFileDescriptor(parent_process_id,
  7877. write_handle_as_size_t,
  7878. event_handle_as_size_t);
  7879. # elif GTEST_OS_FUCHSIA
  7880. if (fields.size() != 3
  7881. || !ParseNaturalNumber(fields[1], &line)
  7882. || !ParseNaturalNumber(fields[2], &index)) {
  7883. DeathTestAbort("Bad --gtest_internal_run_death_test flag: "
  7884. + GTEST_FLAG(internal_run_death_test));
  7885. }
  7886. # else
  7887. if (fields.size() != 4
  7888. || !ParseNaturalNumber(fields[1], &line)
  7889. || !ParseNaturalNumber(fields[2], &index)
  7890. || !ParseNaturalNumber(fields[3], &write_fd)) {
  7891. DeathTestAbort("Bad --gtest_internal_run_death_test flag: "
  7892. + GTEST_FLAG(internal_run_death_test));
  7893. }
  7894. # endif // GTEST_OS_WINDOWS
  7895. return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);
  7896. }
  7897. } // namespace internal
  7898. #endif // GTEST_HAS_DEATH_TEST
  7899. } // namespace testing
  7900. // Copyright 2008, Google Inc.
  7901. // All rights reserved.
  7902. //
  7903. // Redistribution and use in source and binary forms, with or without
  7904. // modification, are permitted provided that the following conditions are
  7905. // met:
  7906. //
  7907. // * Redistributions of source code must retain the above copyright
  7908. // notice, this list of conditions and the following disclaimer.
  7909. // * Redistributions in binary form must reproduce the above
  7910. // copyright notice, this list of conditions and the following disclaimer
  7911. // in the documentation and/or other materials provided with the
  7912. // distribution.
  7913. // * Neither the name of Google Inc. nor the names of its
  7914. // contributors may be used to endorse or promote products derived from
  7915. // this software without specific prior written permission.
  7916. //
  7917. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  7918. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  7919. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  7920. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7921. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  7922. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  7923. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  7924. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  7925. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  7926. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  7927. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  7928. #include <stdlib.h>
  7929. #if GTEST_OS_WINDOWS_MOBILE
  7930. # include <windows.h>
  7931. #elif GTEST_OS_WINDOWS
  7932. # include <direct.h>
  7933. # include <io.h>
  7934. #else
  7935. # include <limits.h>
  7936. # include <climits> // Some Linux distributions define PATH_MAX here.
  7937. #endif // GTEST_OS_WINDOWS_MOBILE
  7938. #if GTEST_OS_WINDOWS
  7939. # define GTEST_PATH_MAX_ _MAX_PATH
  7940. #elif defined(PATH_MAX)
  7941. # define GTEST_PATH_MAX_ PATH_MAX
  7942. #elif defined(_XOPEN_PATH_MAX)
  7943. # define GTEST_PATH_MAX_ _XOPEN_PATH_MAX
  7944. #else
  7945. # define GTEST_PATH_MAX_ _POSIX_PATH_MAX
  7946. #endif // GTEST_OS_WINDOWS
  7947. namespace testing {
  7948. namespace internal {
  7949. #if GTEST_OS_WINDOWS
  7950. // On Windows, '\\' is the standard path separator, but many tools and the
  7951. // Windows API also accept '/' as an alternate path separator. Unless otherwise
  7952. // noted, a file path can contain either kind of path separators, or a mixture
  7953. // of them.
  7954. const char kPathSeparator = '\\';
  7955. const char kAlternatePathSeparator = '/';
  7956. const char kAlternatePathSeparatorString[] = "/";
  7957. # if GTEST_OS_WINDOWS_MOBILE
  7958. // Windows CE doesn't have a current directory. You should not use
  7959. // the current directory in tests on Windows CE, but this at least
  7960. // provides a reasonable fallback.
  7961. const char kCurrentDirectoryString[] = "\\";
  7962. // Windows CE doesn't define INVALID_FILE_ATTRIBUTES
  7963. const DWORD kInvalidFileAttributes = 0xffffffff;
  7964. # else
  7965. const char kCurrentDirectoryString[] = ".\\";
  7966. # endif // GTEST_OS_WINDOWS_MOBILE
  7967. #else
  7968. const char kPathSeparator = '/';
  7969. const char kCurrentDirectoryString[] = "./";
  7970. #endif // GTEST_OS_WINDOWS
  7971. // Returns whether the given character is a valid path separator.
  7972. static bool IsPathSeparator(char c) {
  7973. #if GTEST_HAS_ALT_PATH_SEP_
  7974. return (c == kPathSeparator) || (c == kAlternatePathSeparator);
  7975. #else
  7976. return c == kPathSeparator;
  7977. #endif
  7978. }
  7979. // Returns the current working directory, or "" if unsuccessful.
  7980. FilePath FilePath::GetCurrentDir() {
  7981. #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT
  7982. // Windows CE doesn't have a current directory, so we just return
  7983. // something reasonable.
  7984. return FilePath(kCurrentDirectoryString);
  7985. #elif GTEST_OS_WINDOWS
  7986. char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
  7987. return FilePath(_getcwd(cwd, sizeof(cwd)) == nullptr ? "" : cwd);
  7988. #else
  7989. char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
  7990. char* result = getcwd(cwd, sizeof(cwd));
  7991. # if GTEST_OS_NACL
  7992. // getcwd will likely fail in NaCl due to the sandbox, so return something
  7993. // reasonable. The user may have provided a shim implementation for getcwd,
  7994. // however, so fallback only when failure is detected.
  7995. return FilePath(result == nullptr ? kCurrentDirectoryString : cwd);
  7996. # endif // GTEST_OS_NACL
  7997. return FilePath(result == nullptr ? "" : cwd);
  7998. #endif // GTEST_OS_WINDOWS_MOBILE
  7999. }
  8000. // Returns a copy of the FilePath with the case-insensitive extension removed.
  8001. // Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
  8002. // FilePath("dir/file"). If a case-insensitive extension is not
  8003. // found, returns a copy of the original FilePath.
  8004. FilePath FilePath::RemoveExtension(const char* extension) const {
  8005. const std::string dot_extension = std::string(".") + extension;
  8006. if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) {
  8007. return FilePath(pathname_.substr(
  8008. 0, pathname_.length() - dot_extension.length()));
  8009. }
  8010. return *this;
  8011. }
  8012. // Returns a pointer to the last occurrence of a valid path separator in
  8013. // the FilePath. On Windows, for example, both '/' and '\' are valid path
  8014. // separators. Returns NULL if no path separator was found.
  8015. const char* FilePath::FindLastPathSeparator() const {
  8016. const char* const last_sep = strrchr(c_str(), kPathSeparator);
  8017. #if GTEST_HAS_ALT_PATH_SEP_
  8018. const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator);
  8019. // Comparing two pointers of which only one is NULL is undefined.
  8020. if (last_alt_sep != nullptr &&
  8021. (last_sep == nullptr || last_alt_sep > last_sep)) {
  8022. return last_alt_sep;
  8023. }
  8024. #endif
  8025. return last_sep;
  8026. }
  8027. // Returns a copy of the FilePath with the directory part removed.
  8028. // Example: FilePath("path/to/file").RemoveDirectoryName() returns
  8029. // FilePath("file"). If there is no directory part ("just_a_file"), it returns
  8030. // the FilePath unmodified. If there is no file part ("just_a_dir/") it
  8031. // returns an empty FilePath ("").
  8032. // On Windows platform, '\' is the path separator, otherwise it is '/'.
  8033. FilePath FilePath::RemoveDirectoryName() const {
  8034. const char* const last_sep = FindLastPathSeparator();
  8035. return last_sep ? FilePath(last_sep + 1) : *this;
  8036. }
  8037. // RemoveFileName returns the directory path with the filename removed.
  8038. // Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
  8039. // If the FilePath is "a_file" or "/a_file", RemoveFileName returns
  8040. // FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
  8041. // not have a file, like "just/a/dir/", it returns the FilePath unmodified.
  8042. // On Windows platform, '\' is the path separator, otherwise it is '/'.
  8043. FilePath FilePath::RemoveFileName() const {
  8044. const char* const last_sep = FindLastPathSeparator();
  8045. std::string dir;
  8046. if (last_sep) {
  8047. dir = std::string(c_str(), last_sep + 1 - c_str());
  8048. } else {
  8049. dir = kCurrentDirectoryString;
  8050. }
  8051. return FilePath(dir);
  8052. }
  8053. // Helper functions for naming files in a directory for xml output.
  8054. // Given directory = "dir", base_name = "test", number = 0,
  8055. // extension = "xml", returns "dir/test.xml". If number is greater
  8056. // than zero (e.g., 12), returns "dir/test_12.xml".
  8057. // On Windows platform, uses \ as the separator rather than /.
  8058. FilePath FilePath::MakeFileName(const FilePath& directory,
  8059. const FilePath& base_name,
  8060. int number,
  8061. const char* extension) {
  8062. std::string file;
  8063. if (number == 0) {
  8064. file = base_name.string() + "." + extension;
  8065. } else {
  8066. file = base_name.string() + "_" + StreamableToString(number)
  8067. + "." + extension;
  8068. }
  8069. return ConcatPaths(directory, FilePath(file));
  8070. }
  8071. // Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml".
  8072. // On Windows, uses \ as the separator rather than /.
  8073. FilePath FilePath::ConcatPaths(const FilePath& directory,
  8074. const FilePath& relative_path) {
  8075. if (directory.IsEmpty())
  8076. return relative_path;
  8077. const FilePath dir(directory.RemoveTrailingPathSeparator());
  8078. return FilePath(dir.string() + kPathSeparator + relative_path.string());
  8079. }
  8080. // Returns true if pathname describes something findable in the file-system,
  8081. // either a file, directory, or whatever.
  8082. bool FilePath::FileOrDirectoryExists() const {
  8083. #if GTEST_OS_WINDOWS_MOBILE
  8084. LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());
  8085. const DWORD attributes = GetFileAttributes(unicode);
  8086. delete [] unicode;
  8087. return attributes != kInvalidFileAttributes;
  8088. #else
  8089. posix::StatStruct file_stat;
  8090. return posix::Stat(pathname_.c_str(), &file_stat) == 0;
  8091. #endif // GTEST_OS_WINDOWS_MOBILE
  8092. }
  8093. // Returns true if pathname describes a directory in the file-system
  8094. // that exists.
  8095. bool FilePath::DirectoryExists() const {
  8096. bool result = false;
  8097. #if GTEST_OS_WINDOWS
  8098. // Don't strip off trailing separator if path is a root directory on
  8099. // Windows (like "C:\\").
  8100. const FilePath& path(IsRootDirectory() ? *this :
  8101. RemoveTrailingPathSeparator());
  8102. #else
  8103. const FilePath& path(*this);
  8104. #endif
  8105. #if GTEST_OS_WINDOWS_MOBILE
  8106. LPCWSTR unicode = String::AnsiToUtf16(path.c_str());
  8107. const DWORD attributes = GetFileAttributes(unicode);
  8108. delete [] unicode;
  8109. if ((attributes != kInvalidFileAttributes) &&
  8110. (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
  8111. result = true;
  8112. }
  8113. #else
  8114. posix::StatStruct file_stat;
  8115. result = posix::Stat(path.c_str(), &file_stat) == 0 &&
  8116. posix::IsDir(file_stat);
  8117. #endif // GTEST_OS_WINDOWS_MOBILE
  8118. return result;
  8119. }
  8120. // Returns true if pathname describes a root directory. (Windows has one
  8121. // root directory per disk drive.)
  8122. bool FilePath::IsRootDirectory() const {
  8123. #if GTEST_OS_WINDOWS
  8124. return pathname_.length() == 3 && IsAbsolutePath();
  8125. #else
  8126. return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]);
  8127. #endif
  8128. }
  8129. // Returns true if pathname describes an absolute path.
  8130. bool FilePath::IsAbsolutePath() const {
  8131. const char* const name = pathname_.c_str();
  8132. #if GTEST_OS_WINDOWS
  8133. return pathname_.length() >= 3 &&
  8134. ((name[0] >= 'a' && name[0] <= 'z') ||
  8135. (name[0] >= 'A' && name[0] <= 'Z')) &&
  8136. name[1] == ':' &&
  8137. IsPathSeparator(name[2]);
  8138. #else
  8139. return IsPathSeparator(name[0]);
  8140. #endif
  8141. }
  8142. // Returns a pathname for a file that does not currently exist. The pathname
  8143. // will be directory/base_name.extension or
  8144. // directory/base_name_<number>.extension if directory/base_name.extension
  8145. // already exists. The number will be incremented until a pathname is found
  8146. // that does not already exist.
  8147. // Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.
  8148. // There could be a race condition if two or more processes are calling this
  8149. // function at the same time -- they could both pick the same filename.
  8150. FilePath FilePath::GenerateUniqueFileName(const FilePath& directory,
  8151. const FilePath& base_name,
  8152. const char* extension) {
  8153. FilePath full_pathname;
  8154. int number = 0;
  8155. do {
  8156. full_pathname.Set(MakeFileName(directory, base_name, number++, extension));
  8157. } while (full_pathname.FileOrDirectoryExists());
  8158. return full_pathname;
  8159. }
  8160. // Returns true if FilePath ends with a path separator, which indicates that
  8161. // it is intended to represent a directory. Returns false otherwise.
  8162. // This does NOT check that a directory (or file) actually exists.
  8163. bool FilePath::IsDirectory() const {
  8164. return !pathname_.empty() &&
  8165. IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]);
  8166. }
  8167. // Create directories so that path exists. Returns true if successful or if
  8168. // the directories already exist; returns false if unable to create directories
  8169. // for any reason.
  8170. bool FilePath::CreateDirectoriesRecursively() const {
  8171. if (!this->IsDirectory()) {
  8172. return false;
  8173. }
  8174. if (pathname_.length() == 0 || this->DirectoryExists()) {
  8175. return true;
  8176. }
  8177. const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName());
  8178. return parent.CreateDirectoriesRecursively() && this->CreateFolder();
  8179. }
  8180. // Create the directory so that path exists. Returns true if successful or
  8181. // if the directory already exists; returns false if unable to create the
  8182. // directory for any reason, including if the parent directory does not
  8183. // exist. Not named "CreateDirectory" because that's a macro on Windows.
  8184. bool FilePath::CreateFolder() const {
  8185. #if GTEST_OS_WINDOWS_MOBILE
  8186. FilePath removed_sep(this->RemoveTrailingPathSeparator());
  8187. LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());
  8188. int result = CreateDirectory(unicode, nullptr) ? 0 : -1;
  8189. delete [] unicode;
  8190. #elif GTEST_OS_WINDOWS
  8191. int result = _mkdir(pathname_.c_str());
  8192. #else
  8193. int result = mkdir(pathname_.c_str(), 0777);
  8194. #endif // GTEST_OS_WINDOWS_MOBILE
  8195. if (result == -1) {
  8196. return this->DirectoryExists(); // An error is OK if the directory exists.
  8197. }
  8198. return true; // No error.
  8199. }
  8200. // If input name has a trailing separator character, remove it and return the
  8201. // name, otherwise return the name string unmodified.
  8202. // On Windows platform, uses \ as the separator, other platforms use /.
  8203. FilePath FilePath::RemoveTrailingPathSeparator() const {
  8204. return IsDirectory()
  8205. ? FilePath(pathname_.substr(0, pathname_.length() - 1))
  8206. : *this;
  8207. }
  8208. // Removes any redundant separators that might be in the pathname.
  8209. // For example, "bar///foo" becomes "bar/foo". Does not eliminate other
  8210. // redundancies that might be in a pathname involving "." or "..".
  8211. void FilePath::Normalize() {
  8212. if (pathname_.c_str() == nullptr) {
  8213. pathname_ = "";
  8214. return;
  8215. }
  8216. const char* src = pathname_.c_str();
  8217. char* const dest = new char[pathname_.length() + 1];
  8218. char* dest_ptr = dest;
  8219. memset(dest_ptr, 0, pathname_.length() + 1);
  8220. while (*src != '\0') {
  8221. *dest_ptr = *src;
  8222. if (!IsPathSeparator(*src)) {
  8223. src++;
  8224. } else {
  8225. #if GTEST_HAS_ALT_PATH_SEP_
  8226. if (*dest_ptr == kAlternatePathSeparator) {
  8227. *dest_ptr = kPathSeparator;
  8228. }
  8229. #endif
  8230. while (IsPathSeparator(*src))
  8231. src++;
  8232. }
  8233. dest_ptr++;
  8234. }
  8235. *dest_ptr = '\0';
  8236. pathname_ = dest;
  8237. delete[] dest;
  8238. }
  8239. } // namespace internal
  8240. } // namespace testing
  8241. // Copyright 2007, Google Inc.
  8242. // All rights reserved.
  8243. //
  8244. // Redistribution and use in source and binary forms, with or without
  8245. // modification, are permitted provided that the following conditions are
  8246. // met:
  8247. //
  8248. // * Redistributions of source code must retain the above copyright
  8249. // notice, this list of conditions and the following disclaimer.
  8250. // * Redistributions in binary form must reproduce the above
  8251. // copyright notice, this list of conditions and the following disclaimer
  8252. // in the documentation and/or other materials provided with the
  8253. // distribution.
  8254. // * Neither the name of Google Inc. nor the names of its
  8255. // contributors may be used to endorse or promote products derived from
  8256. // this software without specific prior written permission.
  8257. //
  8258. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  8259. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  8260. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  8261. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  8262. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  8263. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  8264. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  8265. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  8266. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  8267. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  8268. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  8269. // The Google C++ Testing and Mocking Framework (Google Test)
  8270. //
  8271. // This file implements just enough of the matcher interface to allow
  8272. // EXPECT_DEATH and friends to accept a matcher argument.
  8273. #include <string>
  8274. namespace testing {
  8275. // Constructs a matcher that matches a const std::string& whose value is
  8276. // equal to s.
  8277. Matcher<const std::string&>::Matcher(const std::string& s) { *this = Eq(s); }
  8278. #if GTEST_HAS_GLOBAL_STRING
  8279. // Constructs a matcher that matches a const std::string& whose value is
  8280. // equal to s.
  8281. Matcher<const std::string&>::Matcher(const ::string& s) {
  8282. *this = Eq(static_cast<std::string>(s));
  8283. }
  8284. #endif // GTEST_HAS_GLOBAL_STRING
  8285. // Constructs a matcher that matches a const std::string& whose value is
  8286. // equal to s.
  8287. Matcher<const std::string&>::Matcher(const char* s) {
  8288. *this = Eq(std::string(s));
  8289. }
  8290. // Constructs a matcher that matches a std::string whose value is equal to
  8291. // s.
  8292. Matcher<std::string>::Matcher(const std::string& s) { *this = Eq(s); }
  8293. #if GTEST_HAS_GLOBAL_STRING
  8294. // Constructs a matcher that matches a std::string whose value is equal to
  8295. // s.
  8296. Matcher<std::string>::Matcher(const ::string& s) {
  8297. *this = Eq(static_cast<std::string>(s));
  8298. }
  8299. #endif // GTEST_HAS_GLOBAL_STRING
  8300. // Constructs a matcher that matches a std::string whose value is equal to
  8301. // s.
  8302. Matcher<std::string>::Matcher(const char* s) { *this = Eq(std::string(s)); }
  8303. #if GTEST_HAS_GLOBAL_STRING
  8304. // Constructs a matcher that matches a const ::string& whose value is
  8305. // equal to s.
  8306. Matcher<const ::string&>::Matcher(const std::string& s) {
  8307. *this = Eq(static_cast<::string>(s));
  8308. }
  8309. // Constructs a matcher that matches a const ::string& whose value is
  8310. // equal to s.
  8311. Matcher<const ::string&>::Matcher(const ::string& s) { *this = Eq(s); }
  8312. // Constructs a matcher that matches a const ::string& whose value is
  8313. // equal to s.
  8314. Matcher<const ::string&>::Matcher(const char* s) { *this = Eq(::string(s)); }
  8315. // Constructs a matcher that matches a ::string whose value is equal to s.
  8316. Matcher<::string>::Matcher(const std::string& s) {
  8317. *this = Eq(static_cast<::string>(s));
  8318. }
  8319. // Constructs a matcher that matches a ::string whose value is equal to s.
  8320. Matcher<::string>::Matcher(const ::string& s) { *this = Eq(s); }
  8321. // Constructs a matcher that matches a string whose value is equal to s.
  8322. Matcher<::string>::Matcher(const char* s) { *this = Eq(::string(s)); }
  8323. #endif // GTEST_HAS_GLOBAL_STRING
  8324. #if GTEST_HAS_ABSL
  8325. // Constructs a matcher that matches a const absl::string_view& whose value is
  8326. // equal to s.
  8327. Matcher<const absl::string_view&>::Matcher(const std::string& s) {
  8328. *this = Eq(s);
  8329. }
  8330. #if GTEST_HAS_GLOBAL_STRING
  8331. // Constructs a matcher that matches a const absl::string_view& whose value is
  8332. // equal to s.
  8333. Matcher<const absl::string_view&>::Matcher(const ::string& s) { *this = Eq(s); }
  8334. #endif // GTEST_HAS_GLOBAL_STRING
  8335. // Constructs a matcher that matches a const absl::string_view& whose value is
  8336. // equal to s.
  8337. Matcher<const absl::string_view&>::Matcher(const char* s) {
  8338. *this = Eq(std::string(s));
  8339. }
  8340. // Constructs a matcher that matches a const absl::string_view& whose value is
  8341. // equal to s.
  8342. Matcher<const absl::string_view&>::Matcher(absl::string_view s) {
  8343. *this = Eq(std::string(s));
  8344. }
  8345. // Constructs a matcher that matches a absl::string_view whose value is equal to
  8346. // s.
  8347. Matcher<absl::string_view>::Matcher(const std::string& s) { *this = Eq(s); }
  8348. #if GTEST_HAS_GLOBAL_STRING
  8349. // Constructs a matcher that matches a absl::string_view whose value is equal to
  8350. // s.
  8351. Matcher<absl::string_view>::Matcher(const ::string& s) { *this = Eq(s); }
  8352. #endif // GTEST_HAS_GLOBAL_STRING
  8353. // Constructs a matcher that matches a absl::string_view whose value is equal to
  8354. // s.
  8355. Matcher<absl::string_view>::Matcher(const char* s) {
  8356. *this = Eq(std::string(s));
  8357. }
  8358. // Constructs a matcher that matches a absl::string_view whose value is equal to
  8359. // s.
  8360. Matcher<absl::string_view>::Matcher(absl::string_view s) {
  8361. *this = Eq(std::string(s));
  8362. }
  8363. #endif // GTEST_HAS_ABSL
  8364. } // namespace testing
  8365. // Copyright 2008, Google Inc.
  8366. // All rights reserved.
  8367. //
  8368. // Redistribution and use in source and binary forms, with or without
  8369. // modification, are permitted provided that the following conditions are
  8370. // met:
  8371. //
  8372. // * Redistributions of source code must retain the above copyright
  8373. // notice, this list of conditions and the following disclaimer.
  8374. // * Redistributions in binary form must reproduce the above
  8375. // copyright notice, this list of conditions and the following disclaimer
  8376. // in the documentation and/or other materials provided with the
  8377. // distribution.
  8378. // * Neither the name of Google Inc. nor the names of its
  8379. // contributors may be used to endorse or promote products derived from
  8380. // this software without specific prior written permission.
  8381. //
  8382. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  8383. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  8384. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  8385. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  8386. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  8387. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  8388. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  8389. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  8390. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  8391. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  8392. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  8393. #include <limits.h>
  8394. #include <stdio.h>
  8395. #include <stdlib.h>
  8396. #include <string.h>
  8397. #include <fstream>
  8398. #include <memory>
  8399. #if GTEST_OS_WINDOWS
  8400. # include <windows.h>
  8401. # include <io.h>
  8402. # include <sys/stat.h>
  8403. # include <map> // Used in ThreadLocal.
  8404. # ifdef _MSC_VER
  8405. # include <crtdbg.h>
  8406. # endif // _MSC_VER
  8407. #else
  8408. # include <unistd.h>
  8409. #endif // GTEST_OS_WINDOWS
  8410. #if GTEST_OS_MAC
  8411. # include <mach/mach_init.h>
  8412. # include <mach/task.h>
  8413. # include <mach/vm_map.h>
  8414. #endif // GTEST_OS_MAC
  8415. #if GTEST_OS_QNX
  8416. # include <devctl.h>
  8417. # include <fcntl.h>
  8418. # include <sys/procfs.h>
  8419. #endif // GTEST_OS_QNX
  8420. #if GTEST_OS_AIX
  8421. # include <procinfo.h>
  8422. # include <sys/types.h>
  8423. #endif // GTEST_OS_AIX
  8424. #if GTEST_OS_FUCHSIA
  8425. # include <zircon/process.h>
  8426. # include <zircon/syscalls.h>
  8427. #endif // GTEST_OS_FUCHSIA
  8428. namespace testing {
  8429. namespace internal {
  8430. #if defined(_MSC_VER) || defined(__BORLANDC__)
  8431. // MSVC and C++Builder do not provide a definition of STDERR_FILENO.
  8432. const int kStdOutFileno = 1;
  8433. const int kStdErrFileno = 2;
  8434. #else
  8435. const int kStdOutFileno = STDOUT_FILENO;
  8436. const int kStdErrFileno = STDERR_FILENO;
  8437. #endif // _MSC_VER
  8438. #if GTEST_OS_LINUX
  8439. namespace {
  8440. template <typename T>
  8441. T ReadProcFileField(const std::string& filename, int field) {
  8442. std::string dummy;
  8443. std::ifstream file(filename.c_str());
  8444. while (field-- > 0) {
  8445. file >> dummy;
  8446. }
  8447. T output = 0;
  8448. file >> output;
  8449. return output;
  8450. }
  8451. } // namespace
  8452. // Returns the number of active threads, or 0 when there is an error.
  8453. size_t GetThreadCount() {
  8454. const std::string filename =
  8455. (Message() << "/proc/" << getpid() << "/stat").GetString();
  8456. return ReadProcFileField<int>(filename, 19);
  8457. }
  8458. #elif GTEST_OS_MAC
  8459. size_t GetThreadCount() {
  8460. const task_t task = mach_task_self();
  8461. mach_msg_type_number_t thread_count;
  8462. thread_act_array_t thread_list;
  8463. const kern_return_t status = task_threads(task, &thread_list, &thread_count);
  8464. if (status == KERN_SUCCESS) {
  8465. // task_threads allocates resources in thread_list and we need to free them
  8466. // to avoid leaks.
  8467. vm_deallocate(task,
  8468. reinterpret_cast<vm_address_t>(thread_list),
  8469. sizeof(thread_t) * thread_count);
  8470. return static_cast<size_t>(thread_count);
  8471. } else {
  8472. return 0;
  8473. }
  8474. }
  8475. #elif GTEST_OS_QNX
  8476. // Returns the number of threads running in the process, or 0 to indicate that
  8477. // we cannot detect it.
  8478. size_t GetThreadCount() {
  8479. const int fd = open("/proc/self/as", O_RDONLY);
  8480. if (fd < 0) {
  8481. return 0;
  8482. }
  8483. procfs_info process_info;
  8484. const int status =
  8485. devctl(fd, DCMD_PROC_INFO, &process_info, sizeof(process_info), nullptr);
  8486. close(fd);
  8487. if (status == EOK) {
  8488. return static_cast<size_t>(process_info.num_threads);
  8489. } else {
  8490. return 0;
  8491. }
  8492. }
  8493. #elif GTEST_OS_AIX
  8494. size_t GetThreadCount() {
  8495. struct procentry64 entry;
  8496. pid_t pid = getpid();
  8497. int status = getprocs64(&entry, sizeof(entry), nullptr, 0, &pid, 1);
  8498. if (status == 1) {
  8499. return entry.pi_thcount;
  8500. } else {
  8501. return 0;
  8502. }
  8503. }
  8504. #elif GTEST_OS_FUCHSIA
  8505. size_t GetThreadCount() {
  8506. int dummy_buffer;
  8507. size_t avail;
  8508. zx_status_t status = zx_object_get_info(
  8509. zx_process_self(),
  8510. ZX_INFO_PROCESS_THREADS,
  8511. &dummy_buffer,
  8512. 0,
  8513. nullptr,
  8514. &avail);
  8515. if (status == ZX_OK) {
  8516. return avail;
  8517. } else {
  8518. return 0;
  8519. }
  8520. }
  8521. #else
  8522. size_t GetThreadCount() {
  8523. // There's no portable way to detect the number of threads, so we just
  8524. // return 0 to indicate that we cannot detect it.
  8525. return 0;
  8526. }
  8527. #endif // GTEST_OS_LINUX
  8528. #if GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
  8529. void SleepMilliseconds(int n) {
  8530. ::Sleep(n);
  8531. }
  8532. AutoHandle::AutoHandle()
  8533. : handle_(INVALID_HANDLE_VALUE) {}
  8534. AutoHandle::AutoHandle(Handle handle)
  8535. : handle_(handle) {}
  8536. AutoHandle::~AutoHandle() {
  8537. Reset();
  8538. }
  8539. AutoHandle::Handle AutoHandle::Get() const {
  8540. return handle_;
  8541. }
  8542. void AutoHandle::Reset() {
  8543. Reset(INVALID_HANDLE_VALUE);
  8544. }
  8545. void AutoHandle::Reset(HANDLE handle) {
  8546. // Resetting with the same handle we already own is invalid.
  8547. if (handle_ != handle) {
  8548. if (IsCloseable()) {
  8549. ::CloseHandle(handle_);
  8550. }
  8551. handle_ = handle;
  8552. } else {
  8553. GTEST_CHECK_(!IsCloseable())
  8554. << "Resetting a valid handle to itself is likely a programmer error "
  8555. "and thus not allowed.";
  8556. }
  8557. }
  8558. bool AutoHandle::IsCloseable() const {
  8559. // Different Windows APIs may use either of these values to represent an
  8560. // invalid handle.
  8561. return handle_ != nullptr && handle_ != INVALID_HANDLE_VALUE;
  8562. }
  8563. Notification::Notification()
  8564. : event_(::CreateEvent(nullptr, // Default security attributes.
  8565. TRUE, // Do not reset automatically.
  8566. FALSE, // Initially unset.
  8567. nullptr)) { // Anonymous event.
  8568. GTEST_CHECK_(event_.Get() != nullptr);
  8569. }
  8570. void Notification::Notify() {
  8571. GTEST_CHECK_(::SetEvent(event_.Get()) != FALSE);
  8572. }
  8573. void Notification::WaitForNotification() {
  8574. GTEST_CHECK_(
  8575. ::WaitForSingleObject(event_.Get(), INFINITE) == WAIT_OBJECT_0);
  8576. }
  8577. Mutex::Mutex()
  8578. : owner_thread_id_(0),
  8579. type_(kDynamic),
  8580. critical_section_init_phase_(0),
  8581. critical_section_(new CRITICAL_SECTION) {
  8582. ::InitializeCriticalSection(critical_section_);
  8583. }
  8584. Mutex::~Mutex() {
  8585. // Static mutexes are leaked intentionally. It is not thread-safe to try
  8586. // to clean them up.
  8587. if (type_ == kDynamic) {
  8588. ::DeleteCriticalSection(critical_section_);
  8589. delete critical_section_;
  8590. critical_section_ = nullptr;
  8591. }
  8592. }
  8593. void Mutex::Lock() {
  8594. ThreadSafeLazyInit();
  8595. ::EnterCriticalSection(critical_section_);
  8596. owner_thread_id_ = ::GetCurrentThreadId();
  8597. }
  8598. void Mutex::Unlock() {
  8599. ThreadSafeLazyInit();
  8600. // We don't protect writing to owner_thread_id_ here, as it's the
  8601. // caller's responsibility to ensure that the current thread holds the
  8602. // mutex when this is called.
  8603. owner_thread_id_ = 0;
  8604. ::LeaveCriticalSection(critical_section_);
  8605. }
  8606. // Does nothing if the current thread holds the mutex. Otherwise, crashes
  8607. // with high probability.
  8608. void Mutex::AssertHeld() {
  8609. ThreadSafeLazyInit();
  8610. GTEST_CHECK_(owner_thread_id_ == ::GetCurrentThreadId())
  8611. << "The current thread is not holding the mutex @" << this;
  8612. }
  8613. namespace {
  8614. // Use the RAII idiom to flag mem allocs that are intentionally never
  8615. // deallocated. The motivation is to silence the false positive mem leaks
  8616. // that are reported by the debug version of MS's CRT which can only detect
  8617. // if an alloc is missing a matching deallocation.
  8618. // Example:
  8619. // MemoryIsNotDeallocated memory_is_not_deallocated;
  8620. // critical_section_ = new CRITICAL_SECTION;
  8621. //
  8622. class MemoryIsNotDeallocated
  8623. {
  8624. public:
  8625. MemoryIsNotDeallocated() : old_crtdbg_flag_(0) {
  8626. #ifdef _MSC_VER
  8627. old_crtdbg_flag_ = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
  8628. // Set heap allocation block type to _IGNORE_BLOCK so that MS debug CRT
  8629. // doesn't report mem leak if there's no matching deallocation.
  8630. _CrtSetDbgFlag(old_crtdbg_flag_ & ~_CRTDBG_ALLOC_MEM_DF);
  8631. #endif // _MSC_VER
  8632. }
  8633. ~MemoryIsNotDeallocated() {
  8634. #ifdef _MSC_VER
  8635. // Restore the original _CRTDBG_ALLOC_MEM_DF flag
  8636. _CrtSetDbgFlag(old_crtdbg_flag_);
  8637. #endif // _MSC_VER
  8638. }
  8639. private:
  8640. int old_crtdbg_flag_;
  8641. GTEST_DISALLOW_COPY_AND_ASSIGN_(MemoryIsNotDeallocated);
  8642. };
  8643. } // namespace
  8644. // Initializes owner_thread_id_ and critical_section_ in static mutexes.
  8645. void Mutex::ThreadSafeLazyInit() {
  8646. // Dynamic mutexes are initialized in the constructor.
  8647. if (type_ == kStatic) {
  8648. switch (
  8649. ::InterlockedCompareExchange(&critical_section_init_phase_, 1L, 0L)) {
  8650. case 0:
  8651. // If critical_section_init_phase_ was 0 before the exchange, we
  8652. // are the first to test it and need to perform the initialization.
  8653. owner_thread_id_ = 0;
  8654. {
  8655. // Use RAII to flag that following mem alloc is never deallocated.
  8656. MemoryIsNotDeallocated memory_is_not_deallocated;
  8657. critical_section_ = new CRITICAL_SECTION;
  8658. }
  8659. ::InitializeCriticalSection(critical_section_);
  8660. // Updates the critical_section_init_phase_ to 2 to signal
  8661. // initialization complete.
  8662. GTEST_CHECK_(::InterlockedCompareExchange(
  8663. &critical_section_init_phase_, 2L, 1L) ==
  8664. 1L);
  8665. break;
  8666. case 1:
  8667. // Somebody else is already initializing the mutex; spin until they
  8668. // are done.
  8669. while (::InterlockedCompareExchange(&critical_section_init_phase_,
  8670. 2L,
  8671. 2L) != 2L) {
  8672. // Possibly yields the rest of the thread's time slice to other
  8673. // threads.
  8674. ::Sleep(0);
  8675. }
  8676. break;
  8677. case 2:
  8678. break; // The mutex is already initialized and ready for use.
  8679. default:
  8680. GTEST_CHECK_(false)
  8681. << "Unexpected value of critical_section_init_phase_ "
  8682. << "while initializing a static mutex.";
  8683. }
  8684. }
  8685. }
  8686. namespace {
  8687. class ThreadWithParamSupport : public ThreadWithParamBase {
  8688. public:
  8689. static HANDLE CreateThread(Runnable* runnable,
  8690. Notification* thread_can_start) {
  8691. ThreadMainParam* param = new ThreadMainParam(runnable, thread_can_start);
  8692. DWORD thread_id;
  8693. HANDLE thread_handle = ::CreateThread(
  8694. nullptr, // Default security.
  8695. 0, // Default stack size.
  8696. &ThreadWithParamSupport::ThreadMain,
  8697. param, // Parameter to ThreadMainStatic
  8698. 0x0, // Default creation flags.
  8699. &thread_id); // Need a valid pointer for the call to work under Win98.
  8700. GTEST_CHECK_(thread_handle != nullptr)
  8701. << "CreateThread failed with error " << ::GetLastError() << ".";
  8702. if (thread_handle == nullptr) {
  8703. delete param;
  8704. }
  8705. return thread_handle;
  8706. }
  8707. private:
  8708. struct ThreadMainParam {
  8709. ThreadMainParam(Runnable* runnable, Notification* thread_can_start)
  8710. : runnable_(runnable),
  8711. thread_can_start_(thread_can_start) {
  8712. }
  8713. std::unique_ptr<Runnable> runnable_;
  8714. // Does not own.
  8715. Notification* thread_can_start_;
  8716. };
  8717. static DWORD WINAPI ThreadMain(void* ptr) {
  8718. // Transfers ownership.
  8719. std::unique_ptr<ThreadMainParam> param(static_cast<ThreadMainParam*>(ptr));
  8720. if (param->thread_can_start_ != nullptr)
  8721. param->thread_can_start_->WaitForNotification();
  8722. param->runnable_->Run();
  8723. return 0;
  8724. }
  8725. // Prohibit instantiation.
  8726. ThreadWithParamSupport();
  8727. GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParamSupport);
  8728. };
  8729. } // namespace
  8730. ThreadWithParamBase::ThreadWithParamBase(Runnable *runnable,
  8731. Notification* thread_can_start)
  8732. : thread_(ThreadWithParamSupport::CreateThread(runnable,
  8733. thread_can_start)) {
  8734. }
  8735. ThreadWithParamBase::~ThreadWithParamBase() {
  8736. Join();
  8737. }
  8738. void ThreadWithParamBase::Join() {
  8739. GTEST_CHECK_(::WaitForSingleObject(thread_.Get(), INFINITE) == WAIT_OBJECT_0)
  8740. << "Failed to join the thread with error " << ::GetLastError() << ".";
  8741. }
  8742. // Maps a thread to a set of ThreadIdToThreadLocals that have values
  8743. // instantiated on that thread and notifies them when the thread exits. A
  8744. // ThreadLocal instance is expected to persist until all threads it has
  8745. // values on have terminated.
  8746. class ThreadLocalRegistryImpl {
  8747. public:
  8748. // Registers thread_local_instance as having value on the current thread.
  8749. // Returns a value that can be used to identify the thread from other threads.
  8750. static ThreadLocalValueHolderBase* GetValueOnCurrentThread(
  8751. const ThreadLocalBase* thread_local_instance) {
  8752. DWORD current_thread = ::GetCurrentThreadId();
  8753. MutexLock lock(&mutex_);
  8754. ThreadIdToThreadLocals* const thread_to_thread_locals =
  8755. GetThreadLocalsMapLocked();
  8756. ThreadIdToThreadLocals::iterator thread_local_pos =
  8757. thread_to_thread_locals->find(current_thread);
  8758. if (thread_local_pos == thread_to_thread_locals->end()) {
  8759. thread_local_pos = thread_to_thread_locals->insert(
  8760. std::make_pair(current_thread, ThreadLocalValues())).first;
  8761. StartWatcherThreadFor(current_thread);
  8762. }
  8763. ThreadLocalValues& thread_local_values = thread_local_pos->second;
  8764. ThreadLocalValues::iterator value_pos =
  8765. thread_local_values.find(thread_local_instance);
  8766. if (value_pos == thread_local_values.end()) {
  8767. value_pos =
  8768. thread_local_values
  8769. .insert(std::make_pair(
  8770. thread_local_instance,
  8771. std::shared_ptr<ThreadLocalValueHolderBase>(
  8772. thread_local_instance->NewValueForCurrentThread())))
  8773. .first;
  8774. }
  8775. return value_pos->second.get();
  8776. }
  8777. static void OnThreadLocalDestroyed(
  8778. const ThreadLocalBase* thread_local_instance) {
  8779. std::vector<std::shared_ptr<ThreadLocalValueHolderBase> > value_holders;
  8780. // Clean up the ThreadLocalValues data structure while holding the lock, but
  8781. // defer the destruction of the ThreadLocalValueHolderBases.
  8782. {
  8783. MutexLock lock(&mutex_);
  8784. ThreadIdToThreadLocals* const thread_to_thread_locals =
  8785. GetThreadLocalsMapLocked();
  8786. for (ThreadIdToThreadLocals::iterator it =
  8787. thread_to_thread_locals->begin();
  8788. it != thread_to_thread_locals->end();
  8789. ++it) {
  8790. ThreadLocalValues& thread_local_values = it->second;
  8791. ThreadLocalValues::iterator value_pos =
  8792. thread_local_values.find(thread_local_instance);
  8793. if (value_pos != thread_local_values.end()) {
  8794. value_holders.push_back(value_pos->second);
  8795. thread_local_values.erase(value_pos);
  8796. // This 'if' can only be successful at most once, so theoretically we
  8797. // could break out of the loop here, but we don't bother doing so.
  8798. }
  8799. }
  8800. }
  8801. // Outside the lock, let the destructor for 'value_holders' deallocate the
  8802. // ThreadLocalValueHolderBases.
  8803. }
  8804. static void OnThreadExit(DWORD thread_id) {
  8805. GTEST_CHECK_(thread_id != 0) << ::GetLastError();
  8806. std::vector<std::shared_ptr<ThreadLocalValueHolderBase> > value_holders;
  8807. // Clean up the ThreadIdToThreadLocals data structure while holding the
  8808. // lock, but defer the destruction of the ThreadLocalValueHolderBases.
  8809. {
  8810. MutexLock lock(&mutex_);
  8811. ThreadIdToThreadLocals* const thread_to_thread_locals =
  8812. GetThreadLocalsMapLocked();
  8813. ThreadIdToThreadLocals::iterator thread_local_pos =
  8814. thread_to_thread_locals->find(thread_id);
  8815. if (thread_local_pos != thread_to_thread_locals->end()) {
  8816. ThreadLocalValues& thread_local_values = thread_local_pos->second;
  8817. for (ThreadLocalValues::iterator value_pos =
  8818. thread_local_values.begin();
  8819. value_pos != thread_local_values.end();
  8820. ++value_pos) {
  8821. value_holders.push_back(value_pos->second);
  8822. }
  8823. thread_to_thread_locals->erase(thread_local_pos);
  8824. }
  8825. }
  8826. // Outside the lock, let the destructor for 'value_holders' deallocate the
  8827. // ThreadLocalValueHolderBases.
  8828. }
  8829. private:
  8830. // In a particular thread, maps a ThreadLocal object to its value.
  8831. typedef std::map<const ThreadLocalBase*,
  8832. std::shared_ptr<ThreadLocalValueHolderBase> >
  8833. ThreadLocalValues;
  8834. // Stores all ThreadIdToThreadLocals having values in a thread, indexed by
  8835. // thread's ID.
  8836. typedef std::map<DWORD, ThreadLocalValues> ThreadIdToThreadLocals;
  8837. // Holds the thread id and thread handle that we pass from
  8838. // StartWatcherThreadFor to WatcherThreadFunc.
  8839. typedef std::pair<DWORD, HANDLE> ThreadIdAndHandle;
  8840. static void StartWatcherThreadFor(DWORD thread_id) {
  8841. // The returned handle will be kept in thread_map and closed by
  8842. // watcher_thread in WatcherThreadFunc.
  8843. HANDLE thread = ::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION,
  8844. FALSE,
  8845. thread_id);
  8846. GTEST_CHECK_(thread != nullptr);
  8847. // We need to pass a valid thread ID pointer into CreateThread for it
  8848. // to work correctly under Win98.
  8849. DWORD watcher_thread_id;
  8850. HANDLE watcher_thread = ::CreateThread(
  8851. nullptr, // Default security.
  8852. 0, // Default stack size
  8853. &ThreadLocalRegistryImpl::WatcherThreadFunc,
  8854. reinterpret_cast<LPVOID>(new ThreadIdAndHandle(thread_id, thread)),
  8855. CREATE_SUSPENDED, &watcher_thread_id);
  8856. GTEST_CHECK_(watcher_thread != nullptr);
  8857. // Give the watcher thread the same priority as ours to avoid being
  8858. // blocked by it.
  8859. ::SetThreadPriority(watcher_thread,
  8860. ::GetThreadPriority(::GetCurrentThread()));
  8861. ::ResumeThread(watcher_thread);
  8862. ::CloseHandle(watcher_thread);
  8863. }
  8864. // Monitors exit from a given thread and notifies those
  8865. // ThreadIdToThreadLocals about thread termination.
  8866. static DWORD WINAPI WatcherThreadFunc(LPVOID param) {
  8867. const ThreadIdAndHandle* tah =
  8868. reinterpret_cast<const ThreadIdAndHandle*>(param);
  8869. GTEST_CHECK_(
  8870. ::WaitForSingleObject(tah->second, INFINITE) == WAIT_OBJECT_0);
  8871. OnThreadExit(tah->first);
  8872. ::CloseHandle(tah->second);
  8873. delete tah;
  8874. return 0;
  8875. }
  8876. // Returns map of thread local instances.
  8877. static ThreadIdToThreadLocals* GetThreadLocalsMapLocked() {
  8878. mutex_.AssertHeld();
  8879. MemoryIsNotDeallocated memory_is_not_deallocated;
  8880. static ThreadIdToThreadLocals* map = new ThreadIdToThreadLocals();
  8881. return map;
  8882. }
  8883. // Protects access to GetThreadLocalsMapLocked() and its return value.
  8884. static Mutex mutex_;
  8885. // Protects access to GetThreadMapLocked() and its return value.
  8886. static Mutex thread_map_mutex_;
  8887. };
  8888. Mutex ThreadLocalRegistryImpl::mutex_(Mutex::kStaticMutex);
  8889. Mutex ThreadLocalRegistryImpl::thread_map_mutex_(Mutex::kStaticMutex);
  8890. ThreadLocalValueHolderBase* ThreadLocalRegistry::GetValueOnCurrentThread(
  8891. const ThreadLocalBase* thread_local_instance) {
  8892. return ThreadLocalRegistryImpl::GetValueOnCurrentThread(
  8893. thread_local_instance);
  8894. }
  8895. void ThreadLocalRegistry::OnThreadLocalDestroyed(
  8896. const ThreadLocalBase* thread_local_instance) {
  8897. ThreadLocalRegistryImpl::OnThreadLocalDestroyed(thread_local_instance);
  8898. }
  8899. #endif // GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
  8900. #if GTEST_USES_POSIX_RE
  8901. // Implements RE. Currently only needed for death tests.
  8902. RE::~RE() {
  8903. if (is_valid_) {
  8904. // regfree'ing an invalid regex might crash because the content
  8905. // of the regex is undefined. Since the regex's are essentially
  8906. // the same, one cannot be valid (or invalid) without the other
  8907. // being so too.
  8908. regfree(&partial_regex_);
  8909. regfree(&full_regex_);
  8910. }
  8911. free(const_cast<char*>(pattern_));
  8912. }
  8913. // Returns true iff regular expression re matches the entire str.
  8914. bool RE::FullMatch(const char* str, const RE& re) {
  8915. if (!re.is_valid_) return false;
  8916. regmatch_t match;
  8917. return regexec(&re.full_regex_, str, 1, &match, 0) == 0;
  8918. }
  8919. // Returns true iff regular expression re matches a substring of str
  8920. // (including str itself).
  8921. bool RE::PartialMatch(const char* str, const RE& re) {
  8922. if (!re.is_valid_) return false;
  8923. regmatch_t match;
  8924. return regexec(&re.partial_regex_, str, 1, &match, 0) == 0;
  8925. }
  8926. // Initializes an RE from its string representation.
  8927. void RE::Init(const char* regex) {
  8928. pattern_ = posix::StrDup(regex);
  8929. // Reserves enough bytes to hold the regular expression used for a
  8930. // full match.
  8931. const size_t full_regex_len = strlen(regex) + 10;
  8932. char* const full_pattern = new char[full_regex_len];
  8933. snprintf(full_pattern, full_regex_len, "^(%s)$", regex);
  8934. is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0;
  8935. // We want to call regcomp(&partial_regex_, ...) even if the
  8936. // previous expression returns false. Otherwise partial_regex_ may
  8937. // not be properly initialized can may cause trouble when it's
  8938. // freed.
  8939. //
  8940. // Some implementation of POSIX regex (e.g. on at least some
  8941. // versions of Cygwin) doesn't accept the empty string as a valid
  8942. // regex. We change it to an equivalent form "()" to be safe.
  8943. if (is_valid_) {
  8944. const char* const partial_regex = (*regex == '\0') ? "()" : regex;
  8945. is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0;
  8946. }
  8947. EXPECT_TRUE(is_valid_)
  8948. << "Regular expression \"" << regex
  8949. << "\" is not a valid POSIX Extended regular expression.";
  8950. delete[] full_pattern;
  8951. }
  8952. #elif GTEST_USES_SIMPLE_RE
  8953. // Returns true iff ch appears anywhere in str (excluding the
  8954. // terminating '\0' character).
  8955. bool IsInSet(char ch, const char* str) {
  8956. return ch != '\0' && strchr(str, ch) != nullptr;
  8957. }
  8958. // Returns true iff ch belongs to the given classification. Unlike
  8959. // similar functions in <ctype.h>, these aren't affected by the
  8960. // current locale.
  8961. bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; }
  8962. bool IsAsciiPunct(char ch) {
  8963. return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
  8964. }
  8965. bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); }
  8966. bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); }
  8967. bool IsAsciiWordChar(char ch) {
  8968. return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') ||
  8969. ('0' <= ch && ch <= '9') || ch == '_';
  8970. }
  8971. // Returns true iff "\\c" is a supported escape sequence.
  8972. bool IsValidEscape(char c) {
  8973. return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW"));
  8974. }
  8975. // Returns true iff the given atom (specified by escaped and pattern)
  8976. // matches ch. The result is undefined if the atom is invalid.
  8977. bool AtomMatchesChar(bool escaped, char pattern_char, char ch) {
  8978. if (escaped) { // "\\p" where p is pattern_char.
  8979. switch (pattern_char) {
  8980. case 'd': return IsAsciiDigit(ch);
  8981. case 'D': return !IsAsciiDigit(ch);
  8982. case 'f': return ch == '\f';
  8983. case 'n': return ch == '\n';
  8984. case 'r': return ch == '\r';
  8985. case 's': return IsAsciiWhiteSpace(ch);
  8986. case 'S': return !IsAsciiWhiteSpace(ch);
  8987. case 't': return ch == '\t';
  8988. case 'v': return ch == '\v';
  8989. case 'w': return IsAsciiWordChar(ch);
  8990. case 'W': return !IsAsciiWordChar(ch);
  8991. }
  8992. return IsAsciiPunct(pattern_char) && pattern_char == ch;
  8993. }
  8994. return (pattern_char == '.' && ch != '\n') || pattern_char == ch;
  8995. }
  8996. // Helper function used by ValidateRegex() to format error messages.
  8997. static std::string FormatRegexSyntaxError(const char* regex, int index) {
  8998. return (Message() << "Syntax error at index " << index
  8999. << " in simple regular expression \"" << regex << "\": ").GetString();
  9000. }
  9001. // Generates non-fatal failures and returns false if regex is invalid;
  9002. // otherwise returns true.
  9003. bool ValidateRegex(const char* regex) {
  9004. if (regex == nullptr) {
  9005. ADD_FAILURE() << "NULL is not a valid simple regular expression.";
  9006. return false;
  9007. }
  9008. bool is_valid = true;
  9009. // True iff ?, *, or + can follow the previous atom.
  9010. bool prev_repeatable = false;
  9011. for (int i = 0; regex[i]; i++) {
  9012. if (regex[i] == '\\') { // An escape sequence
  9013. i++;
  9014. if (regex[i] == '\0') {
  9015. ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
  9016. << "'\\' cannot appear at the end.";
  9017. return false;
  9018. }
  9019. if (!IsValidEscape(regex[i])) {
  9020. ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
  9021. << "invalid escape sequence \"\\" << regex[i] << "\".";
  9022. is_valid = false;
  9023. }
  9024. prev_repeatable = true;
  9025. } else { // Not an escape sequence.
  9026. const char ch = regex[i];
  9027. if (ch == '^' && i > 0) {
  9028. ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
  9029. << "'^' can only appear at the beginning.";
  9030. is_valid = false;
  9031. } else if (ch == '$' && regex[i + 1] != '\0') {
  9032. ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
  9033. << "'$' can only appear at the end.";
  9034. is_valid = false;
  9035. } else if (IsInSet(ch, "()[]{}|")) {
  9036. ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
  9037. << "'" << ch << "' is unsupported.";
  9038. is_valid = false;
  9039. } else if (IsRepeat(ch) && !prev_repeatable) {
  9040. ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
  9041. << "'" << ch << "' can only follow a repeatable token.";
  9042. is_valid = false;
  9043. }
  9044. prev_repeatable = !IsInSet(ch, "^$?*+");
  9045. }
  9046. }
  9047. return is_valid;
  9048. }
  9049. // Matches a repeated regex atom followed by a valid simple regular
  9050. // expression. The regex atom is defined as c if escaped is false,
  9051. // or \c otherwise. repeat is the repetition meta character (?, *,
  9052. // or +). The behavior is undefined if str contains too many
  9053. // characters to be indexable by size_t, in which case the test will
  9054. // probably time out anyway. We are fine with this limitation as
  9055. // std::string has it too.
  9056. bool MatchRepetitionAndRegexAtHead(
  9057. bool escaped, char c, char repeat, const char* regex,
  9058. const char* str) {
  9059. const size_t min_count = (repeat == '+') ? 1 : 0;
  9060. const size_t max_count = (repeat == '?') ? 1 :
  9061. static_cast<size_t>(-1) - 1;
  9062. // We cannot call numeric_limits::max() as it conflicts with the
  9063. // max() macro on Windows.
  9064. for (size_t i = 0; i <= max_count; ++i) {
  9065. // We know that the atom matches each of the first i characters in str.
  9066. if (i >= min_count && MatchRegexAtHead(regex, str + i)) {
  9067. // We have enough matches at the head, and the tail matches too.
  9068. // Since we only care about *whether* the pattern matches str
  9069. // (as opposed to *how* it matches), there is no need to find a
  9070. // greedy match.
  9071. return true;
  9072. }
  9073. if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i]))
  9074. return false;
  9075. }
  9076. return false;
  9077. }
  9078. // Returns true iff regex matches a prefix of str. regex must be a
  9079. // valid simple regular expression and not start with "^", or the
  9080. // result is undefined.
  9081. bool MatchRegexAtHead(const char* regex, const char* str) {
  9082. if (*regex == '\0') // An empty regex matches a prefix of anything.
  9083. return true;
  9084. // "$" only matches the end of a string. Note that regex being
  9085. // valid guarantees that there's nothing after "$" in it.
  9086. if (*regex == '$')
  9087. return *str == '\0';
  9088. // Is the first thing in regex an escape sequence?
  9089. const bool escaped = *regex == '\\';
  9090. if (escaped)
  9091. ++regex;
  9092. if (IsRepeat(regex[1])) {
  9093. // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so
  9094. // here's an indirect recursion. It terminates as the regex gets
  9095. // shorter in each recursion.
  9096. return MatchRepetitionAndRegexAtHead(
  9097. escaped, regex[0], regex[1], regex + 2, str);
  9098. } else {
  9099. // regex isn't empty, isn't "$", and doesn't start with a
  9100. // repetition. We match the first atom of regex with the first
  9101. // character of str and recurse.
  9102. return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) &&
  9103. MatchRegexAtHead(regex + 1, str + 1);
  9104. }
  9105. }
  9106. // Returns true iff regex matches any substring of str. regex must be
  9107. // a valid simple regular expression, or the result is undefined.
  9108. //
  9109. // The algorithm is recursive, but the recursion depth doesn't exceed
  9110. // the regex length, so we won't need to worry about running out of
  9111. // stack space normally. In rare cases the time complexity can be
  9112. // exponential with respect to the regex length + the string length,
  9113. // but usually it's must faster (often close to linear).
  9114. bool MatchRegexAnywhere(const char* regex, const char* str) {
  9115. if (regex == nullptr || str == nullptr) return false;
  9116. if (*regex == '^')
  9117. return MatchRegexAtHead(regex + 1, str);
  9118. // A successful match can be anywhere in str.
  9119. do {
  9120. if (MatchRegexAtHead(regex, str))
  9121. return true;
  9122. } while (*str++ != '\0');
  9123. return false;
  9124. }
  9125. // Implements the RE class.
  9126. RE::~RE() {
  9127. free(const_cast<char*>(pattern_));
  9128. free(const_cast<char*>(full_pattern_));
  9129. }
  9130. // Returns true iff regular expression re matches the entire str.
  9131. bool RE::FullMatch(const char* str, const RE& re) {
  9132. return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);
  9133. }
  9134. // Returns true iff regular expression re matches a substring of str
  9135. // (including str itself).
  9136. bool RE::PartialMatch(const char* str, const RE& re) {
  9137. return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);
  9138. }
  9139. // Initializes an RE from its string representation.
  9140. void RE::Init(const char* regex) {
  9141. pattern_ = full_pattern_ = nullptr;
  9142. if (regex != nullptr) {
  9143. pattern_ = posix::StrDup(regex);
  9144. }
  9145. is_valid_ = ValidateRegex(regex);
  9146. if (!is_valid_) {
  9147. // No need to calculate the full pattern when the regex is invalid.
  9148. return;
  9149. }
  9150. const size_t len = strlen(regex);
  9151. // Reserves enough bytes to hold the regular expression used for a
  9152. // full match: we need space to prepend a '^', append a '$', and
  9153. // terminate the string with '\0'.
  9154. char* buffer = static_cast<char*>(malloc(len + 3));
  9155. full_pattern_ = buffer;
  9156. if (*regex != '^')
  9157. *buffer++ = '^'; // Makes sure full_pattern_ starts with '^'.
  9158. // We don't use snprintf or strncpy, as they trigger a warning when
  9159. // compiled with VC++ 8.0.
  9160. memcpy(buffer, regex, len);
  9161. buffer += len;
  9162. if (len == 0 || regex[len - 1] != '$')
  9163. *buffer++ = '$'; // Makes sure full_pattern_ ends with '$'.
  9164. *buffer = '\0';
  9165. }
  9166. #endif // GTEST_USES_POSIX_RE
  9167. const char kUnknownFile[] = "unknown file";
  9168. // Formats a source file path and a line number as they would appear
  9169. // in an error message from the compiler used to compile this code.
  9170. GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) {
  9171. const std::string file_name(file == nullptr ? kUnknownFile : file);
  9172. if (line < 0) {
  9173. return file_name + ":";
  9174. }
  9175. #ifdef _MSC_VER
  9176. return file_name + "(" + StreamableToString(line) + "):";
  9177. #else
  9178. return file_name + ":" + StreamableToString(line) + ":";
  9179. #endif // _MSC_VER
  9180. }
  9181. // Formats a file location for compiler-independent XML output.
  9182. // Although this function is not platform dependent, we put it next to
  9183. // FormatFileLocation in order to contrast the two functions.
  9184. // Note that FormatCompilerIndependentFileLocation() does NOT append colon
  9185. // to the file location it produces, unlike FormatFileLocation().
  9186. GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(
  9187. const char* file, int line) {
  9188. const std::string file_name(file == nullptr ? kUnknownFile : file);
  9189. if (line < 0)
  9190. return file_name;
  9191. else
  9192. return file_name + ":" + StreamableToString(line);
  9193. }
  9194. GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line)
  9195. : severity_(severity) {
  9196. const char* const marker =
  9197. severity == GTEST_INFO ? "[ INFO ]" :
  9198. severity == GTEST_WARNING ? "[WARNING]" :
  9199. severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]";
  9200. GetStream() << ::std::endl << marker << " "
  9201. << FormatFileLocation(file, line).c_str() << ": ";
  9202. }
  9203. // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
  9204. GTestLog::~GTestLog() {
  9205. GetStream() << ::std::endl;
  9206. if (severity_ == GTEST_FATAL) {
  9207. fflush(stderr);
  9208. posix::Abort();
  9209. }
  9210. }
  9211. // Disable Microsoft deprecation warnings for POSIX functions called from
  9212. // this class (creat, dup, dup2, and close)
  9213. GTEST_DISABLE_MSC_DEPRECATED_PUSH_()
  9214. #if GTEST_HAS_STREAM_REDIRECTION
  9215. // Object that captures an output stream (stdout/stderr).
  9216. class CapturedStream {
  9217. public:
  9218. // The ctor redirects the stream to a temporary file.
  9219. explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {
  9220. # if GTEST_OS_WINDOWS
  9221. char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT
  9222. char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT
  9223. ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path);
  9224. const UINT success = ::GetTempFileNameA(temp_dir_path,
  9225. "gtest_redir",
  9226. 0, // Generate unique file name.
  9227. temp_file_path);
  9228. GTEST_CHECK_(success != 0)
  9229. << "Unable to create a temporary file in " << temp_dir_path;
  9230. const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
  9231. GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file "
  9232. << temp_file_path;
  9233. filename_ = temp_file_path;
  9234. # else
  9235. // There's no guarantee that a test has write access to the current
  9236. // directory, so we create the temporary file in the /tmp directory
  9237. // instead. We use /tmp on most systems, and /sdcard on Android.
  9238. // That's because Android doesn't have /tmp.
  9239. # if GTEST_OS_LINUX_ANDROID
  9240. // Note: Android applications are expected to call the framework's
  9241. // Context.getExternalStorageDirectory() method through JNI to get
  9242. // the location of the world-writable SD Card directory. However,
  9243. // this requires a Context handle, which cannot be retrieved
  9244. // globally from native code. Doing so also precludes running the
  9245. // code as part of a regular standalone executable, which doesn't
  9246. // run in a Dalvik process (e.g. when running it through 'adb shell').
  9247. //
  9248. // The location /sdcard is directly accessible from native code
  9249. // and is the only location (unofficially) supported by the Android
  9250. // team. It's generally a symlink to the real SD Card mount point
  9251. // which can be /mnt/sdcard, /mnt/sdcard0, /system/media/sdcard, or
  9252. // other OEM-customized locations. Never rely on these, and always
  9253. // use /sdcard.
  9254. char name_template[] = "/sdcard/gtest_captured_stream.XXXXXX";
  9255. # else
  9256. char name_template[] = "/tmp/captured_stream.XXXXXX";
  9257. # endif // GTEST_OS_LINUX_ANDROID
  9258. const int captured_fd = mkstemp(name_template);
  9259. filename_ = name_template;
  9260. # endif // GTEST_OS_WINDOWS
  9261. fflush(nullptr);
  9262. dup2(captured_fd, fd_);
  9263. close(captured_fd);
  9264. }
  9265. ~CapturedStream() {
  9266. remove(filename_.c_str());
  9267. }
  9268. std::string GetCapturedString() {
  9269. if (uncaptured_fd_ != -1) {
  9270. // Restores the original stream.
  9271. fflush(nullptr);
  9272. dup2(uncaptured_fd_, fd_);
  9273. close(uncaptured_fd_);
  9274. uncaptured_fd_ = -1;
  9275. }
  9276. FILE* const file = posix::FOpen(filename_.c_str(), "r");
  9277. const std::string content = ReadEntireFile(file);
  9278. posix::FClose(file);
  9279. return content;
  9280. }
  9281. private:
  9282. const int fd_; // A stream to capture.
  9283. int uncaptured_fd_;
  9284. // Name of the temporary file holding the stderr output.
  9285. ::std::string filename_;
  9286. GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream);
  9287. };
  9288. GTEST_DISABLE_MSC_DEPRECATED_POP_()
  9289. static CapturedStream* g_captured_stderr = nullptr;
  9290. static CapturedStream* g_captured_stdout = nullptr;
  9291. // Starts capturing an output stream (stdout/stderr).
  9292. static void CaptureStream(int fd, const char* stream_name,
  9293. CapturedStream** stream) {
  9294. if (*stream != nullptr) {
  9295. GTEST_LOG_(FATAL) << "Only one " << stream_name
  9296. << " capturer can exist at a time.";
  9297. }
  9298. *stream = new CapturedStream(fd);
  9299. }
  9300. // Stops capturing the output stream and returns the captured string.
  9301. static std::string GetCapturedStream(CapturedStream** captured_stream) {
  9302. const std::string content = (*captured_stream)->GetCapturedString();
  9303. delete *captured_stream;
  9304. *captured_stream = nullptr;
  9305. return content;
  9306. }
  9307. // Starts capturing stdout.
  9308. void CaptureStdout() {
  9309. CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout);
  9310. }
  9311. // Starts capturing stderr.
  9312. void CaptureStderr() {
  9313. CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr);
  9314. }
  9315. // Stops capturing stdout and returns the captured string.
  9316. std::string GetCapturedStdout() {
  9317. return GetCapturedStream(&g_captured_stdout);
  9318. }
  9319. // Stops capturing stderr and returns the captured string.
  9320. std::string GetCapturedStderr() {
  9321. return GetCapturedStream(&g_captured_stderr);
  9322. }
  9323. #endif // GTEST_HAS_STREAM_REDIRECTION
  9324. size_t GetFileSize(FILE* file) {
  9325. fseek(file, 0, SEEK_END);
  9326. return static_cast<size_t>(ftell(file));
  9327. }
  9328. std::string ReadEntireFile(FILE* file) {
  9329. const size_t file_size = GetFileSize(file);
  9330. char* const buffer = new char[file_size];
  9331. size_t bytes_last_read = 0; // # of bytes read in the last fread()
  9332. size_t bytes_read = 0; // # of bytes read so far
  9333. fseek(file, 0, SEEK_SET);
  9334. // Keeps reading the file until we cannot read further or the
  9335. // pre-determined file size is reached.
  9336. do {
  9337. bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
  9338. bytes_read += bytes_last_read;
  9339. } while (bytes_last_read > 0 && bytes_read < file_size);
  9340. const std::string content(buffer, bytes_read);
  9341. delete[] buffer;
  9342. return content;
  9343. }
  9344. #if GTEST_HAS_DEATH_TEST
  9345. static const std::vector<std::string>* g_injected_test_argvs =
  9346. nullptr; // Owned.
  9347. std::vector<std::string> GetInjectableArgvs() {
  9348. if (g_injected_test_argvs != nullptr) {
  9349. return *g_injected_test_argvs;
  9350. }
  9351. return GetArgvs();
  9352. }
  9353. void SetInjectableArgvs(const std::vector<std::string>* new_argvs) {
  9354. if (g_injected_test_argvs != new_argvs) delete g_injected_test_argvs;
  9355. g_injected_test_argvs = new_argvs;
  9356. }
  9357. void SetInjectableArgvs(const std::vector<std::string>& new_argvs) {
  9358. SetInjectableArgvs(
  9359. new std::vector<std::string>(new_argvs.begin(), new_argvs.end()));
  9360. }
  9361. #if GTEST_HAS_GLOBAL_STRING
  9362. void SetInjectableArgvs(const std::vector< ::string>& new_argvs) {
  9363. SetInjectableArgvs(
  9364. new std::vector<std::string>(new_argvs.begin(), new_argvs.end()));
  9365. }
  9366. #endif // GTEST_HAS_GLOBAL_STRING
  9367. void ClearInjectableArgvs() {
  9368. delete g_injected_test_argvs;
  9369. g_injected_test_argvs = nullptr;
  9370. }
  9371. #endif // GTEST_HAS_DEATH_TEST
  9372. #if GTEST_OS_WINDOWS_MOBILE
  9373. namespace posix {
  9374. void Abort() {
  9375. DebugBreak();
  9376. TerminateProcess(GetCurrentProcess(), 1);
  9377. }
  9378. } // namespace posix
  9379. #endif // GTEST_OS_WINDOWS_MOBILE
  9380. // Returns the name of the environment variable corresponding to the
  9381. // given flag. For example, FlagToEnvVar("foo") will return
  9382. // "GTEST_FOO" in the open-source version.
  9383. static std::string FlagToEnvVar(const char* flag) {
  9384. const std::string full_flag =
  9385. (Message() << GTEST_FLAG_PREFIX_ << flag).GetString();
  9386. Message env_var;
  9387. for (size_t i = 0; i != full_flag.length(); i++) {
  9388. env_var << ToUpper(full_flag.c_str()[i]);
  9389. }
  9390. return env_var.GetString();
  9391. }
  9392. // Parses 'str' for a 32-bit signed integer. If successful, writes
  9393. // the result to *value and returns true; otherwise leaves *value
  9394. // unchanged and returns false.
  9395. bool ParseInt32(const Message& src_text, const char* str, Int32* value) {
  9396. // Parses the environment variable as a decimal integer.
  9397. char* end = nullptr;
  9398. const long long_value = strtol(str, &end, 10); // NOLINT
  9399. // Has strtol() consumed all characters in the string?
  9400. if (*end != '\0') {
  9401. // No - an invalid character was encountered.
  9402. Message msg;
  9403. msg << "WARNING: " << src_text
  9404. << " is expected to be a 32-bit integer, but actually"
  9405. << " has value \"" << str << "\".\n";
  9406. printf("%s", msg.GetString().c_str());
  9407. fflush(stdout);
  9408. return false;
  9409. }
  9410. // Is the parsed value in the range of an Int32?
  9411. const Int32 result = static_cast<Int32>(long_value);
  9412. if (long_value == LONG_MAX || long_value == LONG_MIN ||
  9413. // The parsed value overflows as a long. (strtol() returns
  9414. // LONG_MAX or LONG_MIN when the input overflows.)
  9415. result != long_value
  9416. // The parsed value overflows as an Int32.
  9417. ) {
  9418. Message msg;
  9419. msg << "WARNING: " << src_text
  9420. << " is expected to be a 32-bit integer, but actually"
  9421. << " has value " << str << ", which overflows.\n";
  9422. printf("%s", msg.GetString().c_str());
  9423. fflush(stdout);
  9424. return false;
  9425. }
  9426. *value = result;
  9427. return true;
  9428. }
  9429. // Reads and returns the Boolean environment variable corresponding to
  9430. // the given flag; if it's not set, returns default_value.
  9431. //
  9432. // The value is considered true iff it's not "0".
  9433. bool BoolFromGTestEnv(const char* flag, bool default_value) {
  9434. #if defined(GTEST_GET_BOOL_FROM_ENV_)
  9435. return GTEST_GET_BOOL_FROM_ENV_(flag, default_value);
  9436. #else
  9437. const std::string env_var = FlagToEnvVar(flag);
  9438. const char* const string_value = posix::GetEnv(env_var.c_str());
  9439. return string_value == nullptr ? default_value
  9440. : strcmp(string_value, "0") != 0;
  9441. #endif // defined(GTEST_GET_BOOL_FROM_ENV_)
  9442. }
  9443. // Reads and returns a 32-bit integer stored in the environment
  9444. // variable corresponding to the given flag; if it isn't set or
  9445. // doesn't represent a valid 32-bit integer, returns default_value.
  9446. Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) {
  9447. #if defined(GTEST_GET_INT32_FROM_ENV_)
  9448. return GTEST_GET_INT32_FROM_ENV_(flag, default_value);
  9449. #else
  9450. const std::string env_var = FlagToEnvVar(flag);
  9451. const char* const string_value = posix::GetEnv(env_var.c_str());
  9452. if (string_value == nullptr) {
  9453. // The environment variable is not set.
  9454. return default_value;
  9455. }
  9456. Int32 result = default_value;
  9457. if (!ParseInt32(Message() << "Environment variable " << env_var,
  9458. string_value, &result)) {
  9459. printf("The default value %s is used.\n",
  9460. (Message() << default_value).GetString().c_str());
  9461. fflush(stdout);
  9462. return default_value;
  9463. }
  9464. return result;
  9465. #endif // defined(GTEST_GET_INT32_FROM_ENV_)
  9466. }
  9467. // As a special case for the 'output' flag, if GTEST_OUTPUT is not
  9468. // set, we look for XML_OUTPUT_FILE, which is set by the Bazel build
  9469. // system. The value of XML_OUTPUT_FILE is a filename without the
  9470. // "xml:" prefix of GTEST_OUTPUT.
  9471. // Note that this is meant to be called at the call site so it does
  9472. // not check that the flag is 'output'
  9473. // In essence this checks an env variable called XML_OUTPUT_FILE
  9474. // and if it is set we prepend "xml:" to its value, if it not set we return ""
  9475. std::string OutputFlagAlsoCheckEnvVar(){
  9476. std::string default_value_for_output_flag = "";
  9477. const char* xml_output_file_env = posix::GetEnv("XML_OUTPUT_FILE");
  9478. if (nullptr != xml_output_file_env) {
  9479. default_value_for_output_flag = std::string("xml:") + xml_output_file_env;
  9480. }
  9481. return default_value_for_output_flag;
  9482. }
  9483. // Reads and returns the string environment variable corresponding to
  9484. // the given flag; if it's not set, returns default_value.
  9485. const char* StringFromGTestEnv(const char* flag, const char* default_value) {
  9486. #if defined(GTEST_GET_STRING_FROM_ENV_)
  9487. return GTEST_GET_STRING_FROM_ENV_(flag, default_value);
  9488. #else
  9489. const std::string env_var = FlagToEnvVar(flag);
  9490. const char* const value = posix::GetEnv(env_var.c_str());
  9491. return value == nullptr ? default_value : value;
  9492. #endif // defined(GTEST_GET_STRING_FROM_ENV_)
  9493. }
  9494. } // namespace internal
  9495. } // namespace testing
  9496. // Copyright 2007, Google Inc.
  9497. // All rights reserved.
  9498. //
  9499. // Redistribution and use in source and binary forms, with or without
  9500. // modification, are permitted provided that the following conditions are
  9501. // met:
  9502. //
  9503. // * Redistributions of source code must retain the above copyright
  9504. // notice, this list of conditions and the following disclaimer.
  9505. // * Redistributions in binary form must reproduce the above
  9506. // copyright notice, this list of conditions and the following disclaimer
  9507. // in the documentation and/or other materials provided with the
  9508. // distribution.
  9509. // * Neither the name of Google Inc. nor the names of its
  9510. // contributors may be used to endorse or promote products derived from
  9511. // this software without specific prior written permission.
  9512. //
  9513. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  9514. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  9515. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  9516. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  9517. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  9518. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  9519. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  9520. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  9521. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  9522. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  9523. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  9524. // Google Test - The Google C++ Testing and Mocking Framework
  9525. //
  9526. // This file implements a universal value printer that can print a
  9527. // value of any type T:
  9528. //
  9529. // void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);
  9530. //
  9531. // It uses the << operator when possible, and prints the bytes in the
  9532. // object otherwise. A user can override its behavior for a class
  9533. // type Foo by defining either operator<<(::std::ostream&, const Foo&)
  9534. // or void PrintTo(const Foo&, ::std::ostream*) in the namespace that
  9535. // defines Foo.
  9536. #include <stdio.h>
  9537. #include <cctype>
  9538. #include <cwchar>
  9539. #include <ostream> // NOLINT
  9540. #include <string>
  9541. namespace testing {
  9542. namespace {
  9543. using ::std::ostream;
  9544. // Prints a segment of bytes in the given object.
  9545. GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
  9546. GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
  9547. GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
  9548. void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start,
  9549. size_t count, ostream* os) {
  9550. char text[5] = "";
  9551. for (size_t i = 0; i != count; i++) {
  9552. const size_t j = start + i;
  9553. if (i != 0) {
  9554. // Organizes the bytes into groups of 2 for easy parsing by
  9555. // human.
  9556. if ((j % 2) == 0)
  9557. *os << ' ';
  9558. else
  9559. *os << '-';
  9560. }
  9561. GTEST_SNPRINTF_(text, sizeof(text), "%02X", obj_bytes[j]);
  9562. *os << text;
  9563. }
  9564. }
  9565. // Prints the bytes in the given value to the given ostream.
  9566. void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count,
  9567. ostream* os) {
  9568. // Tells the user how big the object is.
  9569. *os << count << "-byte object <";
  9570. const size_t kThreshold = 132;
  9571. const size_t kChunkSize = 64;
  9572. // If the object size is bigger than kThreshold, we'll have to omit
  9573. // some details by printing only the first and the last kChunkSize
  9574. // bytes.
  9575. if (count < kThreshold) {
  9576. PrintByteSegmentInObjectTo(obj_bytes, 0, count, os);
  9577. } else {
  9578. PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os);
  9579. *os << " ... ";
  9580. // Rounds up to 2-byte boundary.
  9581. const size_t resume_pos = (count - kChunkSize + 1)/2*2;
  9582. PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os);
  9583. }
  9584. *os << ">";
  9585. }
  9586. } // namespace
  9587. namespace internal2 {
  9588. // Delegates to PrintBytesInObjectToImpl() to print the bytes in the
  9589. // given object. The delegation simplifies the implementation, which
  9590. // uses the << operator and thus is easier done outside of the
  9591. // ::testing::internal namespace, which contains a << operator that
  9592. // sometimes conflicts with the one in STL.
  9593. void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count,
  9594. ostream* os) {
  9595. PrintBytesInObjectToImpl(obj_bytes, count, os);
  9596. }
  9597. } // namespace internal2
  9598. namespace internal {
  9599. // Depending on the value of a char (or wchar_t), we print it in one
  9600. // of three formats:
  9601. // - as is if it's a printable ASCII (e.g. 'a', '2', ' '),
  9602. // - as a hexadecimal escape sequence (e.g. '\x7F'), or
  9603. // - as a special escape sequence (e.g. '\r', '\n').
  9604. enum CharFormat {
  9605. kAsIs,
  9606. kHexEscape,
  9607. kSpecialEscape
  9608. };
  9609. // Returns true if c is a printable ASCII character. We test the
  9610. // value of c directly instead of calling isprint(), which is buggy on
  9611. // Windows Mobile.
  9612. inline bool IsPrintableAscii(wchar_t c) {
  9613. return 0x20 <= c && c <= 0x7E;
  9614. }
  9615. // Prints a wide or narrow char c as a character literal without the
  9616. // quotes, escaping it when necessary; returns how c was formatted.
  9617. // The template argument UnsignedChar is the unsigned version of Char,
  9618. // which is the type of c.
  9619. template <typename UnsignedChar, typename Char>
  9620. static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {
  9621. switch (static_cast<wchar_t>(c)) {
  9622. case L'\0':
  9623. *os << "\\0";
  9624. break;
  9625. case L'\'':
  9626. *os << "\\'";
  9627. break;
  9628. case L'\\':
  9629. *os << "\\\\";
  9630. break;
  9631. case L'\a':
  9632. *os << "\\a";
  9633. break;
  9634. case L'\b':
  9635. *os << "\\b";
  9636. break;
  9637. case L'\f':
  9638. *os << "\\f";
  9639. break;
  9640. case L'\n':
  9641. *os << "\\n";
  9642. break;
  9643. case L'\r':
  9644. *os << "\\r";
  9645. break;
  9646. case L'\t':
  9647. *os << "\\t";
  9648. break;
  9649. case L'\v':
  9650. *os << "\\v";
  9651. break;
  9652. default:
  9653. if (IsPrintableAscii(c)) {
  9654. *os << static_cast<char>(c);
  9655. return kAsIs;
  9656. } else {
  9657. ostream::fmtflags flags = os->flags();
  9658. *os << "\\x" << std::hex << std::uppercase
  9659. << static_cast<int>(static_cast<UnsignedChar>(c));
  9660. os->flags(flags);
  9661. return kHexEscape;
  9662. }
  9663. }
  9664. return kSpecialEscape;
  9665. }
  9666. // Prints a wchar_t c as if it's part of a string literal, escaping it when
  9667. // necessary; returns how c was formatted.
  9668. static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) {
  9669. switch (c) {
  9670. case L'\'':
  9671. *os << "'";
  9672. return kAsIs;
  9673. case L'"':
  9674. *os << "\\\"";
  9675. return kSpecialEscape;
  9676. default:
  9677. return PrintAsCharLiteralTo<wchar_t>(c, os);
  9678. }
  9679. }
  9680. // Prints a char c as if it's part of a string literal, escaping it when
  9681. // necessary; returns how c was formatted.
  9682. static CharFormat PrintAsStringLiteralTo(char c, ostream* os) {
  9683. return PrintAsStringLiteralTo(
  9684. static_cast<wchar_t>(static_cast<unsigned char>(c)), os);
  9685. }
  9686. // Prints a wide or narrow character c and its code. '\0' is printed
  9687. // as "'\\0'", other unprintable characters are also properly escaped
  9688. // using the standard C++ escape sequence. The template argument
  9689. // UnsignedChar is the unsigned version of Char, which is the type of c.
  9690. template <typename UnsignedChar, typename Char>
  9691. void PrintCharAndCodeTo(Char c, ostream* os) {
  9692. // First, print c as a literal in the most readable form we can find.
  9693. *os << ((sizeof(c) > 1) ? "L'" : "'");
  9694. const CharFormat format = PrintAsCharLiteralTo<UnsignedChar>(c, os);
  9695. *os << "'";
  9696. // To aid user debugging, we also print c's code in decimal, unless
  9697. // it's 0 (in which case c was printed as '\\0', making the code
  9698. // obvious).
  9699. if (c == 0)
  9700. return;
  9701. *os << " (" << static_cast<int>(c);
  9702. // For more convenience, we print c's code again in hexadecimal,
  9703. // unless c was already printed in the form '\x##' or the code is in
  9704. // [1, 9].
  9705. if (format == kHexEscape || (1 <= c && c <= 9)) {
  9706. // Do nothing.
  9707. } else {
  9708. *os << ", 0x" << String::FormatHexInt(static_cast<UnsignedChar>(c));
  9709. }
  9710. *os << ")";
  9711. }
  9712. void PrintTo(unsigned char c, ::std::ostream* os) {
  9713. PrintCharAndCodeTo<unsigned char>(c, os);
  9714. }
  9715. void PrintTo(signed char c, ::std::ostream* os) {
  9716. PrintCharAndCodeTo<unsigned char>(c, os);
  9717. }
  9718. // Prints a wchar_t as a symbol if it is printable or as its internal
  9719. // code otherwise and also as its code. L'\0' is printed as "L'\\0'".
  9720. void PrintTo(wchar_t wc, ostream* os) {
  9721. PrintCharAndCodeTo<wchar_t>(wc, os);
  9722. }
  9723. // Prints the given array of characters to the ostream. CharType must be either
  9724. // char or wchar_t.
  9725. // The array starts at begin, the length is len, it may include '\0' characters
  9726. // and may not be NUL-terminated.
  9727. template <typename CharType>
  9728. GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
  9729. GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
  9730. GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
  9731. static CharFormat PrintCharsAsStringTo(
  9732. const CharType* begin, size_t len, ostream* os) {
  9733. const char* const kQuoteBegin = sizeof(CharType) == 1 ? "\"" : "L\"";
  9734. *os << kQuoteBegin;
  9735. bool is_previous_hex = false;
  9736. CharFormat print_format = kAsIs;
  9737. for (size_t index = 0; index < len; ++index) {
  9738. const CharType cur = begin[index];
  9739. if (is_previous_hex && IsXDigit(cur)) {
  9740. // Previous character is of '\x..' form and this character can be
  9741. // interpreted as another hexadecimal digit in its number. Break string to
  9742. // disambiguate.
  9743. *os << "\" " << kQuoteBegin;
  9744. }
  9745. is_previous_hex = PrintAsStringLiteralTo(cur, os) == kHexEscape;
  9746. // Remember if any characters required hex escaping.
  9747. if (is_previous_hex) {
  9748. print_format = kHexEscape;
  9749. }
  9750. }
  9751. *os << "\"";
  9752. return print_format;
  9753. }
  9754. // Prints a (const) char/wchar_t array of 'len' elements, starting at address
  9755. // 'begin'. CharType must be either char or wchar_t.
  9756. template <typename CharType>
  9757. GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
  9758. GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
  9759. GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
  9760. static void UniversalPrintCharArray(
  9761. const CharType* begin, size_t len, ostream* os) {
  9762. // The code
  9763. // const char kFoo[] = "foo";
  9764. // generates an array of 4, not 3, elements, with the last one being '\0'.
  9765. //
  9766. // Therefore when printing a char array, we don't print the last element if
  9767. // it's '\0', such that the output matches the string literal as it's
  9768. // written in the source code.
  9769. if (len > 0 && begin[len - 1] == '\0') {
  9770. PrintCharsAsStringTo(begin, len - 1, os);
  9771. return;
  9772. }
  9773. // If, however, the last element in the array is not '\0', e.g.
  9774. // const char kFoo[] = { 'f', 'o', 'o' };
  9775. // we must print the entire array. We also print a message to indicate
  9776. // that the array is not NUL-terminated.
  9777. PrintCharsAsStringTo(begin, len, os);
  9778. *os << " (no terminating NUL)";
  9779. }
  9780. // Prints a (const) char array of 'len' elements, starting at address 'begin'.
  9781. void UniversalPrintArray(const char* begin, size_t len, ostream* os) {
  9782. UniversalPrintCharArray(begin, len, os);
  9783. }
  9784. // Prints a (const) wchar_t array of 'len' elements, starting at address
  9785. // 'begin'.
  9786. void UniversalPrintArray(const wchar_t* begin, size_t len, ostream* os) {
  9787. UniversalPrintCharArray(begin, len, os);
  9788. }
  9789. // Prints the given C string to the ostream.
  9790. void PrintTo(const char* s, ostream* os) {
  9791. if (s == nullptr) {
  9792. *os << "NULL";
  9793. } else {
  9794. *os << ImplicitCast_<const void*>(s) << " pointing to ";
  9795. PrintCharsAsStringTo(s, strlen(s), os);
  9796. }
  9797. }
  9798. // MSVC compiler can be configured to define whar_t as a typedef
  9799. // of unsigned short. Defining an overload for const wchar_t* in that case
  9800. // would cause pointers to unsigned shorts be printed as wide strings,
  9801. // possibly accessing more memory than intended and causing invalid
  9802. // memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when
  9803. // wchar_t is implemented as a native type.
  9804. #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
  9805. // Prints the given wide C string to the ostream.
  9806. void PrintTo(const wchar_t* s, ostream* os) {
  9807. if (s == nullptr) {
  9808. *os << "NULL";
  9809. } else {
  9810. *os << ImplicitCast_<const void*>(s) << " pointing to ";
  9811. PrintCharsAsStringTo(s, wcslen(s), os);
  9812. }
  9813. }
  9814. #endif // wchar_t is native
  9815. namespace {
  9816. bool ContainsUnprintableControlCodes(const char* str, size_t length) {
  9817. const unsigned char *s = reinterpret_cast<const unsigned char *>(str);
  9818. for (size_t i = 0; i < length; i++) {
  9819. unsigned char ch = *s++;
  9820. if (std::iscntrl(ch)) {
  9821. switch (ch) {
  9822. case '\t':
  9823. case '\n':
  9824. case '\r':
  9825. break;
  9826. default:
  9827. return true;
  9828. }
  9829. }
  9830. }
  9831. return false;
  9832. }
  9833. bool IsUTF8TrailByte(unsigned char t) { return 0x80 <= t && t<= 0xbf; }
  9834. bool IsValidUTF8(const char* str, size_t length) {
  9835. const unsigned char *s = reinterpret_cast<const unsigned char *>(str);
  9836. for (size_t i = 0; i < length;) {
  9837. unsigned char lead = s[i++];
  9838. if (lead <= 0x7f) {
  9839. continue; // single-byte character (ASCII) 0..7F
  9840. }
  9841. if (lead < 0xc2) {
  9842. return false; // trail byte or non-shortest form
  9843. } else if (lead <= 0xdf && (i + 1) <= length && IsUTF8TrailByte(s[i])) {
  9844. ++i; // 2-byte character
  9845. } else if (0xe0 <= lead && lead <= 0xef && (i + 2) <= length &&
  9846. IsUTF8TrailByte(s[i]) &&
  9847. IsUTF8TrailByte(s[i + 1]) &&
  9848. // check for non-shortest form and surrogate
  9849. (lead != 0xe0 || s[i] >= 0xa0) &&
  9850. (lead != 0xed || s[i] < 0xa0)) {
  9851. i += 2; // 3-byte character
  9852. } else if (0xf0 <= lead && lead <= 0xf4 && (i + 3) <= length &&
  9853. IsUTF8TrailByte(s[i]) &&
  9854. IsUTF8TrailByte(s[i + 1]) &&
  9855. IsUTF8TrailByte(s[i + 2]) &&
  9856. // check for non-shortest form
  9857. (lead != 0xf0 || s[i] >= 0x90) &&
  9858. (lead != 0xf4 || s[i] < 0x90)) {
  9859. i += 3; // 4-byte character
  9860. } else {
  9861. return false;
  9862. }
  9863. }
  9864. return true;
  9865. }
  9866. void ConditionalPrintAsText(const char* str, size_t length, ostream* os) {
  9867. if (!ContainsUnprintableControlCodes(str, length) &&
  9868. IsValidUTF8(str, length)) {
  9869. *os << "\n As Text: \"" << str << "\"";
  9870. }
  9871. }
  9872. } // anonymous namespace
  9873. // Prints a ::string object.
  9874. #if GTEST_HAS_GLOBAL_STRING
  9875. void PrintStringTo(const ::string& s, ostream* os) {
  9876. if (PrintCharsAsStringTo(s.data(), s.size(), os) == kHexEscape) {
  9877. if (GTEST_FLAG(print_utf8)) {
  9878. ConditionalPrintAsText(s.data(), s.size(), os);
  9879. }
  9880. }
  9881. }
  9882. #endif // GTEST_HAS_GLOBAL_STRING
  9883. void PrintStringTo(const ::std::string& s, ostream* os) {
  9884. if (PrintCharsAsStringTo(s.data(), s.size(), os) == kHexEscape) {
  9885. if (GTEST_FLAG(print_utf8)) {
  9886. ConditionalPrintAsText(s.data(), s.size(), os);
  9887. }
  9888. }
  9889. }
  9890. // Prints a ::wstring object.
  9891. #if GTEST_HAS_GLOBAL_WSTRING
  9892. void PrintWideStringTo(const ::wstring& s, ostream* os) {
  9893. PrintCharsAsStringTo(s.data(), s.size(), os);
  9894. }
  9895. #endif // GTEST_HAS_GLOBAL_WSTRING
  9896. #if GTEST_HAS_STD_WSTRING
  9897. void PrintWideStringTo(const ::std::wstring& s, ostream* os) {
  9898. PrintCharsAsStringTo(s.data(), s.size(), os);
  9899. }
  9900. #endif // GTEST_HAS_STD_WSTRING
  9901. } // namespace internal
  9902. } // namespace testing
  9903. // Copyright 2008, Google Inc.
  9904. // All rights reserved.
  9905. //
  9906. // Redistribution and use in source and binary forms, with or without
  9907. // modification, are permitted provided that the following conditions are
  9908. // met:
  9909. //
  9910. // * Redistributions of source code must retain the above copyright
  9911. // notice, this list of conditions and the following disclaimer.
  9912. // * Redistributions in binary form must reproduce the above
  9913. // copyright notice, this list of conditions and the following disclaimer
  9914. // in the documentation and/or other materials provided with the
  9915. // distribution.
  9916. // * Neither the name of Google Inc. nor the names of its
  9917. // contributors may be used to endorse or promote products derived from
  9918. // this software without specific prior written permission.
  9919. //
  9920. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  9921. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  9922. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  9923. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  9924. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  9925. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  9926. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  9927. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  9928. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  9929. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  9930. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  9931. //
  9932. // The Google C++ Testing and Mocking Framework (Google Test)
  9933. namespace testing {
  9934. using internal::GetUnitTestImpl;
  9935. // Gets the summary of the failure message by omitting the stack trace
  9936. // in it.
  9937. std::string TestPartResult::ExtractSummary(const char* message) {
  9938. const char* const stack_trace = strstr(message, internal::kStackTraceMarker);
  9939. return stack_trace == nullptr ? message : std::string(message, stack_trace);
  9940. }
  9941. // Prints a TestPartResult object.
  9942. std::ostream& operator<<(std::ostream& os, const TestPartResult& result) {
  9943. return os << result.file_name() << ":" << result.line_number() << ": "
  9944. << (result.type() == TestPartResult::kSuccess
  9945. ? "Success"
  9946. : result.type() == TestPartResult::kSkip
  9947. ? "Skipped"
  9948. : result.type() == TestPartResult::kFatalFailure
  9949. ? "Fatal failure"
  9950. : "Non-fatal failure")
  9951. << ":\n"
  9952. << result.message() << std::endl;
  9953. }
  9954. // Appends a TestPartResult to the array.
  9955. void TestPartResultArray::Append(const TestPartResult& result) {
  9956. array_.push_back(result);
  9957. }
  9958. // Returns the TestPartResult at the given index (0-based).
  9959. const TestPartResult& TestPartResultArray::GetTestPartResult(int index) const {
  9960. if (index < 0 || index >= size()) {
  9961. printf("\nInvalid index (%d) into TestPartResultArray.\n", index);
  9962. internal::posix::Abort();
  9963. }
  9964. return array_[index];
  9965. }
  9966. // Returns the number of TestPartResult objects in the array.
  9967. int TestPartResultArray::size() const {
  9968. return static_cast<int>(array_.size());
  9969. }
  9970. namespace internal {
  9971. HasNewFatalFailureHelper::HasNewFatalFailureHelper()
  9972. : has_new_fatal_failure_(false),
  9973. original_reporter_(GetUnitTestImpl()->
  9974. GetTestPartResultReporterForCurrentThread()) {
  9975. GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this);
  9976. }
  9977. HasNewFatalFailureHelper::~HasNewFatalFailureHelper() {
  9978. GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(
  9979. original_reporter_);
  9980. }
  9981. void HasNewFatalFailureHelper::ReportTestPartResult(
  9982. const TestPartResult& result) {
  9983. if (result.fatally_failed())
  9984. has_new_fatal_failure_ = true;
  9985. original_reporter_->ReportTestPartResult(result);
  9986. }
  9987. } // namespace internal
  9988. } // namespace testing
  9989. // Copyright 2008 Google Inc.
  9990. // All Rights Reserved.
  9991. //
  9992. // Redistribution and use in source and binary forms, with or without
  9993. // modification, are permitted provided that the following conditions are
  9994. // met:
  9995. //
  9996. // * Redistributions of source code must retain the above copyright
  9997. // notice, this list of conditions and the following disclaimer.
  9998. // * Redistributions in binary form must reproduce the above
  9999. // copyright notice, this list of conditions and the following disclaimer
  10000. // in the documentation and/or other materials provided with the
  10001. // distribution.
  10002. // * Neither the name of Google Inc. nor the names of its
  10003. // contributors may be used to endorse or promote products derived from
  10004. // this software without specific prior written permission.
  10005. //
  10006. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  10007. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  10008. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  10009. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  10010. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  10011. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  10012. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  10013. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  10014. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  10015. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  10016. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  10017. namespace testing {
  10018. namespace internal {
  10019. #if GTEST_HAS_TYPED_TEST_P
  10020. // Skips to the first non-space char in str. Returns an empty string if str
  10021. // contains only whitespace characters.
  10022. static const char* SkipSpaces(const char* str) {
  10023. while (IsSpace(*str))
  10024. str++;
  10025. return str;
  10026. }
  10027. static std::vector<std::string> SplitIntoTestNames(const char* src) {
  10028. std::vector<std::string> name_vec;
  10029. src = SkipSpaces(src);
  10030. for (; src != nullptr; src = SkipComma(src)) {
  10031. name_vec.push_back(StripTrailingSpaces(GetPrefixUntilComma(src)));
  10032. }
  10033. return name_vec;
  10034. }
  10035. // Verifies that registered_tests match the test names in
  10036. // registered_tests_; returns registered_tests if successful, or
  10037. // aborts the program otherwise.
  10038. const char* TypedTestSuitePState::VerifyRegisteredTestNames(
  10039. const char* file, int line, const char* registered_tests) {
  10040. typedef RegisteredTestsMap::const_iterator RegisteredTestIter;
  10041. registered_ = true;
  10042. std::vector<std::string> name_vec = SplitIntoTestNames(registered_tests);
  10043. Message errors;
  10044. std::set<std::string> tests;
  10045. for (std::vector<std::string>::const_iterator name_it = name_vec.begin();
  10046. name_it != name_vec.end(); ++name_it) {
  10047. const std::string& name = *name_it;
  10048. if (tests.count(name) != 0) {
  10049. errors << "Test " << name << " is listed more than once.\n";
  10050. continue;
  10051. }
  10052. bool found = false;
  10053. for (RegisteredTestIter it = registered_tests_.begin();
  10054. it != registered_tests_.end();
  10055. ++it) {
  10056. if (name == it->first) {
  10057. found = true;
  10058. break;
  10059. }
  10060. }
  10061. if (found) {
  10062. tests.insert(name);
  10063. } else {
  10064. errors << "No test named " << name
  10065. << " can be found in this test suite.\n";
  10066. }
  10067. }
  10068. for (RegisteredTestIter it = registered_tests_.begin();
  10069. it != registered_tests_.end();
  10070. ++it) {
  10071. if (tests.count(it->first) == 0) {
  10072. errors << "You forgot to list test " << it->first << ".\n";
  10073. }
  10074. }
  10075. const std::string& errors_str = errors.GetString();
  10076. if (errors_str != "") {
  10077. fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
  10078. errors_str.c_str());
  10079. fflush(stderr);
  10080. posix::Abort();
  10081. }
  10082. return registered_tests;
  10083. }
  10084. #endif // GTEST_HAS_TYPED_TEST_P
  10085. } // namespace internal
  10086. } // namespace testing