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.

9592 lines
346 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. // Author: mheule@google.com (Markus Heule)
  31. //
  32. // Google C++ Testing Framework (Google Test)
  33. //
  34. // Sometimes it's desirable to build Google Test by compiling a single file.
  35. // This file serves this purpose.
  36. // This line ensures that gtest.h can be compiled on its own, even
  37. // when it's fused.
  38. #include "gtest/gtest.h"
  39. // The following lines pull in the real gtest *.cc files.
  40. // Copyright 2005, Google Inc.
  41. // All rights reserved.
  42. //
  43. // Redistribution and use in source and binary forms, with or without
  44. // modification, are permitted provided that the following conditions are
  45. // met:
  46. //
  47. // * Redistributions of source code must retain the above copyright
  48. // notice, this list of conditions and the following disclaimer.
  49. // * Redistributions in binary form must reproduce the above
  50. // copyright notice, this list of conditions and the following disclaimer
  51. // in the documentation and/or other materials provided with the
  52. // distribution.
  53. // * Neither the name of Google Inc. nor the names of its
  54. // contributors may be used to endorse or promote products derived from
  55. // this software without specific prior written permission.
  56. //
  57. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  58. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  59. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  60. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  61. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  62. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  63. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  64. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  65. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  66. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  67. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  68. //
  69. // Author: wan@google.com (Zhanyong Wan)
  70. //
  71. // The Google C++ Testing Framework (Google Test)
  72. // Copyright 2007, Google Inc.
  73. // All rights reserved.
  74. //
  75. // Redistribution and use in source and binary forms, with or without
  76. // modification, are permitted provided that the following conditions are
  77. // met:
  78. //
  79. // * Redistributions of source code must retain the above copyright
  80. // notice, this list of conditions and the following disclaimer.
  81. // * Redistributions in binary form must reproduce the above
  82. // copyright notice, this list of conditions and the following disclaimer
  83. // in the documentation and/or other materials provided with the
  84. // distribution.
  85. // * Neither the name of Google Inc. nor the names of its
  86. // contributors may be used to endorse or promote products derived from
  87. // this software without specific prior written permission.
  88. //
  89. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  90. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  91. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  92. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  93. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  94. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  95. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  96. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  97. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  98. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  99. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  100. //
  101. // Author: wan@google.com (Zhanyong Wan)
  102. //
  103. // Utilities for testing Google Test itself and code that uses Google Test
  104. // (e.g. frameworks built on top of Google Test).
  105. #ifndef GTEST_INCLUDE_GTEST_GTEST_SPI_H_
  106. #define GTEST_INCLUDE_GTEST_GTEST_SPI_H_
  107. namespace testing {
  108. // This helper class can be used to mock out Google Test failure reporting
  109. // so that we can test Google Test or code that builds on Google Test.
  110. //
  111. // An object of this class appends a TestPartResult object to the
  112. // TestPartResultArray object given in the constructor whenever a Google Test
  113. // failure is reported. It can either intercept only failures that are
  114. // generated in the same thread that created this object or it can intercept
  115. // all generated failures. The scope of this mock object can be controlled with
  116. // the second argument to the two arguments constructor.
  117. class GTEST_API_ ScopedFakeTestPartResultReporter
  118. : public TestPartResultReporterInterface {
  119. public:
  120. // The two possible mocking modes of this object.
  121. enum InterceptMode {
  122. INTERCEPT_ONLY_CURRENT_THREAD, // Intercepts only thread local failures.
  123. INTERCEPT_ALL_THREADS // Intercepts all failures.
  124. };
  125. // The c'tor sets this object as the test part result reporter used
  126. // by Google Test. The 'result' parameter specifies where to report the
  127. // results. This reporter will only catch failures generated in the current
  128. // thread. DEPRECATED
  129. explicit ScopedFakeTestPartResultReporter(TestPartResultArray* result);
  130. // Same as above, but you can choose the interception scope of this object.
  131. ScopedFakeTestPartResultReporter(InterceptMode intercept_mode,
  132. TestPartResultArray* result);
  133. // The d'tor restores the previous test part result reporter.
  134. virtual ~ScopedFakeTestPartResultReporter();
  135. // Appends the TestPartResult object to the TestPartResultArray
  136. // received in the constructor.
  137. //
  138. // This method is from the TestPartResultReporterInterface
  139. // interface.
  140. virtual void ReportTestPartResult(const TestPartResult& result);
  141. private:
  142. void Init();
  143. const InterceptMode intercept_mode_;
  144. TestPartResultReporterInterface* old_reporter_;
  145. TestPartResultArray* const result_;
  146. GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedFakeTestPartResultReporter);
  147. };
  148. namespace internal {
  149. // A helper class for implementing EXPECT_FATAL_FAILURE() and
  150. // EXPECT_NONFATAL_FAILURE(). Its destructor verifies that the given
  151. // TestPartResultArray contains exactly one failure that has the given
  152. // type and contains the given substring. If that's not the case, a
  153. // non-fatal failure will be generated.
  154. class GTEST_API_ SingleFailureChecker {
  155. public:
  156. // The constructor remembers the arguments.
  157. SingleFailureChecker(const TestPartResultArray* results,
  158. TestPartResult::Type type,
  159. const string& substr);
  160. ~SingleFailureChecker();
  161. private:
  162. const TestPartResultArray* const results_;
  163. const TestPartResult::Type type_;
  164. const string substr_;
  165. GTEST_DISALLOW_COPY_AND_ASSIGN_(SingleFailureChecker);
  166. };
  167. } // namespace internal
  168. } // namespace testing
  169. // A set of macros for testing Google Test assertions or code that's expected
  170. // to generate Google Test fatal failures. It verifies that the given
  171. // statement will cause exactly one fatal Google Test failure with 'substr'
  172. // being part of the failure message.
  173. //
  174. // There are two different versions of this macro. EXPECT_FATAL_FAILURE only
  175. // affects and considers failures generated in the current thread and
  176. // EXPECT_FATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
  177. //
  178. // The verification of the assertion is done correctly even when the statement
  179. // throws an exception or aborts the current function.
  180. //
  181. // Known restrictions:
  182. // - 'statement' cannot reference local non-static variables or
  183. // non-static members of the current object.
  184. // - 'statement' cannot return a value.
  185. // - You cannot stream a failure message to this macro.
  186. //
  187. // Note that even though the implementations of the following two
  188. // macros are much alike, we cannot refactor them to use a common
  189. // helper macro, due to some peculiarity in how the preprocessor
  190. // works. The AcceptsMacroThatExpandsToUnprotectedComma test in
  191. // gtest_unittest.cc will fail to compile if we do that.
  192. #define EXPECT_FATAL_FAILURE(statement, substr) \
  193. do { \
  194. class GTestExpectFatalFailureHelper {\
  195. public:\
  196. static void Execute() { statement; }\
  197. };\
  198. ::testing::TestPartResultArray gtest_failures;\
  199. ::testing::internal::SingleFailureChecker gtest_checker(\
  200. &gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
  201. {\
  202. ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
  203. ::testing::ScopedFakeTestPartResultReporter:: \
  204. INTERCEPT_ONLY_CURRENT_THREAD, &gtest_failures);\
  205. GTestExpectFatalFailureHelper::Execute();\
  206. }\
  207. } while (::testing::internal::AlwaysFalse())
  208. #define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
  209. do { \
  210. class GTestExpectFatalFailureHelper {\
  211. public:\
  212. static void Execute() { statement; }\
  213. };\
  214. ::testing::TestPartResultArray gtest_failures;\
  215. ::testing::internal::SingleFailureChecker gtest_checker(\
  216. &gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
  217. {\
  218. ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
  219. ::testing::ScopedFakeTestPartResultReporter:: \
  220. INTERCEPT_ALL_THREADS, &gtest_failures);\
  221. GTestExpectFatalFailureHelper::Execute();\
  222. }\
  223. } while (::testing::internal::AlwaysFalse())
  224. // A macro for testing Google Test assertions or code that's expected to
  225. // generate Google Test non-fatal failures. It asserts that the given
  226. // statement will cause exactly one non-fatal Google Test failure with 'substr'
  227. // being part of the failure message.
  228. //
  229. // There are two different versions of this macro. EXPECT_NONFATAL_FAILURE only
  230. // affects and considers failures generated in the current thread and
  231. // EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
  232. //
  233. // 'statement' is allowed to reference local variables and members of
  234. // the current object.
  235. //
  236. // The verification of the assertion is done correctly even when the statement
  237. // throws an exception or aborts the current function.
  238. //
  239. // Known restrictions:
  240. // - You cannot stream a failure message to this macro.
  241. //
  242. // Note that even though the implementations of the following two
  243. // macros are much alike, we cannot refactor them to use a common
  244. // helper macro, due to some peculiarity in how the preprocessor
  245. // works. If we do that, the code won't compile when the user gives
  246. // EXPECT_NONFATAL_FAILURE() a statement that contains a macro that
  247. // expands to code containing an unprotected comma. The
  248. // AcceptsMacroThatExpandsToUnprotectedComma test in gtest_unittest.cc
  249. // catches that.
  250. //
  251. // For the same reason, we have to write
  252. // if (::testing::internal::AlwaysTrue()) { statement; }
  253. // instead of
  254. // GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)
  255. // to avoid an MSVC warning on unreachable code.
  256. #define EXPECT_NONFATAL_FAILURE(statement, substr) \
  257. do {\
  258. ::testing::TestPartResultArray gtest_failures;\
  259. ::testing::internal::SingleFailureChecker gtest_checker(\
  260. &gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \
  261. (substr));\
  262. {\
  263. ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
  264. ::testing::ScopedFakeTestPartResultReporter:: \
  265. INTERCEPT_ONLY_CURRENT_THREAD, &gtest_failures);\
  266. if (::testing::internal::AlwaysTrue()) { statement; }\
  267. }\
  268. } while (::testing::internal::AlwaysFalse())
  269. #define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
  270. do {\
  271. ::testing::TestPartResultArray gtest_failures;\
  272. ::testing::internal::SingleFailureChecker gtest_checker(\
  273. &gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \
  274. (substr));\
  275. {\
  276. ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
  277. ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \
  278. &gtest_failures);\
  279. if (::testing::internal::AlwaysTrue()) { statement; }\
  280. }\
  281. } while (::testing::internal::AlwaysFalse())
  282. #endif // GTEST_INCLUDE_GTEST_GTEST_SPI_H_
  283. #include <ctype.h>
  284. #include <math.h>
  285. #include <stdarg.h>
  286. #include <stdio.h>
  287. #include <stdlib.h>
  288. #include <time.h>
  289. #include <wchar.h>
  290. #include <wctype.h>
  291. #include <algorithm>
  292. #include <iomanip>
  293. #include <limits>
  294. #include <ostream> // NOLINT
  295. #include <sstream>
  296. #include <vector>
  297. #if GTEST_OS_LINUX
  298. // TODO(kenton@google.com): Use autoconf to detect availability of
  299. // gettimeofday().
  300. # define GTEST_HAS_GETTIMEOFDAY_ 1
  301. # include <fcntl.h> // NOLINT
  302. # include <limits.h> // NOLINT
  303. # include <sched.h> // NOLINT
  304. // Declares vsnprintf(). This header is not available on Windows.
  305. # include <strings.h> // NOLINT
  306. # include <sys/mman.h> // NOLINT
  307. # include <sys/time.h> // NOLINT
  308. # include <unistd.h> // NOLINT
  309. # include <string>
  310. #elif GTEST_OS_SYMBIAN
  311. # define GTEST_HAS_GETTIMEOFDAY_ 1
  312. # include <sys/time.h> // NOLINT
  313. #elif GTEST_OS_ZOS
  314. # define GTEST_HAS_GETTIMEOFDAY_ 1
  315. # include <sys/time.h> // NOLINT
  316. // On z/OS we additionally need strings.h for strcasecmp.
  317. # include <strings.h> // NOLINT
  318. #elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE.
  319. # include <windows.h> // NOLINT
  320. #elif GTEST_OS_WINDOWS // We are on Windows proper.
  321. # include <io.h> // NOLINT
  322. # include <sys/timeb.h> // NOLINT
  323. # include <sys/types.h> // NOLINT
  324. # include <sys/stat.h> // NOLINT
  325. # if GTEST_OS_WINDOWS_MINGW
  326. // MinGW has gettimeofday() but not _ftime64().
  327. // TODO(kenton@google.com): Use autoconf to detect availability of
  328. // gettimeofday().
  329. // TODO(kenton@google.com): There are other ways to get the time on
  330. // Windows, like GetTickCount() or GetSystemTimeAsFileTime(). MinGW
  331. // supports these. consider using them instead.
  332. # define GTEST_HAS_GETTIMEOFDAY_ 1
  333. # include <sys/time.h> // NOLINT
  334. # endif // GTEST_OS_WINDOWS_MINGW
  335. // cpplint thinks that the header is already included, so we want to
  336. // silence it.
  337. # include <windows.h> // NOLINT
  338. #else
  339. // Assume other platforms have gettimeofday().
  340. // TODO(kenton@google.com): Use autoconf to detect availability of
  341. // gettimeofday().
  342. # define GTEST_HAS_GETTIMEOFDAY_ 1
  343. // cpplint thinks that the header is already included, so we want to
  344. // silence it.
  345. # include <sys/time.h> // NOLINT
  346. # include <unistd.h> // NOLINT
  347. #endif // GTEST_OS_LINUX
  348. #if GTEST_HAS_EXCEPTIONS
  349. # include <stdexcept>
  350. #endif
  351. #if GTEST_CAN_STREAM_RESULTS_
  352. # include <arpa/inet.h> // NOLINT
  353. # include <netdb.h> // NOLINT
  354. #endif
  355. // Indicates that this translation unit is part of Google Test's
  356. // implementation. It must come before gtest-internal-inl.h is
  357. // included, or there will be a compiler error. This trick is to
  358. // prevent a user from accidentally including gtest-internal-inl.h in
  359. // his code.
  360. #define GTEST_IMPLEMENTATION_ 1
  361. // Copyright 2005, Google Inc.
  362. // All rights reserved.
  363. //
  364. // Redistribution and use in source and binary forms, with or without
  365. // modification, are permitted provided that the following conditions are
  366. // met:
  367. //
  368. // * Redistributions of source code must retain the above copyright
  369. // notice, this list of conditions and the following disclaimer.
  370. // * Redistributions in binary form must reproduce the above
  371. // copyright notice, this list of conditions and the following disclaimer
  372. // in the documentation and/or other materials provided with the
  373. // distribution.
  374. // * Neither the name of Google Inc. nor the names of its
  375. // contributors may be used to endorse or promote products derived from
  376. // this software without specific prior written permission.
  377. //
  378. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  379. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  380. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  381. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  382. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  383. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  384. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  385. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  386. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  387. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  388. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  389. // Utility functions and classes used by the Google C++ testing framework.
  390. //
  391. // Author: wan@google.com (Zhanyong Wan)
  392. //
  393. // This file contains purely Google Test's internal implementation. Please
  394. // DO NOT #INCLUDE IT IN A USER PROGRAM.
  395. #ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_
  396. #define GTEST_SRC_GTEST_INTERNAL_INL_H_
  397. // GTEST_IMPLEMENTATION_ is defined to 1 iff the current translation unit is
  398. // part of Google Test's implementation; otherwise it's undefined.
  399. #if !GTEST_IMPLEMENTATION_
  400. // A user is trying to include this from his code - just say no.
  401. # error "gtest-internal-inl.h is part of Google Test's internal implementation."
  402. # error "It must not be included except by Google Test itself."
  403. #endif // GTEST_IMPLEMENTATION_
  404. #ifndef _WIN32_WCE
  405. # include <errno.h>
  406. #endif // !_WIN32_WCE
  407. #include <stddef.h>
  408. #include <stdlib.h> // For strtoll/_strtoul64/malloc/free.
  409. #include <string.h> // For memmove.
  410. #include <algorithm>
  411. #include <string>
  412. #include <vector>
  413. #if GTEST_CAN_STREAM_RESULTS_
  414. # include <arpa/inet.h> // NOLINT
  415. # include <netdb.h> // NOLINT
  416. #endif
  417. #if GTEST_OS_WINDOWS
  418. # include <windows.h> // NOLINT
  419. #endif // GTEST_OS_WINDOWS
  420. namespace testing {
  421. // Declares the flags.
  422. //
  423. // We don't want the users to modify this flag in the code, but want
  424. // Google Test's own unit tests to be able to access it. Therefore we
  425. // declare it here as opposed to in gtest.h.
  426. GTEST_DECLARE_bool_(death_test_use_fork);
  427. namespace internal {
  428. // The value of GetTestTypeId() as seen from within the Google Test
  429. // library. This is solely for testing GetTestTypeId().
  430. GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest;
  431. // Names of the flags (needed for parsing Google Test flags).
  432. const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests";
  433. const char kBreakOnFailureFlag[] = "break_on_failure";
  434. const char kCatchExceptionsFlag[] = "catch_exceptions";
  435. const char kColorFlag[] = "color";
  436. const char kFilterFlag[] = "filter";
  437. const char kListTestsFlag[] = "list_tests";
  438. const char kOutputFlag[] = "output";
  439. const char kPrintTimeFlag[] = "print_time";
  440. const char kRandomSeedFlag[] = "random_seed";
  441. const char kRepeatFlag[] = "repeat";
  442. const char kShuffleFlag[] = "shuffle";
  443. const char kStackTraceDepthFlag[] = "stack_trace_depth";
  444. const char kStreamResultToFlag[] = "stream_result_to";
  445. const char kThrowOnFailureFlag[] = "throw_on_failure";
  446. // A valid random seed must be in [1, kMaxRandomSeed].
  447. const int kMaxRandomSeed = 99999;
  448. // g_help_flag is true iff the --help flag or an equivalent form is
  449. // specified on the command line.
  450. GTEST_API_ extern bool g_help_flag;
  451. // Returns the current time in milliseconds.
  452. GTEST_API_ TimeInMillis GetTimeInMillis();
  453. // Returns true iff Google Test should use colors in the output.
  454. GTEST_API_ bool ShouldUseColor(bool stdout_is_tty);
  455. // Formats the given time in milliseconds as seconds.
  456. GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms);
  457. // Converts the given time in milliseconds to a date string in the ISO 8601
  458. // format, without the timezone information. N.B.: due to the use the
  459. // non-reentrant localtime() function, this function is not thread safe. Do
  460. // not use it in any code that can be called from multiple threads.
  461. GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms);
  462. // Parses a string for an Int32 flag, in the form of "--flag=value".
  463. //
  464. // On success, stores the value of the flag in *value, and returns
  465. // true. On failure, returns false without changing *value.
  466. GTEST_API_ bool ParseInt32Flag(
  467. const char* str, const char* flag, Int32* value);
  468. // Returns a random seed in range [1, kMaxRandomSeed] based on the
  469. // given --gtest_random_seed flag value.
  470. inline int GetRandomSeedFromFlag(Int32 random_seed_flag) {
  471. const unsigned int raw_seed = (random_seed_flag == 0) ?
  472. static_cast<unsigned int>(GetTimeInMillis()) :
  473. static_cast<unsigned int>(random_seed_flag);
  474. // Normalizes the actual seed to range [1, kMaxRandomSeed] such that
  475. // it's easy to type.
  476. const int normalized_seed =
  477. static_cast<int>((raw_seed - 1U) %
  478. static_cast<unsigned int>(kMaxRandomSeed)) + 1;
  479. return normalized_seed;
  480. }
  481. // Returns the first valid random seed after 'seed'. The behavior is
  482. // undefined if 'seed' is invalid. The seed after kMaxRandomSeed is
  483. // considered to be 1.
  484. inline int GetNextRandomSeed(int seed) {
  485. GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed)
  486. << "Invalid random seed " << seed << " - must be in [1, "
  487. << kMaxRandomSeed << "].";
  488. const int next_seed = seed + 1;
  489. return (next_seed > kMaxRandomSeed) ? 1 : next_seed;
  490. }
  491. // This class saves the values of all Google Test flags in its c'tor, and
  492. // restores them in its d'tor.
  493. class GTestFlagSaver {
  494. public:
  495. // The c'tor.
  496. GTestFlagSaver() {
  497. also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests);
  498. break_on_failure_ = GTEST_FLAG(break_on_failure);
  499. catch_exceptions_ = GTEST_FLAG(catch_exceptions);
  500. color_ = GTEST_FLAG(color);
  501. death_test_style_ = GTEST_FLAG(death_test_style);
  502. death_test_use_fork_ = GTEST_FLAG(death_test_use_fork);
  503. filter_ = GTEST_FLAG(filter);
  504. internal_run_death_test_ = GTEST_FLAG(internal_run_death_test);
  505. list_tests_ = GTEST_FLAG(list_tests);
  506. output_ = GTEST_FLAG(output);
  507. print_time_ = GTEST_FLAG(print_time);
  508. random_seed_ = GTEST_FLAG(random_seed);
  509. repeat_ = GTEST_FLAG(repeat);
  510. shuffle_ = GTEST_FLAG(shuffle);
  511. stack_trace_depth_ = GTEST_FLAG(stack_trace_depth);
  512. stream_result_to_ = GTEST_FLAG(stream_result_to);
  513. throw_on_failure_ = GTEST_FLAG(throw_on_failure);
  514. }
  515. // The d'tor is not virtual. DO NOT INHERIT FROM THIS CLASS.
  516. ~GTestFlagSaver() {
  517. GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_;
  518. GTEST_FLAG(break_on_failure) = break_on_failure_;
  519. GTEST_FLAG(catch_exceptions) = catch_exceptions_;
  520. GTEST_FLAG(color) = color_;
  521. GTEST_FLAG(death_test_style) = death_test_style_;
  522. GTEST_FLAG(death_test_use_fork) = death_test_use_fork_;
  523. GTEST_FLAG(filter) = filter_;
  524. GTEST_FLAG(internal_run_death_test) = internal_run_death_test_;
  525. GTEST_FLAG(list_tests) = list_tests_;
  526. GTEST_FLAG(output) = output_;
  527. GTEST_FLAG(print_time) = print_time_;
  528. GTEST_FLAG(random_seed) = random_seed_;
  529. GTEST_FLAG(repeat) = repeat_;
  530. GTEST_FLAG(shuffle) = shuffle_;
  531. GTEST_FLAG(stack_trace_depth) = stack_trace_depth_;
  532. GTEST_FLAG(stream_result_to) = stream_result_to_;
  533. GTEST_FLAG(throw_on_failure) = throw_on_failure_;
  534. }
  535. private:
  536. // Fields for saving the original values of flags.
  537. bool also_run_disabled_tests_;
  538. bool break_on_failure_;
  539. bool catch_exceptions_;
  540. std::string color_;
  541. std::string death_test_style_;
  542. bool death_test_use_fork_;
  543. std::string filter_;
  544. std::string internal_run_death_test_;
  545. bool list_tests_;
  546. std::string output_;
  547. bool print_time_;
  548. internal::Int32 random_seed_;
  549. internal::Int32 repeat_;
  550. bool shuffle_;
  551. internal::Int32 stack_trace_depth_;
  552. std::string stream_result_to_;
  553. bool throw_on_failure_;
  554. } GTEST_ATTRIBUTE_UNUSED_;
  555. // Converts a Unicode code point to a narrow string in UTF-8 encoding.
  556. // code_point parameter is of type UInt32 because wchar_t may not be
  557. // wide enough to contain a code point.
  558. // If the code_point is not a valid Unicode code point
  559. // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
  560. // to "(Invalid Unicode 0xXXXXXXXX)".
  561. GTEST_API_ std::string CodePointToUtf8(UInt32 code_point);
  562. // Converts a wide string to a narrow string in UTF-8 encoding.
  563. // The wide string is assumed to have the following encoding:
  564. // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
  565. // UTF-32 if sizeof(wchar_t) == 4 (on Linux)
  566. // Parameter str points to a null-terminated wide string.
  567. // Parameter num_chars may additionally limit the number
  568. // of wchar_t characters processed. -1 is used when the entire string
  569. // should be processed.
  570. // If the string contains code points that are not valid Unicode code points
  571. // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
  572. // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
  573. // and contains invalid UTF-16 surrogate pairs, values in those pairs
  574. // will be encoded as individual Unicode characters from Basic Normal Plane.
  575. GTEST_API_ std::string WideStringToUtf8(const wchar_t* str, int num_chars);
  576. // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
  577. // if the variable is present. If a file already exists at this location, this
  578. // function will write over it. If the variable is present, but the file cannot
  579. // be created, prints an error and exits.
  580. void WriteToShardStatusFileIfNeeded();
  581. // Checks whether sharding is enabled by examining the relevant
  582. // environment variable values. If the variables are present,
  583. // but inconsistent (e.g., shard_index >= total_shards), prints
  584. // an error and exits. If in_subprocess_for_death_test, sharding is
  585. // disabled because it must only be applied to the original test
  586. // process. Otherwise, we could filter out death tests we intended to execute.
  587. GTEST_API_ bool ShouldShard(const char* total_shards_str,
  588. const char* shard_index_str,
  589. bool in_subprocess_for_death_test);
  590. // Parses the environment variable var as an Int32. If it is unset,
  591. // returns default_val. If it is not an Int32, prints an error and
  592. // and aborts.
  593. GTEST_API_ Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val);
  594. // Given the total number of shards, the shard index, and the test id,
  595. // returns true iff the test should be run on this shard. The test id is
  596. // some arbitrary but unique non-negative integer assigned to each test
  597. // method. Assumes that 0 <= shard_index < total_shards.
  598. GTEST_API_ bool ShouldRunTestOnShard(
  599. int total_shards, int shard_index, int test_id);
  600. // STL container utilities.
  601. // Returns the number of elements in the given container that satisfy
  602. // the given predicate.
  603. template <class Container, typename Predicate>
  604. inline int CountIf(const Container& c, Predicate predicate) {
  605. // Implemented as an explicit loop since std::count_if() in libCstd on
  606. // Solaris has a non-standard signature.
  607. int count = 0;
  608. for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) {
  609. if (predicate(*it))
  610. ++count;
  611. }
  612. return count;
  613. }
  614. // Applies a function/functor to each element in the container.
  615. template <class Container, typename Functor>
  616. void ForEach(const Container& c, Functor functor) {
  617. std::for_each(c.begin(), c.end(), functor);
  618. }
  619. // Returns the i-th element of the vector, or default_value if i is not
  620. // in range [0, v.size()).
  621. template <typename E>
  622. inline E GetElementOr(const std::vector<E>& v, int i, E default_value) {
  623. return (i < 0 || i >= static_cast<int>(v.size())) ? default_value : v[i];
  624. }
  625. // Performs an in-place shuffle of a range of the vector's elements.
  626. // 'begin' and 'end' are element indices as an STL-style range;
  627. // i.e. [begin, end) are shuffled, where 'end' == size() means to
  628. // shuffle to the end of the vector.
  629. template <typename E>
  630. void ShuffleRange(internal::Random* random, int begin, int end,
  631. std::vector<E>* v) {
  632. const int size = static_cast<int>(v->size());
  633. GTEST_CHECK_(0 <= begin && begin <= size)
  634. << "Invalid shuffle range start " << begin << ": must be in range [0, "
  635. << size << "].";
  636. GTEST_CHECK_(begin <= end && end <= size)
  637. << "Invalid shuffle range finish " << end << ": must be in range ["
  638. << begin << ", " << size << "].";
  639. // Fisher-Yates shuffle, from
  640. // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
  641. for (int range_width = end - begin; range_width >= 2; range_width--) {
  642. const int last_in_range = begin + range_width - 1;
  643. const int selected = begin + random->Generate(range_width);
  644. std::swap((*v)[selected], (*v)[last_in_range]);
  645. }
  646. }
  647. // Performs an in-place shuffle of the vector's elements.
  648. template <typename E>
  649. inline void Shuffle(internal::Random* random, std::vector<E>* v) {
  650. ShuffleRange(random, 0, static_cast<int>(v->size()), v);
  651. }
  652. // A function for deleting an object. Handy for being used as a
  653. // functor.
  654. template <typename T>
  655. static void Delete(T* x) {
  656. delete x;
  657. }
  658. // A predicate that checks the key of a TestProperty against a known key.
  659. //
  660. // TestPropertyKeyIs is copyable.
  661. class TestPropertyKeyIs {
  662. public:
  663. // Constructor.
  664. //
  665. // TestPropertyKeyIs has NO default constructor.
  666. explicit TestPropertyKeyIs(const std::string& key) : key_(key) {}
  667. // Returns true iff the test name of test property matches on key_.
  668. bool operator()(const TestProperty& test_property) const {
  669. return test_property.key() == key_;
  670. }
  671. private:
  672. std::string key_;
  673. };
  674. // Class UnitTestOptions.
  675. //
  676. // This class contains functions for processing options the user
  677. // specifies when running the tests. It has only static members.
  678. //
  679. // In most cases, the user can specify an option using either an
  680. // environment variable or a command line flag. E.g. you can set the
  681. // test filter using either GTEST_FILTER or --gtest_filter. If both
  682. // the variable and the flag are present, the latter overrides the
  683. // former.
  684. class GTEST_API_ UnitTestOptions {
  685. public:
  686. // Functions for processing the gtest_output flag.
  687. // Returns the output format, or "" for normal printed output.
  688. static std::string GetOutputFormat();
  689. // Returns the absolute path of the requested output file, or the
  690. // default (test_detail.xml in the original working directory) if
  691. // none was explicitly specified.
  692. static std::string GetAbsolutePathToOutputFile();
  693. // Functions for processing the gtest_filter flag.
  694. // Returns true iff the wildcard pattern matches the string. The
  695. // first ':' or '\0' character in pattern marks the end of it.
  696. //
  697. // This recursive algorithm isn't very efficient, but is clear and
  698. // works well enough for matching test names, which are short.
  699. static bool PatternMatchesString(const char *pattern, const char *str);
  700. // Returns true iff the user-specified filter matches the test case
  701. // name and the test name.
  702. static bool FilterMatchesTest(const std::string &test_case_name,
  703. const std::string &test_name);
  704. #if GTEST_OS_WINDOWS
  705. // Function for supporting the gtest_catch_exception flag.
  706. // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
  707. // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
  708. // This function is useful as an __except condition.
  709. static int GTestShouldProcessSEH(DWORD exception_code);
  710. #endif // GTEST_OS_WINDOWS
  711. // Returns true if "name" matches the ':' separated list of glob-style
  712. // filters in "filter".
  713. static bool MatchesFilter(const std::string& name, const char* filter);
  714. };
  715. // Returns the current application's name, removing directory path if that
  716. // is present. Used by UnitTestOptions::GetOutputFile.
  717. GTEST_API_ FilePath GetCurrentExecutableName();
  718. // The role interface for getting the OS stack trace as a string.
  719. class OsStackTraceGetterInterface {
  720. public:
  721. OsStackTraceGetterInterface() {}
  722. virtual ~OsStackTraceGetterInterface() {}
  723. // Returns the current OS stack trace as an std::string. Parameters:
  724. //
  725. // max_depth - the maximum number of stack frames to be included
  726. // in the trace.
  727. // skip_count - the number of top frames to be skipped; doesn't count
  728. // against max_depth.
  729. virtual string CurrentStackTrace(int max_depth, int skip_count) = 0;
  730. // UponLeavingGTest() should be called immediately before Google Test calls
  731. // user code. It saves some information about the current stack that
  732. // CurrentStackTrace() will use to find and hide Google Test stack frames.
  733. virtual void UponLeavingGTest() = 0;
  734. private:
  735. GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface);
  736. };
  737. // A working implementation of the OsStackTraceGetterInterface interface.
  738. class OsStackTraceGetter : public OsStackTraceGetterInterface {
  739. public:
  740. OsStackTraceGetter() : caller_frame_(NULL) {}
  741. virtual string CurrentStackTrace(int max_depth, int skip_count)
  742. GTEST_LOCK_EXCLUDED_(mutex_);
  743. virtual void UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_);
  744. // This string is inserted in place of stack frames that are part of
  745. // Google Test's implementation.
  746. static const char* const kElidedFramesMarker;
  747. private:
  748. Mutex mutex_; // protects all internal state
  749. // We save the stack frame below the frame that calls user code.
  750. // We do this because the address of the frame immediately below
  751. // the user code changes between the call to UponLeavingGTest()
  752. // and any calls to CurrentStackTrace() from within the user code.
  753. void* caller_frame_;
  754. GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter);
  755. };
  756. // Information about a Google Test trace point.
  757. struct TraceInfo {
  758. const char* file;
  759. int line;
  760. std::string message;
  761. };
  762. // This is the default global test part result reporter used in UnitTestImpl.
  763. // This class should only be used by UnitTestImpl.
  764. class DefaultGlobalTestPartResultReporter
  765. : public TestPartResultReporterInterface {
  766. public:
  767. explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test);
  768. // Implements the TestPartResultReporterInterface. Reports the test part
  769. // result in the current test.
  770. virtual void ReportTestPartResult(const TestPartResult& result);
  771. private:
  772. UnitTestImpl* const unit_test_;
  773. GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter);
  774. };
  775. // This is the default per thread test part result reporter used in
  776. // UnitTestImpl. This class should only be used by UnitTestImpl.
  777. class DefaultPerThreadTestPartResultReporter
  778. : public TestPartResultReporterInterface {
  779. public:
  780. explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test);
  781. // Implements the TestPartResultReporterInterface. The implementation just
  782. // delegates to the current global test part result reporter of *unit_test_.
  783. virtual void ReportTestPartResult(const TestPartResult& result);
  784. private:
  785. UnitTestImpl* const unit_test_;
  786. GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter);
  787. };
  788. // The private implementation of the UnitTest class. We don't protect
  789. // the methods under a mutex, as this class is not accessible by a
  790. // user and the UnitTest class that delegates work to this class does
  791. // proper locking.
  792. class GTEST_API_ UnitTestImpl {
  793. public:
  794. explicit UnitTestImpl(UnitTest* parent);
  795. virtual ~UnitTestImpl();
  796. // There are two different ways to register your own TestPartResultReporter.
  797. // You can register your own repoter to listen either only for test results
  798. // from the current thread or for results from all threads.
  799. // By default, each per-thread test result repoter just passes a new
  800. // TestPartResult to the global test result reporter, which registers the
  801. // test part result for the currently running test.
  802. // Returns the global test part result reporter.
  803. TestPartResultReporterInterface* GetGlobalTestPartResultReporter();
  804. // Sets the global test part result reporter.
  805. void SetGlobalTestPartResultReporter(
  806. TestPartResultReporterInterface* reporter);
  807. // Returns the test part result reporter for the current thread.
  808. TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread();
  809. // Sets the test part result reporter for the current thread.
  810. void SetTestPartResultReporterForCurrentThread(
  811. TestPartResultReporterInterface* reporter);
  812. // Gets the number of successful test cases.
  813. int successful_test_case_count() const;
  814. // Gets the number of failed test cases.
  815. int failed_test_case_count() const;
  816. // Gets the number of all test cases.
  817. int total_test_case_count() const;
  818. // Gets the number of all test cases that contain at least one test
  819. // that should run.
  820. int test_case_to_run_count() const;
  821. // Gets the number of successful tests.
  822. int successful_test_count() const;
  823. // Gets the number of failed tests.
  824. int failed_test_count() const;
  825. // Gets the number of disabled tests that will be reported in the XML report.
  826. int reportable_disabled_test_count() const;
  827. // Gets the number of disabled tests.
  828. int disabled_test_count() const;
  829. // Gets the number of tests to be printed in the XML report.
  830. int reportable_test_count() const;
  831. // Gets the number of all tests.
  832. int total_test_count() const;
  833. // Gets the number of tests that should run.
  834. int test_to_run_count() const;
  835. // Gets the time of the test program start, in ms from the start of the
  836. // UNIX epoch.
  837. TimeInMillis start_timestamp() const { return start_timestamp_; }
  838. // Gets the elapsed time, in milliseconds.
  839. TimeInMillis elapsed_time() const { return elapsed_time_; }
  840. // Returns true iff the unit test passed (i.e. all test cases passed).
  841. bool Passed() const { return !Failed(); }
  842. // Returns true iff the unit test failed (i.e. some test case failed
  843. // or something outside of all tests failed).
  844. bool Failed() const {
  845. return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed();
  846. }
  847. // Gets the i-th test case among all the test cases. i can range from 0 to
  848. // total_test_case_count() - 1. If i is not in that range, returns NULL.
  849. const TestCase* GetTestCase(int i) const {
  850. const int index = GetElementOr(test_case_indices_, i, -1);
  851. return index < 0 ? NULL : test_cases_[i];
  852. }
  853. // Gets the i-th test case among all the test cases. i can range from 0 to
  854. // total_test_case_count() - 1. If i is not in that range, returns NULL.
  855. TestCase* GetMutableTestCase(int i) {
  856. const int index = GetElementOr(test_case_indices_, i, -1);
  857. return index < 0 ? NULL : test_cases_[index];
  858. }
  859. // Provides access to the event listener list.
  860. TestEventListeners* listeners() { return &listeners_; }
  861. // Returns the TestResult for the test that's currently running, or
  862. // the TestResult for the ad hoc test if no test is running.
  863. TestResult* current_test_result();
  864. // Returns the TestResult for the ad hoc test.
  865. const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; }
  866. // Sets the OS stack trace getter.
  867. //
  868. // Does nothing if the input and the current OS stack trace getter
  869. // are the same; otherwise, deletes the old getter and makes the
  870. // input the current getter.
  871. void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter);
  872. // Returns the current OS stack trace getter if it is not NULL;
  873. // otherwise, creates an OsStackTraceGetter, makes it the current
  874. // getter, and returns it.
  875. OsStackTraceGetterInterface* os_stack_trace_getter();
  876. // Returns the current OS stack trace as an std::string.
  877. //
  878. // The maximum number of stack frames to be included is specified by
  879. // the gtest_stack_trace_depth flag. The skip_count parameter
  880. // specifies the number of top frames to be skipped, which doesn't
  881. // count against the number of frames to be included.
  882. //
  883. // For example, if Foo() calls Bar(), which in turn calls
  884. // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
  885. // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
  886. std::string CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_;
  887. // Finds and returns a TestCase with the given name. If one doesn't
  888. // exist, creates one and returns it.
  889. //
  890. // Arguments:
  891. //
  892. // test_case_name: name of the test case
  893. // type_param: the name of the test's type parameter, or NULL if
  894. // this is not a typed or a type-parameterized test.
  895. // set_up_tc: pointer to the function that sets up the test case
  896. // tear_down_tc: pointer to the function that tears down the test case
  897. TestCase* GetTestCase(const char* test_case_name,
  898. const char* type_param,
  899. Test::SetUpTestCaseFunc set_up_tc,
  900. Test::TearDownTestCaseFunc tear_down_tc);
  901. // Adds a TestInfo to the unit test.
  902. //
  903. // Arguments:
  904. //
  905. // set_up_tc: pointer to the function that sets up the test case
  906. // tear_down_tc: pointer to the function that tears down the test case
  907. // test_info: the TestInfo object
  908. void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc,
  909. Test::TearDownTestCaseFunc tear_down_tc,
  910. TestInfo* test_info) {
  911. // In order to support thread-safe death tests, we need to
  912. // remember the original working directory when the test program
  913. // was first invoked. We cannot do this in RUN_ALL_TESTS(), as
  914. // the user may have changed the current directory before calling
  915. // RUN_ALL_TESTS(). Therefore we capture the current directory in
  916. // AddTestInfo(), which is called to register a TEST or TEST_F
  917. // before main() is reached.
  918. if (original_working_dir_.IsEmpty()) {
  919. original_working_dir_.Set(FilePath::GetCurrentDir());
  920. GTEST_CHECK_(!original_working_dir_.IsEmpty())
  921. << "Failed to get the current working directory.";
  922. }
  923. GetTestCase(test_info->test_case_name(),
  924. test_info->type_param(),
  925. set_up_tc,
  926. tear_down_tc)->AddTestInfo(test_info);
  927. }
  928. #if GTEST_HAS_PARAM_TEST
  929. // Returns ParameterizedTestCaseRegistry object used to keep track of
  930. // value-parameterized tests and instantiate and register them.
  931. internal::ParameterizedTestCaseRegistry& parameterized_test_registry() {
  932. return parameterized_test_registry_;
  933. }
  934. #endif // GTEST_HAS_PARAM_TEST
  935. // Sets the TestCase object for the test that's currently running.
  936. void set_current_test_case(TestCase* a_current_test_case) {
  937. current_test_case_ = a_current_test_case;
  938. }
  939. // Sets the TestInfo object for the test that's currently running. If
  940. // current_test_info is NULL, the assertion results will be stored in
  941. // ad_hoc_test_result_.
  942. void set_current_test_info(TestInfo* a_current_test_info) {
  943. current_test_info_ = a_current_test_info;
  944. }
  945. // Registers all parameterized tests defined using TEST_P and
  946. // INSTANTIATE_TEST_CASE_P, creating regular tests for each test/parameter
  947. // combination. This method can be called more then once; it has guards
  948. // protecting from registering the tests more then once. If
  949. // value-parameterized tests are disabled, RegisterParameterizedTests is
  950. // present but does nothing.
  951. void RegisterParameterizedTests();
  952. // Runs all tests in this UnitTest object, prints the result, and
  953. // returns true if all tests are successful. If any exception is
  954. // thrown during a test, this test is considered to be failed, but
  955. // the rest of the tests will still be run.
  956. bool RunAllTests();
  957. // Clears the results of all tests, except the ad hoc tests.
  958. void ClearNonAdHocTestResult() {
  959. ForEach(test_cases_, TestCase::ClearTestCaseResult);
  960. }
  961. // Clears the results of ad-hoc test assertions.
  962. void ClearAdHocTestResult() {
  963. ad_hoc_test_result_.Clear();
  964. }
  965. // Adds a TestProperty to the current TestResult object when invoked in a
  966. // context of a test or a test case, or to the global property set. If the
  967. // result already contains a property with the same key, the value will be
  968. // updated.
  969. void RecordProperty(const TestProperty& test_property);
  970. enum ReactionToSharding {
  971. HONOR_SHARDING_PROTOCOL,
  972. IGNORE_SHARDING_PROTOCOL
  973. };
  974. // Matches the full name of each test against the user-specified
  975. // filter to decide whether the test should run, then records the
  976. // result in each TestCase and TestInfo object.
  977. // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests
  978. // based on sharding variables in the environment.
  979. // Returns the number of tests that should run.
  980. int FilterTests(ReactionToSharding shard_tests);
  981. // Prints the names of the tests matching the user-specified filter flag.
  982. void ListTestsMatchingFilter();
  983. const TestCase* current_test_case() const { return current_test_case_; }
  984. TestInfo* current_test_info() { return current_test_info_; }
  985. const TestInfo* current_test_info() const { return current_test_info_; }
  986. // Returns the vector of environments that need to be set-up/torn-down
  987. // before/after the tests are run.
  988. std::vector<Environment*>& environments() { return environments_; }
  989. // Getters for the per-thread Google Test trace stack.
  990. std::vector<TraceInfo>& gtest_trace_stack() {
  991. return *(gtest_trace_stack_.pointer());
  992. }
  993. const std::vector<TraceInfo>& gtest_trace_stack() const {
  994. return gtest_trace_stack_.get();
  995. }
  996. #if GTEST_HAS_DEATH_TEST
  997. void InitDeathTestSubprocessControlInfo() {
  998. internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());
  999. }
  1000. // Returns a pointer to the parsed --gtest_internal_run_death_test
  1001. // flag, or NULL if that flag was not specified.
  1002. // This information is useful only in a death test child process.
  1003. // Must not be called before a call to InitGoogleTest.
  1004. const InternalRunDeathTestFlag* internal_run_death_test_flag() const {
  1005. return internal_run_death_test_flag_.get();
  1006. }
  1007. // Returns a pointer to the current death test factory.
  1008. internal::DeathTestFactory* death_test_factory() {
  1009. return death_test_factory_.get();
  1010. }
  1011. void SuppressTestEventsIfInSubprocess();
  1012. friend class ReplaceDeathTestFactory;
  1013. #endif // GTEST_HAS_DEATH_TEST
  1014. // Initializes the event listener performing XML output as specified by
  1015. // UnitTestOptions. Must not be called before InitGoogleTest.
  1016. void ConfigureXmlOutput();
  1017. #if GTEST_CAN_STREAM_RESULTS_
  1018. // Initializes the event listener for streaming test results to a socket.
  1019. // Must not be called before InitGoogleTest.
  1020. void ConfigureStreamingOutput();
  1021. #endif
  1022. // Performs initialization dependent upon flag values obtained in
  1023. // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
  1024. // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
  1025. // this function is also called from RunAllTests. Since this function can be
  1026. // called more than once, it has to be idempotent.
  1027. void PostFlagParsingInit();
  1028. // Gets the random seed used at the start of the current test iteration.
  1029. int random_seed() const { return random_seed_; }
  1030. // Gets the random number generator.
  1031. internal::Random* random() { return &random_; }
  1032. // Shuffles all test cases, and the tests within each test case,
  1033. // making sure that death tests are still run first.
  1034. void ShuffleTests();
  1035. // Restores the test cases and tests to their order before the first shuffle.
  1036. void UnshuffleTests();
  1037. // Returns the value of GTEST_FLAG(catch_exceptions) at the moment
  1038. // UnitTest::Run() starts.
  1039. bool catch_exceptions() const { return catch_exceptions_; }
  1040. private:
  1041. friend class ::testing::UnitTest;
  1042. // Used by UnitTest::Run() to capture the state of
  1043. // GTEST_FLAG(catch_exceptions) at the moment it starts.
  1044. void set_catch_exceptions(bool value) { catch_exceptions_ = value; }
  1045. // The UnitTest object that owns this implementation object.
  1046. UnitTest* const parent_;
  1047. // The working directory when the first TEST() or TEST_F() was
  1048. // executed.
  1049. internal::FilePath original_working_dir_;
  1050. // The default test part result reporters.
  1051. DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_;
  1052. DefaultPerThreadTestPartResultReporter
  1053. default_per_thread_test_part_result_reporter_;
  1054. // Points to (but doesn't own) the global test part result reporter.
  1055. TestPartResultReporterInterface* global_test_part_result_repoter_;
  1056. // Protects read and write access to global_test_part_result_reporter_.
  1057. internal::Mutex global_test_part_result_reporter_mutex_;
  1058. // Points to (but doesn't own) the per-thread test part result reporter.
  1059. internal::ThreadLocal<TestPartResultReporterInterface*>
  1060. per_thread_test_part_result_reporter_;
  1061. // The vector of environments that need to be set-up/torn-down
  1062. // before/after the tests are run.
  1063. std::vector<Environment*> environments_;
  1064. // The vector of TestCases in their original order. It owns the
  1065. // elements in the vector.
  1066. std::vector<TestCase*> test_cases_;
  1067. // Provides a level of indirection for the test case list to allow
  1068. // easy shuffling and restoring the test case order. The i-th
  1069. // element of this vector is the index of the i-th test case in the
  1070. // shuffled order.
  1071. std::vector<int> test_case_indices_;
  1072. #if GTEST_HAS_PARAM_TEST
  1073. // ParameterizedTestRegistry object used to register value-parameterized
  1074. // tests.
  1075. internal::ParameterizedTestCaseRegistry parameterized_test_registry_;
  1076. // Indicates whether RegisterParameterizedTests() has been called already.
  1077. bool parameterized_tests_registered_;
  1078. #endif // GTEST_HAS_PARAM_TEST
  1079. // Index of the last death test case registered. Initially -1.
  1080. int last_death_test_case_;
  1081. // This points to the TestCase for the currently running test. It
  1082. // changes as Google Test goes through one test case after another.
  1083. // When no test is running, this is set to NULL and Google Test
  1084. // stores assertion results in ad_hoc_test_result_. Initially NULL.
  1085. TestCase* current_test_case_;
  1086. // This points to the TestInfo for the currently running test. It
  1087. // changes as Google Test goes through one test after another. When
  1088. // no test is running, this is set to NULL and Google Test stores
  1089. // assertion results in ad_hoc_test_result_. Initially NULL.
  1090. TestInfo* current_test_info_;
  1091. // Normally, a user only writes assertions inside a TEST or TEST_F,
  1092. // or inside a function called by a TEST or TEST_F. Since Google
  1093. // Test keeps track of which test is current running, it can
  1094. // associate such an assertion with the test it belongs to.
  1095. //
  1096. // If an assertion is encountered when no TEST or TEST_F is running,
  1097. // Google Test attributes the assertion result to an imaginary "ad hoc"
  1098. // test, and records the result in ad_hoc_test_result_.
  1099. TestResult ad_hoc_test_result_;
  1100. // The list of event listeners that can be used to track events inside
  1101. // Google Test.
  1102. TestEventListeners listeners_;
  1103. // The OS stack trace getter. Will be deleted when the UnitTest
  1104. // object is destructed. By default, an OsStackTraceGetter is used,
  1105. // but the user can set this field to use a custom getter if that is
  1106. // desired.
  1107. OsStackTraceGetterInterface* os_stack_trace_getter_;
  1108. // True iff PostFlagParsingInit() has been called.
  1109. bool post_flag_parse_init_performed_;
  1110. // The random number seed used at the beginning of the test run.
  1111. int random_seed_;
  1112. // Our random number generator.
  1113. internal::Random random_;
  1114. // The time of the test program start, in ms from the start of the
  1115. // UNIX epoch.
  1116. TimeInMillis start_timestamp_;
  1117. // How long the test took to run, in milliseconds.
  1118. TimeInMillis elapsed_time_;
  1119. #if GTEST_HAS_DEATH_TEST
  1120. // The decomposed components of the gtest_internal_run_death_test flag,
  1121. // parsed when RUN_ALL_TESTS is called.
  1122. internal::scoped_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;
  1123. internal::scoped_ptr<internal::DeathTestFactory> death_test_factory_;
  1124. #endif // GTEST_HAS_DEATH_TEST
  1125. // A per-thread stack of traces created by the SCOPED_TRACE() macro.
  1126. internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_;
  1127. // The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests()
  1128. // starts.
  1129. bool catch_exceptions_;
  1130. GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl);
  1131. }; // class UnitTestImpl
  1132. // Convenience function for accessing the global UnitTest
  1133. // implementation object.
  1134. inline UnitTestImpl* GetUnitTestImpl() {
  1135. return UnitTest::GetInstance()->impl();
  1136. }
  1137. #if GTEST_USES_SIMPLE_RE
  1138. // Internal helper functions for implementing the simple regular
  1139. // expression matcher.
  1140. GTEST_API_ bool IsInSet(char ch, const char* str);
  1141. GTEST_API_ bool IsAsciiDigit(char ch);
  1142. GTEST_API_ bool IsAsciiPunct(char ch);
  1143. GTEST_API_ bool IsRepeat(char ch);
  1144. GTEST_API_ bool IsAsciiWhiteSpace(char ch);
  1145. GTEST_API_ bool IsAsciiWordChar(char ch);
  1146. GTEST_API_ bool IsValidEscape(char ch);
  1147. GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch);
  1148. GTEST_API_ bool ValidateRegex(const char* regex);
  1149. GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str);
  1150. GTEST_API_ bool MatchRepetitionAndRegexAtHead(
  1151. bool escaped, char ch, char repeat, const char* regex, const char* str);
  1152. GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str);
  1153. #endif // GTEST_USES_SIMPLE_RE
  1154. // Parses the command line for Google Test flags, without initializing
  1155. // other parts of Google Test.
  1156. GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv);
  1157. GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv);
  1158. #if GTEST_HAS_DEATH_TEST
  1159. // Returns the message describing the last system error, regardless of the
  1160. // platform.
  1161. GTEST_API_ std::string GetLastErrnoDescription();
  1162. # if GTEST_OS_WINDOWS
  1163. // Provides leak-safe Windows kernel handle ownership.
  1164. class AutoHandle {
  1165. public:
  1166. AutoHandle() : handle_(INVALID_HANDLE_VALUE) {}
  1167. explicit AutoHandle(HANDLE handle) : handle_(handle) {}
  1168. ~AutoHandle() { Reset(); }
  1169. HANDLE Get() const { return handle_; }
  1170. void Reset() { Reset(INVALID_HANDLE_VALUE); }
  1171. void Reset(HANDLE handle) {
  1172. if (handle != handle_) {
  1173. if (handle_ != INVALID_HANDLE_VALUE)
  1174. ::CloseHandle(handle_);
  1175. handle_ = handle;
  1176. }
  1177. }
  1178. private:
  1179. HANDLE handle_;
  1180. GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle);
  1181. };
  1182. # endif // GTEST_OS_WINDOWS
  1183. // Attempts to parse a string into a positive integer pointed to by the
  1184. // number parameter. Returns true if that is possible.
  1185. // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use
  1186. // it here.
  1187. template <typename Integer>
  1188. bool ParseNaturalNumber(const ::std::string& str, Integer* number) {
  1189. // Fail fast if the given string does not begin with a digit;
  1190. // this bypasses strtoXXX's "optional leading whitespace and plus
  1191. // or minus sign" semantics, which are undesirable here.
  1192. if (str.empty() || !IsDigit(str[0])) {
  1193. return false;
  1194. }
  1195. errno = 0;
  1196. char* end;
  1197. // BiggestConvertible is the largest integer type that system-provided
  1198. // string-to-number conversion routines can return.
  1199. # if GTEST_OS_WINDOWS && !defined(__GNUC__)
  1200. // MSVC and C++ Builder define __int64 instead of the standard long long.
  1201. typedef unsigned __int64 BiggestConvertible;
  1202. const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10);
  1203. # else
  1204. typedef unsigned long long BiggestConvertible; // NOLINT
  1205. const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10);
  1206. # endif // GTEST_OS_WINDOWS && !defined(__GNUC__)
  1207. const bool parse_success = *end == '\0' && errno == 0;
  1208. // TODO(vladl@google.com): Convert this to compile time assertion when it is
  1209. // available.
  1210. GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed));
  1211. const Integer result = static_cast<Integer>(parsed);
  1212. if (parse_success && static_cast<BiggestConvertible>(result) == parsed) {
  1213. *number = result;
  1214. return true;
  1215. }
  1216. return false;
  1217. }
  1218. #endif // GTEST_HAS_DEATH_TEST
  1219. // TestResult contains some private methods that should be hidden from
  1220. // Google Test user but are required for testing. This class allow our tests
  1221. // to access them.
  1222. //
  1223. // This class is supplied only for the purpose of testing Google Test's own
  1224. // constructs. Do not use it in user tests, either directly or indirectly.
  1225. class TestResultAccessor {
  1226. public:
  1227. static void RecordProperty(TestResult* test_result,
  1228. const std::string& xml_element,
  1229. const TestProperty& property) {
  1230. test_result->RecordProperty(xml_element, property);
  1231. }
  1232. static void ClearTestPartResults(TestResult* test_result) {
  1233. test_result->ClearTestPartResults();
  1234. }
  1235. static const std::vector<testing::TestPartResult>& test_part_results(
  1236. const TestResult& test_result) {
  1237. return test_result.test_part_results();
  1238. }
  1239. };
  1240. #if GTEST_CAN_STREAM_RESULTS_
  1241. // Streams test results to the given port on the given host machine.
  1242. class StreamingListener : public EmptyTestEventListener {
  1243. public:
  1244. // Abstract base class for writing strings to a socket.
  1245. class AbstractSocketWriter {
  1246. public:
  1247. virtual ~AbstractSocketWriter() {}
  1248. // Sends a string to the socket.
  1249. virtual void Send(const string& message) = 0;
  1250. // Closes the socket.
  1251. virtual void CloseConnection() {}
  1252. // Sends a string and a newline to the socket.
  1253. void SendLn(const string& message) {
  1254. Send(message + "\n");
  1255. }
  1256. };
  1257. // Concrete class for actually writing strings to a socket.
  1258. class SocketWriter : public AbstractSocketWriter {
  1259. public:
  1260. SocketWriter(const string& host, const string& port)
  1261. : sockfd_(-1), host_name_(host), port_num_(port) {
  1262. MakeConnection();
  1263. }
  1264. virtual ~SocketWriter() {
  1265. if (sockfd_ != -1)
  1266. CloseConnection();
  1267. }
  1268. // Sends a string to the socket.
  1269. virtual void Send(const string& message) {
  1270. GTEST_CHECK_(sockfd_ != -1)
  1271. << "Send() can be called only when there is a connection.";
  1272. const int len = static_cast<int>(message.length());
  1273. if (write(sockfd_, message.c_str(), len) != len) {
  1274. GTEST_LOG_(WARNING)
  1275. << "stream_result_to: failed to stream to "
  1276. << host_name_ << ":" << port_num_;
  1277. }
  1278. }
  1279. private:
  1280. // Creates a client socket and connects to the server.
  1281. void MakeConnection();
  1282. // Closes the socket.
  1283. void CloseConnection() {
  1284. GTEST_CHECK_(sockfd_ != -1)
  1285. << "CloseConnection() can be called only when there is a connection.";
  1286. close(sockfd_);
  1287. sockfd_ = -1;
  1288. }
  1289. int sockfd_; // socket file descriptor
  1290. const string host_name_;
  1291. const string port_num_;
  1292. GTEST_DISALLOW_COPY_AND_ASSIGN_(SocketWriter);
  1293. }; // class SocketWriter
  1294. // Escapes '=', '&', '%', and '\n' characters in str as "%xx".
  1295. static string UrlEncode(const char* str);
  1296. StreamingListener(const string& host, const string& port)
  1297. : socket_writer_(new SocketWriter(host, port)) { Start(); }
  1298. explicit StreamingListener(AbstractSocketWriter* socket_writer)
  1299. : socket_writer_(socket_writer) { Start(); }
  1300. void OnTestProgramStart(const UnitTest& /* unit_test */) {
  1301. SendLn("event=TestProgramStart");
  1302. }
  1303. void OnTestProgramEnd(const UnitTest& unit_test) {
  1304. // Note that Google Test current only report elapsed time for each
  1305. // test iteration, not for the entire test program.
  1306. SendLn("event=TestProgramEnd&passed=" + FormatBool(unit_test.Passed()));
  1307. // Notify the streaming server to stop.
  1308. socket_writer_->CloseConnection();
  1309. }
  1310. void OnTestIterationStart(const UnitTest& /* unit_test */, int iteration) {
  1311. SendLn("event=TestIterationStart&iteration=" +
  1312. StreamableToString(iteration));
  1313. }
  1314. void OnTestIterationEnd(const UnitTest& unit_test, int /* iteration */) {
  1315. SendLn("event=TestIterationEnd&passed=" +
  1316. FormatBool(unit_test.Passed()) + "&elapsed_time=" +
  1317. StreamableToString(unit_test.elapsed_time()) + "ms");
  1318. }
  1319. void OnTestCaseStart(const TestCase& test_case) {
  1320. SendLn(std::string("event=TestCaseStart&name=") + test_case.name());
  1321. }
  1322. void OnTestCaseEnd(const TestCase& test_case) {
  1323. SendLn("event=TestCaseEnd&passed=" + FormatBool(test_case.Passed())
  1324. + "&elapsed_time=" + StreamableToString(test_case.elapsed_time())
  1325. + "ms");
  1326. }
  1327. void OnTestStart(const TestInfo& test_info) {
  1328. SendLn(std::string("event=TestStart&name=") + test_info.name());
  1329. }
  1330. void OnTestEnd(const TestInfo& test_info) {
  1331. SendLn("event=TestEnd&passed=" +
  1332. FormatBool((test_info.result())->Passed()) +
  1333. "&elapsed_time=" +
  1334. StreamableToString((test_info.result())->elapsed_time()) + "ms");
  1335. }
  1336. void OnTestPartResult(const TestPartResult& test_part_result) {
  1337. const char* file_name = test_part_result.file_name();
  1338. if (file_name == NULL)
  1339. file_name = "";
  1340. SendLn("event=TestPartResult&file=" + UrlEncode(file_name) +
  1341. "&line=" + StreamableToString(test_part_result.line_number()) +
  1342. "&message=" + UrlEncode(test_part_result.message()));
  1343. }
  1344. private:
  1345. // Sends the given message and a newline to the socket.
  1346. void SendLn(const string& message) { socket_writer_->SendLn(message); }
  1347. // Called at the start of streaming to notify the receiver what
  1348. // protocol we are using.
  1349. void Start() { SendLn("gtest_streaming_protocol_version=1.0"); }
  1350. string FormatBool(bool value) { return value ? "1" : "0"; }
  1351. const scoped_ptr<AbstractSocketWriter> socket_writer_;
  1352. GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener);
  1353. }; // class StreamingListener
  1354. #endif // GTEST_CAN_STREAM_RESULTS_
  1355. } // namespace internal
  1356. } // namespace testing
  1357. #endif // GTEST_SRC_GTEST_INTERNAL_INL_H_
  1358. #undef GTEST_IMPLEMENTATION_
  1359. #if GTEST_OS_WINDOWS
  1360. # define vsnprintf _vsnprintf
  1361. #endif // GTEST_OS_WINDOWS
  1362. namespace testing {
  1363. using internal::CountIf;
  1364. using internal::ForEach;
  1365. using internal::GetElementOr;
  1366. using internal::Shuffle;
  1367. // Constants.
  1368. // A test whose test case name or test name matches this filter is
  1369. // disabled and not run.
  1370. static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
  1371. // A test case whose name matches this filter is considered a death
  1372. // test case and will be run before test cases whose name doesn't
  1373. // match this filter.
  1374. static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*";
  1375. // A test filter that matches everything.
  1376. static const char kUniversalFilter[] = "*";
  1377. // The default output file for XML output.
  1378. static const char kDefaultOutputFile[] = "test_detail.xml";
  1379. // The environment variable name for the test shard index.
  1380. static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
  1381. // The environment variable name for the total number of test shards.
  1382. static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
  1383. // The environment variable name for the test shard status file.
  1384. static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
  1385. namespace internal {
  1386. // The text used in failure messages to indicate the start of the
  1387. // stack trace.
  1388. const char kStackTraceMarker[] = "\nStack trace:\n";
  1389. // g_help_flag is true iff the --help flag or an equivalent form is
  1390. // specified on the command line.
  1391. bool g_help_flag = false;
  1392. } // namespace internal
  1393. static const char* GetDefaultFilter() {
  1394. return kUniversalFilter;
  1395. }
  1396. GTEST_DEFINE_bool_(
  1397. also_run_disabled_tests,
  1398. internal::BoolFromGTestEnv("also_run_disabled_tests", false),
  1399. "Run disabled tests too, in addition to the tests normally being run.");
  1400. GTEST_DEFINE_bool_(
  1401. break_on_failure,
  1402. internal::BoolFromGTestEnv("break_on_failure", false),
  1403. "True iff a failed assertion should be a debugger break-point.");
  1404. GTEST_DEFINE_bool_(
  1405. catch_exceptions,
  1406. internal::BoolFromGTestEnv("catch_exceptions", true),
  1407. "True iff " GTEST_NAME_
  1408. " should catch exceptions and treat them as test failures.");
  1409. GTEST_DEFINE_string_(
  1410. color,
  1411. internal::StringFromGTestEnv("color", "auto"),
  1412. "Whether to use colors in the output. Valid values: yes, no, "
  1413. "and auto. 'auto' means to use colors if the output is "
  1414. "being sent to a terminal and the TERM environment variable "
  1415. "is set to a terminal type that supports colors.");
  1416. GTEST_DEFINE_string_(
  1417. filter,
  1418. internal::StringFromGTestEnv("filter", GetDefaultFilter()),
  1419. "A colon-separated list of glob (not regex) patterns "
  1420. "for filtering the tests to run, optionally followed by a "
  1421. "'-' and a : separated list of negative patterns (tests to "
  1422. "exclude). A test is run if it matches one of the positive "
  1423. "patterns and does not match any of the negative patterns.");
  1424. GTEST_DEFINE_bool_(list_tests, false,
  1425. "List all tests without running them.");
  1426. GTEST_DEFINE_string_(
  1427. output,
  1428. internal::StringFromGTestEnv("output", ""),
  1429. "A format (currently must be \"xml\"), optionally followed "
  1430. "by a colon and an output file name or directory. A directory "
  1431. "is indicated by a trailing pathname separator. "
  1432. "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
  1433. "If a directory is specified, output files will be created "
  1434. "within that directory, with file-names based on the test "
  1435. "executable's name and, if necessary, made unique by adding "
  1436. "digits.");
  1437. GTEST_DEFINE_bool_(
  1438. print_time,
  1439. internal::BoolFromGTestEnv("print_time", true),
  1440. "True iff " GTEST_NAME_
  1441. " should display elapsed time in text output.");
  1442. GTEST_DEFINE_int32_(
  1443. random_seed,
  1444. internal::Int32FromGTestEnv("random_seed", 0),
  1445. "Random number seed to use when shuffling test orders. Must be in range "
  1446. "[1, 99999], or 0 to use a seed based on the current time.");
  1447. GTEST_DEFINE_int32_(
  1448. repeat,
  1449. internal::Int32FromGTestEnv("repeat", 1),
  1450. "How many times to repeat each test. Specify a negative number "
  1451. "for repeating forever. Useful for shaking out flaky tests.");
  1452. GTEST_DEFINE_bool_(
  1453. show_internal_stack_frames, false,
  1454. "True iff " GTEST_NAME_ " should include internal stack frames when "
  1455. "printing test failure stack traces.");
  1456. GTEST_DEFINE_bool_(
  1457. shuffle,
  1458. internal::BoolFromGTestEnv("shuffle", false),
  1459. "True iff " GTEST_NAME_
  1460. " should randomize tests' order on every run.");
  1461. GTEST_DEFINE_int32_(
  1462. stack_trace_depth,
  1463. internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
  1464. "The maximum number of stack frames to print when an "
  1465. "assertion fails. The valid range is 0 through 100, inclusive.");
  1466. GTEST_DEFINE_string_(
  1467. stream_result_to,
  1468. internal::StringFromGTestEnv("stream_result_to", ""),
  1469. "This flag specifies the host name and the port number on which to stream "
  1470. "test results. Example: \"localhost:555\". The flag is effective only on "
  1471. "Linux.");
  1472. GTEST_DEFINE_bool_(
  1473. throw_on_failure,
  1474. internal::BoolFromGTestEnv("throw_on_failure", false),
  1475. "When this flag is specified, a failed assertion will throw an exception "
  1476. "if exceptions are enabled or exit the program with a non-zero code "
  1477. "otherwise.");
  1478. namespace internal {
  1479. // Generates a random number from [0, range), using a Linear
  1480. // Congruential Generator (LCG). Crashes if 'range' is 0 or greater
  1481. // than kMaxRange.
  1482. UInt32 Random::Generate(UInt32 range) {
  1483. // These constants are the same as are used in glibc's rand(3).
  1484. state_ = (1103515245U*state_ + 12345U) % kMaxRange;
  1485. GTEST_CHECK_(range > 0)
  1486. << "Cannot generate a number in the range [0, 0).";
  1487. GTEST_CHECK_(range <= kMaxRange)
  1488. << "Generation of a number in [0, " << range << ") was requested, "
  1489. << "but this can only generate numbers in [0, " << kMaxRange << ").";
  1490. // Converting via modulus introduces a bit of downward bias, but
  1491. // it's simple, and a linear congruential generator isn't too good
  1492. // to begin with.
  1493. return state_ % range;
  1494. }
  1495. // GTestIsInitialized() returns true iff the user has initialized
  1496. // Google Test. Useful for catching the user mistake of not initializing
  1497. // Google Test before calling RUN_ALL_TESTS().
  1498. //
  1499. // A user must call testing::InitGoogleTest() to initialize Google
  1500. // Test. g_init_gtest_count is set to the number of times
  1501. // InitGoogleTest() has been called. We don't protect this variable
  1502. // under a mutex as it is only accessed in the main thread.
  1503. GTEST_API_ int g_init_gtest_count = 0;
  1504. static bool GTestIsInitialized() { return g_init_gtest_count != 0; }
  1505. // Iterates over a vector of TestCases, keeping a running sum of the
  1506. // results of calling a given int-returning method on each.
  1507. // Returns the sum.
  1508. static int SumOverTestCaseList(const std::vector<TestCase*>& case_list,
  1509. int (TestCase::*method)() const) {
  1510. int sum = 0;
  1511. for (size_t i = 0; i < case_list.size(); i++) {
  1512. sum += (case_list[i]->*method)();
  1513. }
  1514. return sum;
  1515. }
  1516. // Returns true iff the test case passed.
  1517. static bool TestCasePassed(const TestCase* test_case) {
  1518. return test_case->should_run() && test_case->Passed();
  1519. }
  1520. // Returns true iff the test case failed.
  1521. static bool TestCaseFailed(const TestCase* test_case) {
  1522. return test_case->should_run() && test_case->Failed();
  1523. }
  1524. // Returns true iff test_case contains at least one test that should
  1525. // run.
  1526. static bool ShouldRunTestCase(const TestCase* test_case) {
  1527. return test_case->should_run();
  1528. }
  1529. // AssertHelper constructor.
  1530. AssertHelper::AssertHelper(TestPartResult::Type type,
  1531. const char* file,
  1532. int line,
  1533. const char* message)
  1534. : data_(new AssertHelperData(type, file, line, message)) {
  1535. }
  1536. AssertHelper::~AssertHelper() {
  1537. delete data_;
  1538. }
  1539. // Message assignment, for assertion streaming support.
  1540. void AssertHelper::operator=(const Message& message) const {
  1541. UnitTest::GetInstance()->
  1542. AddTestPartResult(data_->type, data_->file, data_->line,
  1543. AppendUserMessage(data_->message, message),
  1544. UnitTest::GetInstance()->impl()
  1545. ->CurrentOsStackTraceExceptTop(1)
  1546. // Skips the stack frame for this function itself.
  1547. ); // NOLINT
  1548. }
  1549. // Mutex for linked pointers.
  1550. GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex);
  1551. // Application pathname gotten in InitGoogleTest.
  1552. std::string g_executable_path;
  1553. // Returns the current application's name, removing directory path if that
  1554. // is present.
  1555. FilePath GetCurrentExecutableName() {
  1556. FilePath result;
  1557. #if GTEST_OS_WINDOWS
  1558. result.Set(FilePath(g_executable_path).RemoveExtension("exe"));
  1559. #else
  1560. result.Set(FilePath(g_executable_path));
  1561. #endif // GTEST_OS_WINDOWS
  1562. return result.RemoveDirectoryName();
  1563. }
  1564. // Functions for processing the gtest_output flag.
  1565. // Returns the output format, or "" for normal printed output.
  1566. std::string UnitTestOptions::GetOutputFormat() {
  1567. const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
  1568. if (gtest_output_flag == NULL) return std::string("");
  1569. const char* const colon = strchr(gtest_output_flag, ':');
  1570. return (colon == NULL) ?
  1571. std::string(gtest_output_flag) :
  1572. std::string(gtest_output_flag, colon - gtest_output_flag);
  1573. }
  1574. // Returns the name of the requested output file, or the default if none
  1575. // was explicitly specified.
  1576. std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
  1577. const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
  1578. if (gtest_output_flag == NULL)
  1579. return "";
  1580. const char* const colon = strchr(gtest_output_flag, ':');
  1581. if (colon == NULL)
  1582. return internal::FilePath::ConcatPaths(
  1583. internal::FilePath(
  1584. UnitTest::GetInstance()->original_working_dir()),
  1585. internal::FilePath(kDefaultOutputFile)).string();
  1586. internal::FilePath output_name(colon + 1);
  1587. if (!output_name.IsAbsolutePath())
  1588. // TODO(wan@google.com): on Windows \some\path is not an absolute
  1589. // path (as its meaning depends on the current drive), yet the
  1590. // following logic for turning it into an absolute path is wrong.
  1591. // Fix it.
  1592. output_name = internal::FilePath::ConcatPaths(
  1593. internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
  1594. internal::FilePath(colon + 1));
  1595. if (!output_name.IsDirectory())
  1596. return output_name.string();
  1597. internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
  1598. output_name, internal::GetCurrentExecutableName(),
  1599. GetOutputFormat().c_str()));
  1600. return result.string();
  1601. }
  1602. // Returns true iff the wildcard pattern matches the string. The
  1603. // first ':' or '\0' character in pattern marks the end of it.
  1604. //
  1605. // This recursive algorithm isn't very efficient, but is clear and
  1606. // works well enough for matching test names, which are short.
  1607. bool UnitTestOptions::PatternMatchesString(const char *pattern,
  1608. const char *str) {
  1609. switch (*pattern) {
  1610. case '\0':
  1611. case ':': // Either ':' or '\0' marks the end of the pattern.
  1612. return *str == '\0';
  1613. case '?': // Matches any single character.
  1614. return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);
  1615. case '*': // Matches any string (possibly empty) of characters.
  1616. return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||
  1617. PatternMatchesString(pattern + 1, str);
  1618. default: // Non-special character. Matches itself.
  1619. return *pattern == *str &&
  1620. PatternMatchesString(pattern + 1, str + 1);
  1621. }
  1622. }
  1623. bool UnitTestOptions::MatchesFilter(
  1624. const std::string& name, const char* filter) {
  1625. const char *cur_pattern = filter;
  1626. for (;;) {
  1627. if (PatternMatchesString(cur_pattern, name.c_str())) {
  1628. return true;
  1629. }
  1630. // Finds the next pattern in the filter.
  1631. cur_pattern = strchr(cur_pattern, ':');
  1632. // Returns if no more pattern can be found.
  1633. if (cur_pattern == NULL) {
  1634. return false;
  1635. }
  1636. // Skips the pattern separater (the ':' character).
  1637. cur_pattern++;
  1638. }
  1639. }
  1640. // Returns true iff the user-specified filter matches the test case
  1641. // name and the test name.
  1642. bool UnitTestOptions::FilterMatchesTest(const std::string &test_case_name,
  1643. const std::string &test_name) {
  1644. const std::string& full_name = test_case_name + "." + test_name.c_str();
  1645. // Split --gtest_filter at '-', if there is one, to separate into
  1646. // positive filter and negative filter portions
  1647. const char* const p = GTEST_FLAG(filter).c_str();
  1648. const char* const dash = strchr(p, '-');
  1649. std::string positive;
  1650. std::string negative;
  1651. if (dash == NULL) {
  1652. positive = GTEST_FLAG(filter).c_str(); // Whole string is a positive filter
  1653. negative = "";
  1654. } else {
  1655. positive = std::string(p, dash); // Everything up to the dash
  1656. negative = std::string(dash + 1); // Everything after the dash
  1657. if (positive.empty()) {
  1658. // Treat '-test1' as the same as '*-test1'
  1659. positive = kUniversalFilter;
  1660. }
  1661. }
  1662. // A filter is a colon-separated list of patterns. It matches a
  1663. // test if any pattern in it matches the test.
  1664. return (MatchesFilter(full_name, positive.c_str()) &&
  1665. !MatchesFilter(full_name, negative.c_str()));
  1666. }
  1667. #if GTEST_HAS_SEH
  1668. // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
  1669. // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
  1670. // This function is useful as an __except condition.
  1671. int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
  1672. // Google Test should handle a SEH exception if:
  1673. // 1. the user wants it to, AND
  1674. // 2. this is not a breakpoint exception, AND
  1675. // 3. this is not a C++ exception (VC++ implements them via SEH,
  1676. // apparently).
  1677. //
  1678. // SEH exception code for C++ exceptions.
  1679. // (see http://support.microsoft.com/kb/185294 for more information).
  1680. const DWORD kCxxExceptionCode = 0xe06d7363;
  1681. bool should_handle = true;
  1682. if (!GTEST_FLAG(catch_exceptions))
  1683. should_handle = false;
  1684. else if (exception_code == EXCEPTION_BREAKPOINT)
  1685. should_handle = false;
  1686. else if (exception_code == kCxxExceptionCode)
  1687. should_handle = false;
  1688. return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
  1689. }
  1690. #endif // GTEST_HAS_SEH
  1691. } // namespace internal
  1692. // The c'tor sets this object as the test part result reporter used by
  1693. // Google Test. The 'result' parameter specifies where to report the
  1694. // results. Intercepts only failures from the current thread.
  1695. ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
  1696. TestPartResultArray* result)
  1697. : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
  1698. result_(result) {
  1699. Init();
  1700. }
  1701. // The c'tor sets this object as the test part result reporter used by
  1702. // Google Test. The 'result' parameter specifies where to report the
  1703. // results.
  1704. ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
  1705. InterceptMode intercept_mode, TestPartResultArray* result)
  1706. : intercept_mode_(intercept_mode),
  1707. result_(result) {
  1708. Init();
  1709. }
  1710. void ScopedFakeTestPartResultReporter::Init() {
  1711. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  1712. if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
  1713. old_reporter_ = impl->GetGlobalTestPartResultReporter();
  1714. impl->SetGlobalTestPartResultReporter(this);
  1715. } else {
  1716. old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
  1717. impl->SetTestPartResultReporterForCurrentThread(this);
  1718. }
  1719. }
  1720. // The d'tor restores the test part result reporter used by Google Test
  1721. // before.
  1722. ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
  1723. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  1724. if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
  1725. impl->SetGlobalTestPartResultReporter(old_reporter_);
  1726. } else {
  1727. impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
  1728. }
  1729. }
  1730. // Increments the test part result count and remembers the result.
  1731. // This method is from the TestPartResultReporterInterface interface.
  1732. void ScopedFakeTestPartResultReporter::ReportTestPartResult(
  1733. const TestPartResult& result) {
  1734. result_->Append(result);
  1735. }
  1736. namespace internal {
  1737. // Returns the type ID of ::testing::Test. We should always call this
  1738. // instead of GetTypeId< ::testing::Test>() to get the type ID of
  1739. // testing::Test. This is to work around a suspected linker bug when
  1740. // using Google Test as a framework on Mac OS X. The bug causes
  1741. // GetTypeId< ::testing::Test>() to return different values depending
  1742. // on whether the call is from the Google Test framework itself or
  1743. // from user test code. GetTestTypeId() is guaranteed to always
  1744. // return the same value, as it always calls GetTypeId<>() from the
  1745. // gtest.cc, which is within the Google Test framework.
  1746. TypeId GetTestTypeId() {
  1747. return GetTypeId<Test>();
  1748. }
  1749. // The value of GetTestTypeId() as seen from within the Google Test
  1750. // library. This is solely for testing GetTestTypeId().
  1751. extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
  1752. // This predicate-formatter checks that 'results' contains a test part
  1753. // failure of the given type and that the failure message contains the
  1754. // given substring.
  1755. AssertionResult HasOneFailure(const char* /* results_expr */,
  1756. const char* /* type_expr */,
  1757. const char* /* substr_expr */,
  1758. const TestPartResultArray& results,
  1759. TestPartResult::Type type,
  1760. const string& substr) {
  1761. const std::string expected(type == TestPartResult::kFatalFailure ?
  1762. "1 fatal failure" :
  1763. "1 non-fatal failure");
  1764. Message msg;
  1765. if (results.size() != 1) {
  1766. msg << "Expected: " << expected << "\n"
  1767. << " Actual: " << results.size() << " failures";
  1768. for (int i = 0; i < results.size(); i++) {
  1769. msg << "\n" << results.GetTestPartResult(i);
  1770. }
  1771. return AssertionFailure() << msg;
  1772. }
  1773. const TestPartResult& r = results.GetTestPartResult(0);
  1774. if (r.type() != type) {
  1775. return AssertionFailure() << "Expected: " << expected << "\n"
  1776. << " Actual:\n"
  1777. << r;
  1778. }
  1779. if (strstr(r.message(), substr.c_str()) == NULL) {
  1780. return AssertionFailure() << "Expected: " << expected << " containing \""
  1781. << substr << "\"\n"
  1782. << " Actual:\n"
  1783. << r;
  1784. }
  1785. return AssertionSuccess();
  1786. }
  1787. // The constructor of SingleFailureChecker remembers where to look up
  1788. // test part results, what type of failure we expect, and what
  1789. // substring the failure message should contain.
  1790. SingleFailureChecker:: SingleFailureChecker(
  1791. const TestPartResultArray* results,
  1792. TestPartResult::Type type,
  1793. const string& substr)
  1794. : results_(results),
  1795. type_(type),
  1796. substr_(substr) {}
  1797. // The destructor of SingleFailureChecker verifies that the given
  1798. // TestPartResultArray contains exactly one failure that has the given
  1799. // type and contains the given substring. If that's not the case, a
  1800. // non-fatal failure will be generated.
  1801. SingleFailureChecker::~SingleFailureChecker() {
  1802. EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_);
  1803. }
  1804. DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
  1805. UnitTestImpl* unit_test) : unit_test_(unit_test) {}
  1806. void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
  1807. const TestPartResult& result) {
  1808. unit_test_->current_test_result()->AddTestPartResult(result);
  1809. unit_test_->listeners()->repeater()->OnTestPartResult(result);
  1810. }
  1811. DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
  1812. UnitTestImpl* unit_test) : unit_test_(unit_test) {}
  1813. void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
  1814. const TestPartResult& result) {
  1815. unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
  1816. }
  1817. // Returns the global test part result reporter.
  1818. TestPartResultReporterInterface*
  1819. UnitTestImpl::GetGlobalTestPartResultReporter() {
  1820. internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
  1821. return global_test_part_result_repoter_;
  1822. }
  1823. // Sets the global test part result reporter.
  1824. void UnitTestImpl::SetGlobalTestPartResultReporter(
  1825. TestPartResultReporterInterface* reporter) {
  1826. internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
  1827. global_test_part_result_repoter_ = reporter;
  1828. }
  1829. // Returns the test part result reporter for the current thread.
  1830. TestPartResultReporterInterface*
  1831. UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
  1832. return per_thread_test_part_result_reporter_.get();
  1833. }
  1834. // Sets the test part result reporter for the current thread.
  1835. void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
  1836. TestPartResultReporterInterface* reporter) {
  1837. per_thread_test_part_result_reporter_.set(reporter);
  1838. }
  1839. // Gets the number of successful test cases.
  1840. int UnitTestImpl::successful_test_case_count() const {
  1841. return CountIf(test_cases_, TestCasePassed);
  1842. }
  1843. // Gets the number of failed test cases.
  1844. int UnitTestImpl::failed_test_case_count() const {
  1845. return CountIf(test_cases_, TestCaseFailed);
  1846. }
  1847. // Gets the number of all test cases.
  1848. int UnitTestImpl::total_test_case_count() const {
  1849. return static_cast<int>(test_cases_.size());
  1850. }
  1851. // Gets the number of all test cases that contain at least one test
  1852. // that should run.
  1853. int UnitTestImpl::test_case_to_run_count() const {
  1854. return CountIf(test_cases_, ShouldRunTestCase);
  1855. }
  1856. // Gets the number of successful tests.
  1857. int UnitTestImpl::successful_test_count() const {
  1858. return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count);
  1859. }
  1860. // Gets the number of failed tests.
  1861. int UnitTestImpl::failed_test_count() const {
  1862. return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count);
  1863. }
  1864. // Gets the number of disabled tests that will be reported in the XML report.
  1865. int UnitTestImpl::reportable_disabled_test_count() const {
  1866. return SumOverTestCaseList(test_cases_,
  1867. &TestCase::reportable_disabled_test_count);
  1868. }
  1869. // Gets the number of disabled tests.
  1870. int UnitTestImpl::disabled_test_count() const {
  1871. return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count);
  1872. }
  1873. // Gets the number of tests to be printed in the XML report.
  1874. int UnitTestImpl::reportable_test_count() const {
  1875. return SumOverTestCaseList(test_cases_, &TestCase::reportable_test_count);
  1876. }
  1877. // Gets the number of all tests.
  1878. int UnitTestImpl::total_test_count() const {
  1879. return SumOverTestCaseList(test_cases_, &TestCase::total_test_count);
  1880. }
  1881. // Gets the number of tests that should run.
  1882. int UnitTestImpl::test_to_run_count() const {
  1883. return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count);
  1884. }
  1885. // Returns the current OS stack trace as an std::string.
  1886. //
  1887. // The maximum number of stack frames to be included is specified by
  1888. // the gtest_stack_trace_depth flag. The skip_count parameter
  1889. // specifies the number of top frames to be skipped, which doesn't
  1890. // count against the number of frames to be included.
  1891. //
  1892. // For example, if Foo() calls Bar(), which in turn calls
  1893. // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
  1894. // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
  1895. std::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
  1896. (void)skip_count;
  1897. return "";
  1898. }
  1899. // Returns the current time in milliseconds.
  1900. TimeInMillis GetTimeInMillis() {
  1901. #if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__)
  1902. // Difference between 1970-01-01 and 1601-01-01 in milliseconds.
  1903. // http://analogous.blogspot.com/2005/04/epoch.html
  1904. const TimeInMillis kJavaEpochToWinFileTimeDelta =
  1905. static_cast<TimeInMillis>(116444736UL) * 100000UL;
  1906. const DWORD kTenthMicrosInMilliSecond = 10000;
  1907. SYSTEMTIME now_systime;
  1908. FILETIME now_filetime;
  1909. ULARGE_INTEGER now_int64;
  1910. // TODO(kenton@google.com): Shouldn't this just use
  1911. // GetSystemTimeAsFileTime()?
  1912. GetSystemTime(&now_systime);
  1913. if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
  1914. now_int64.LowPart = now_filetime.dwLowDateTime;
  1915. now_int64.HighPart = now_filetime.dwHighDateTime;
  1916. now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
  1917. kJavaEpochToWinFileTimeDelta;
  1918. return now_int64.QuadPart;
  1919. }
  1920. return 0;
  1921. #elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_
  1922. __timeb64 now;
  1923. # ifdef _MSC_VER
  1924. // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996
  1925. // (deprecated function) there.
  1926. // TODO(kenton@google.com): Use GetTickCount()? Or use
  1927. // SystemTimeToFileTime()
  1928. # pragma warning(push) // Saves the current warning state.
  1929. # pragma warning(disable:4996) // Temporarily disables warning 4996.
  1930. _ftime64(&now);
  1931. # pragma warning(pop) // Restores the warning state.
  1932. # else
  1933. _ftime64(&now);
  1934. # endif // _MSC_VER
  1935. return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
  1936. #elif GTEST_HAS_GETTIMEOFDAY_
  1937. struct timeval now;
  1938. gettimeofday(&now, NULL);
  1939. return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
  1940. #else
  1941. # error "Don't know how to get the current time on your system."
  1942. #endif
  1943. }
  1944. // Utilities
  1945. // class String.
  1946. #if GTEST_OS_WINDOWS_MOBILE
  1947. // Creates a UTF-16 wide string from the given ANSI string, allocating
  1948. // memory using new. The caller is responsible for deleting the return
  1949. // value using delete[]. Returns the wide string, or NULL if the
  1950. // input is NULL.
  1951. LPCWSTR String::AnsiToUtf16(const char* ansi) {
  1952. if (!ansi) return NULL;
  1953. const int length = strlen(ansi);
  1954. const int unicode_length =
  1955. MultiByteToWideChar(CP_ACP, 0, ansi, length,
  1956. NULL, 0);
  1957. WCHAR* unicode = new WCHAR[unicode_length + 1];
  1958. MultiByteToWideChar(CP_ACP, 0, ansi, length,
  1959. unicode, unicode_length);
  1960. unicode[unicode_length] = 0;
  1961. return unicode;
  1962. }
  1963. // Creates an ANSI string from the given wide string, allocating
  1964. // memory using new. The caller is responsible for deleting the return
  1965. // value using delete[]. Returns the ANSI string, or NULL if the
  1966. // input is NULL.
  1967. const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
  1968. if (!utf16_str) return NULL;
  1969. const int ansi_length =
  1970. WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
  1971. NULL, 0, NULL, NULL);
  1972. char* ansi = new char[ansi_length + 1];
  1973. WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
  1974. ansi, ansi_length, NULL, NULL);
  1975. ansi[ansi_length] = 0;
  1976. return ansi;
  1977. }
  1978. #endif // GTEST_OS_WINDOWS_MOBILE
  1979. // Compares two C strings. Returns true iff they have the same content.
  1980. //
  1981. // Unlike strcmp(), this function can handle NULL argument(s). A NULL
  1982. // C string is considered different to any non-NULL C string,
  1983. // including the empty string.
  1984. bool String::CStringEquals(const char * lhs, const char * rhs) {
  1985. if ( lhs == NULL ) return rhs == NULL;
  1986. if ( rhs == NULL ) return false;
  1987. return strcmp(lhs, rhs) == 0;
  1988. }
  1989. #if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
  1990. // Converts an array of wide chars to a narrow string using the UTF-8
  1991. // encoding, and streams the result to the given Message object.
  1992. static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
  1993. Message* msg) {
  1994. for (size_t i = 0; i != length; ) { // NOLINT
  1995. if (wstr[i] != L'\0') {
  1996. *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
  1997. while (i != length && wstr[i] != L'\0')
  1998. i++;
  1999. } else {
  2000. *msg << '\0';
  2001. i++;
  2002. }
  2003. }
  2004. }
  2005. #endif // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
  2006. } // namespace internal
  2007. // Constructs an empty Message.
  2008. // We allocate the stringstream separately because otherwise each use of
  2009. // ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's
  2010. // stack frame leading to huge stack frames in some cases; gcc does not reuse
  2011. // the stack space.
  2012. Message::Message() : ss_(new ::std::stringstream) {
  2013. // By default, we want there to be enough precision when printing
  2014. // a double to a Message.
  2015. *ss_ << std::setprecision(std::numeric_limits<double>::digits10 + 2);
  2016. }
  2017. // These two overloads allow streaming a wide C string to a Message
  2018. // using the UTF-8 encoding.
  2019. Message& Message::operator <<(const wchar_t* wide_c_str) {
  2020. return *this << internal::String::ShowWideCString(wide_c_str);
  2021. }
  2022. Message& Message::operator <<(wchar_t* wide_c_str) {
  2023. return *this << internal::String::ShowWideCString(wide_c_str);
  2024. }
  2025. #if GTEST_HAS_STD_WSTRING
  2026. // Converts the given wide string to a narrow string using the UTF-8
  2027. // encoding, and streams the result to this Message object.
  2028. Message& Message::operator <<(const ::std::wstring& wstr) {
  2029. internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
  2030. return *this;
  2031. }
  2032. #endif // GTEST_HAS_STD_WSTRING
  2033. #if GTEST_HAS_GLOBAL_WSTRING
  2034. // Converts the given wide string to a narrow string using the UTF-8
  2035. // encoding, and streams the result to this Message object.
  2036. Message& Message::operator <<(const ::wstring& wstr) {
  2037. internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
  2038. return *this;
  2039. }
  2040. #endif // GTEST_HAS_GLOBAL_WSTRING
  2041. // Gets the text streamed to this object so far as an std::string.
  2042. // Each '\0' character in the buffer is replaced with "\\0".
  2043. std::string Message::GetString() const {
  2044. return internal::StringStreamToString(ss_.get());
  2045. }
  2046. // AssertionResult constructors.
  2047. // Used in EXPECT_TRUE/FALSE(assertion_result).
  2048. AssertionResult::AssertionResult(const AssertionResult& other)
  2049. : success_(other.success_),
  2050. message_(other.message_.get() != NULL ?
  2051. new ::std::string(*other.message_) :
  2052. static_cast< ::std::string*>(NULL)) {
  2053. }
  2054. // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
  2055. AssertionResult AssertionResult::operator!() const {
  2056. AssertionResult negation(!success_);
  2057. if (message_.get() != NULL)
  2058. negation << *message_;
  2059. return negation;
  2060. }
  2061. // Makes a successful assertion result.
  2062. AssertionResult AssertionSuccess() {
  2063. return AssertionResult(true);
  2064. }
  2065. // Makes a failed assertion result.
  2066. AssertionResult AssertionFailure() {
  2067. return AssertionResult(false);
  2068. }
  2069. // Makes a failed assertion result with the given failure message.
  2070. // Deprecated; use AssertionFailure() << message.
  2071. AssertionResult AssertionFailure(const Message& message) {
  2072. return AssertionFailure() << message;
  2073. }
  2074. namespace internal {
  2075. // Constructs and returns the message for an equality assertion
  2076. // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
  2077. //
  2078. // The first four parameters are the expressions used in the assertion
  2079. // and their values, as strings. For example, for ASSERT_EQ(foo, bar)
  2080. // where foo is 5 and bar is 6, we have:
  2081. //
  2082. // expected_expression: "foo"
  2083. // actual_expression: "bar"
  2084. // expected_value: "5"
  2085. // actual_value: "6"
  2086. //
  2087. // The ignoring_case parameter is true iff the assertion is a
  2088. // *_STRCASEEQ*. When it's true, the string " (ignoring case)" will
  2089. // be inserted into the message.
  2090. AssertionResult EqFailure(const char* expected_expression,
  2091. const char* actual_expression,
  2092. const std::string& expected_value,
  2093. const std::string& actual_value,
  2094. bool ignoring_case) {
  2095. Message msg;
  2096. msg << "Value of: " << actual_expression;
  2097. if (actual_value != actual_expression) {
  2098. msg << "\n Actual: " << actual_value;
  2099. }
  2100. msg << "\nExpected: " << expected_expression;
  2101. if (ignoring_case) {
  2102. msg << " (ignoring case)";
  2103. }
  2104. if (expected_value != expected_expression) {
  2105. msg << "\nWhich is: " << expected_value;
  2106. }
  2107. return AssertionFailure() << msg;
  2108. }
  2109. // Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
  2110. std::string GetBoolAssertionFailureMessage(
  2111. const AssertionResult& assertion_result,
  2112. const char* expression_text,
  2113. const char* actual_predicate_value,
  2114. const char* expected_predicate_value) {
  2115. const char* actual_message = assertion_result.message();
  2116. Message msg;
  2117. msg << "Value of: " << expression_text
  2118. << "\n Actual: " << actual_predicate_value;
  2119. if (actual_message[0] != '\0')
  2120. msg << " (" << actual_message << ")";
  2121. msg << "\nExpected: " << expected_predicate_value;
  2122. return msg.GetString();
  2123. }
  2124. // Helper function for implementing ASSERT_NEAR.
  2125. AssertionResult DoubleNearPredFormat(const char* expr1,
  2126. const char* expr2,
  2127. const char* abs_error_expr,
  2128. double val1,
  2129. double val2,
  2130. double abs_error) {
  2131. const double diff = fabs(val1 - val2);
  2132. if (diff <= abs_error) return AssertionSuccess();
  2133. // TODO(wan): do not print the value of an expression if it's
  2134. // already a literal.
  2135. return AssertionFailure()
  2136. << "The difference between " << expr1 << " and " << expr2
  2137. << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"
  2138. << expr1 << " evaluates to " << val1 << ",\n"
  2139. << expr2 << " evaluates to " << val2 << ", and\n"
  2140. << abs_error_expr << " evaluates to " << abs_error << ".";
  2141. }
  2142. // Helper template for implementing FloatLE() and DoubleLE().
  2143. template <typename RawType>
  2144. AssertionResult FloatingPointLE(const char* expr1,
  2145. const char* expr2,
  2146. RawType val1,
  2147. RawType val2) {
  2148. // Returns success if val1 is less than val2,
  2149. if (val1 < val2) {
  2150. return AssertionSuccess();
  2151. }
  2152. // or if val1 is almost equal to val2.
  2153. const FloatingPoint<RawType> lhs(val1), rhs(val2);
  2154. if (lhs.AlmostEquals(rhs)) {
  2155. return AssertionSuccess();
  2156. }
  2157. // Note that the above two checks will both fail if either val1 or
  2158. // val2 is NaN, as the IEEE floating-point standard requires that
  2159. // any predicate involving a NaN must return false.
  2160. ::std::stringstream val1_ss;
  2161. val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
  2162. << val1;
  2163. ::std::stringstream val2_ss;
  2164. val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
  2165. << val2;
  2166. return AssertionFailure()
  2167. << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
  2168. << " Actual: " << StringStreamToString(&val1_ss) << " vs "
  2169. << StringStreamToString(&val2_ss);
  2170. }
  2171. } // namespace internal
  2172. // Asserts that val1 is less than, or almost equal to, val2. Fails
  2173. // otherwise. In particular, it fails if either val1 or val2 is NaN.
  2174. AssertionResult FloatLE(const char* expr1, const char* expr2,
  2175. float val1, float val2) {
  2176. return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
  2177. }
  2178. // Asserts that val1 is less than, or almost equal to, val2. Fails
  2179. // otherwise. In particular, it fails if either val1 or val2 is NaN.
  2180. AssertionResult DoubleLE(const char* expr1, const char* expr2,
  2181. double val1, double val2) {
  2182. return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
  2183. }
  2184. namespace internal {
  2185. // The helper function for {ASSERT|EXPECT}_EQ with int or enum
  2186. // arguments.
  2187. AssertionResult CmpHelperEQ(const char* expected_expression,
  2188. const char* actual_expression,
  2189. BiggestInt expected,
  2190. BiggestInt actual) {
  2191. if (expected == actual) {
  2192. return AssertionSuccess();
  2193. }
  2194. return EqFailure(expected_expression,
  2195. actual_expression,
  2196. FormatForComparisonFailureMessage(expected, actual),
  2197. FormatForComparisonFailureMessage(actual, expected),
  2198. false);
  2199. }
  2200. // A macro for implementing the helper functions needed to implement
  2201. // ASSERT_?? and EXPECT_?? with integer or enum arguments. It is here
  2202. // just to avoid copy-and-paste of similar code.
  2203. #define GTEST_IMPL_CMP_HELPER_(op_name, op)\
  2204. AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
  2205. BiggestInt val1, BiggestInt val2) {\
  2206. if (val1 op val2) {\
  2207. return AssertionSuccess();\
  2208. } else {\
  2209. return AssertionFailure() \
  2210. << "Expected: (" << expr1 << ") " #op " (" << expr2\
  2211. << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
  2212. << " vs " << FormatForComparisonFailureMessage(val2, val1);\
  2213. }\
  2214. }
  2215. // Implements the helper function for {ASSERT|EXPECT}_NE with int or
  2216. // enum arguments.
  2217. GTEST_IMPL_CMP_HELPER_(NE, !=)
  2218. // Implements the helper function for {ASSERT|EXPECT}_LE with int or
  2219. // enum arguments.
  2220. GTEST_IMPL_CMP_HELPER_(LE, <=)
  2221. // Implements the helper function for {ASSERT|EXPECT}_LT with int or
  2222. // enum arguments.
  2223. GTEST_IMPL_CMP_HELPER_(LT, < )
  2224. // Implements the helper function for {ASSERT|EXPECT}_GE with int or
  2225. // enum arguments.
  2226. GTEST_IMPL_CMP_HELPER_(GE, >=)
  2227. // Implements the helper function for {ASSERT|EXPECT}_GT with int or
  2228. // enum arguments.
  2229. GTEST_IMPL_CMP_HELPER_(GT, > )
  2230. #undef GTEST_IMPL_CMP_HELPER_
  2231. // The helper function for {ASSERT|EXPECT}_STREQ.
  2232. AssertionResult CmpHelperSTREQ(const char* expected_expression,
  2233. const char* actual_expression,
  2234. const char* expected,
  2235. const char* actual) {
  2236. if (String::CStringEquals(expected, actual)) {
  2237. return AssertionSuccess();
  2238. }
  2239. return EqFailure(expected_expression,
  2240. actual_expression,
  2241. PrintToString(expected),
  2242. PrintToString(actual),
  2243. false);
  2244. }
  2245. // The helper function for {ASSERT|EXPECT}_STRCASEEQ.
  2246. AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression,
  2247. const char* actual_expression,
  2248. const char* expected,
  2249. const char* actual) {
  2250. if (String::CaseInsensitiveCStringEquals(expected, actual)) {
  2251. return AssertionSuccess();
  2252. }
  2253. return EqFailure(expected_expression,
  2254. actual_expression,
  2255. PrintToString(expected),
  2256. PrintToString(actual),
  2257. true);
  2258. }
  2259. // The helper function for {ASSERT|EXPECT}_STRNE.
  2260. AssertionResult CmpHelperSTRNE(const char* s1_expression,
  2261. const char* s2_expression,
  2262. const char* s1,
  2263. const char* s2) {
  2264. if (!String::CStringEquals(s1, s2)) {
  2265. return AssertionSuccess();
  2266. } else {
  2267. return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
  2268. << s2_expression << "), actual: \""
  2269. << s1 << "\" vs \"" << s2 << "\"";
  2270. }
  2271. }
  2272. // The helper function for {ASSERT|EXPECT}_STRCASENE.
  2273. AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
  2274. const char* s2_expression,
  2275. const char* s1,
  2276. const char* s2) {
  2277. if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
  2278. return AssertionSuccess();
  2279. } else {
  2280. return AssertionFailure()
  2281. << "Expected: (" << s1_expression << ") != ("
  2282. << s2_expression << ") (ignoring case), actual: \""
  2283. << s1 << "\" vs \"" << s2 << "\"";
  2284. }
  2285. }
  2286. } // namespace internal
  2287. namespace {
  2288. // Helper functions for implementing IsSubString() and IsNotSubstring().
  2289. // This group of overloaded functions return true iff needle is a
  2290. // substring of haystack. NULL is considered a substring of itself
  2291. // only.
  2292. bool IsSubstringPred(const char* needle, const char* haystack) {
  2293. if (needle == NULL || haystack == NULL)
  2294. return needle == haystack;
  2295. return strstr(haystack, needle) != NULL;
  2296. }
  2297. bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
  2298. if (needle == NULL || haystack == NULL)
  2299. return needle == haystack;
  2300. return wcsstr(haystack, needle) != NULL;
  2301. }
  2302. // StringType here can be either ::std::string or ::std::wstring.
  2303. template <typename StringType>
  2304. bool IsSubstringPred(const StringType& needle,
  2305. const StringType& haystack) {
  2306. return haystack.find(needle) != StringType::npos;
  2307. }
  2308. // This function implements either IsSubstring() or IsNotSubstring(),
  2309. // depending on the value of the expected_to_be_substring parameter.
  2310. // StringType here can be const char*, const wchar_t*, ::std::string,
  2311. // or ::std::wstring.
  2312. template <typename StringType>
  2313. AssertionResult IsSubstringImpl(
  2314. bool expected_to_be_substring,
  2315. const char* needle_expr, const char* haystack_expr,
  2316. const StringType& needle, const StringType& haystack) {
  2317. if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
  2318. return AssertionSuccess();
  2319. const bool is_wide_string = sizeof(needle[0]) > 1;
  2320. const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
  2321. return AssertionFailure()
  2322. << "Value of: " << needle_expr << "\n"
  2323. << " Actual: " << begin_string_quote << needle << "\"\n"
  2324. << "Expected: " << (expected_to_be_substring ? "" : "not ")
  2325. << "a substring of " << haystack_expr << "\n"
  2326. << "Which is: " << begin_string_quote << haystack << "\"";
  2327. }
  2328. } // namespace
  2329. // IsSubstring() and IsNotSubstring() check whether needle is a
  2330. // substring of haystack (NULL is considered a substring of itself
  2331. // only), and return an appropriate error message when they fail.
  2332. AssertionResult IsSubstring(
  2333. const char* needle_expr, const char* haystack_expr,
  2334. const char* needle, const char* haystack) {
  2335. return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
  2336. }
  2337. AssertionResult IsSubstring(
  2338. const char* needle_expr, const char* haystack_expr,
  2339. const wchar_t* needle, const wchar_t* haystack) {
  2340. return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
  2341. }
  2342. AssertionResult IsNotSubstring(
  2343. const char* needle_expr, const char* haystack_expr,
  2344. const char* needle, const char* haystack) {
  2345. return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
  2346. }
  2347. AssertionResult IsNotSubstring(
  2348. const char* needle_expr, const char* haystack_expr,
  2349. const wchar_t* needle, const wchar_t* haystack) {
  2350. return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
  2351. }
  2352. AssertionResult IsSubstring(
  2353. const char* needle_expr, const char* haystack_expr,
  2354. const ::std::string& needle, const ::std::string& haystack) {
  2355. return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
  2356. }
  2357. AssertionResult IsNotSubstring(
  2358. const char* needle_expr, const char* haystack_expr,
  2359. const ::std::string& needle, const ::std::string& haystack) {
  2360. return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
  2361. }
  2362. #if GTEST_HAS_STD_WSTRING
  2363. AssertionResult IsSubstring(
  2364. const char* needle_expr, const char* haystack_expr,
  2365. const ::std::wstring& needle, const ::std::wstring& haystack) {
  2366. return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
  2367. }
  2368. AssertionResult IsNotSubstring(
  2369. const char* needle_expr, const char* haystack_expr,
  2370. const ::std::wstring& needle, const ::std::wstring& haystack) {
  2371. return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
  2372. }
  2373. #endif // GTEST_HAS_STD_WSTRING
  2374. namespace internal {
  2375. #if GTEST_OS_WINDOWS
  2376. namespace {
  2377. // Helper function for IsHRESULT{SuccessFailure} predicates
  2378. AssertionResult HRESULTFailureHelper(const char* expr,
  2379. const char* expected,
  2380. long hr) { // NOLINT
  2381. # if GTEST_OS_WINDOWS_MOBILE
  2382. // Windows CE doesn't support FormatMessage.
  2383. const char error_text[] = "";
  2384. # else
  2385. // Looks up the human-readable system message for the HRESULT code
  2386. // and since we're not passing any params to FormatMessage, we don't
  2387. // want inserts expanded.
  2388. const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
  2389. FORMAT_MESSAGE_IGNORE_INSERTS;
  2390. const DWORD kBufSize = 4096;
  2391. // Gets the system's human readable message string for this HRESULT.
  2392. char error_text[kBufSize] = { '\0' };
  2393. DWORD message_length = ::FormatMessageA(kFlags,
  2394. 0, // no source, we're asking system
  2395. hr, // the error
  2396. 0, // no line width restrictions
  2397. error_text, // output buffer
  2398. kBufSize, // buf size
  2399. NULL); // no arguments for inserts
  2400. // Trims tailing white space (FormatMessage leaves a trailing CR-LF)
  2401. for (; message_length && IsSpace(error_text[message_length - 1]);
  2402. --message_length) {
  2403. error_text[message_length - 1] = '\0';
  2404. }
  2405. # endif // GTEST_OS_WINDOWS_MOBILE
  2406. const std::string error_hex("0x" + String::FormatHexInt(hr));
  2407. return ::testing::AssertionFailure()
  2408. << "Expected: " << expr << " " << expected << ".\n"
  2409. << " Actual: " << error_hex << " " << error_text << "\n";
  2410. }
  2411. } // namespace
  2412. AssertionResult IsHRESULTSuccess(const char* expr, long hr) { // NOLINT
  2413. if (SUCCEEDED(hr)) {
  2414. return AssertionSuccess();
  2415. }
  2416. return HRESULTFailureHelper(expr, "succeeds", hr);
  2417. }
  2418. AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT
  2419. if (FAILED(hr)) {
  2420. return AssertionSuccess();
  2421. }
  2422. return HRESULTFailureHelper(expr, "fails", hr);
  2423. }
  2424. #endif // GTEST_OS_WINDOWS
  2425. // Utility functions for encoding Unicode text (wide strings) in
  2426. // UTF-8.
  2427. // A Unicode code-point can have upto 21 bits, and is encoded in UTF-8
  2428. // like this:
  2429. //
  2430. // Code-point length Encoding
  2431. // 0 - 7 bits 0xxxxxxx
  2432. // 8 - 11 bits 110xxxxx 10xxxxxx
  2433. // 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx
  2434. // 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  2435. // The maximum code-point a one-byte UTF-8 sequence can represent.
  2436. const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) << 7) - 1;
  2437. // The maximum code-point a two-byte UTF-8 sequence can represent.
  2438. const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1;
  2439. // The maximum code-point a three-byte UTF-8 sequence can represent.
  2440. const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2*6)) - 1;
  2441. // The maximum code-point a four-byte UTF-8 sequence can represent.
  2442. const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3*6)) - 1;
  2443. // Chops off the n lowest bits from a bit pattern. Returns the n
  2444. // lowest bits. As a side effect, the original bit pattern will be
  2445. // shifted to the right by n bits.
  2446. inline UInt32 ChopLowBits(UInt32* bits, int n) {
  2447. const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1);
  2448. *bits >>= n;
  2449. return low_bits;
  2450. }
  2451. // Converts a Unicode code point to a narrow string in UTF-8 encoding.
  2452. // code_point parameter is of type UInt32 because wchar_t may not be
  2453. // wide enough to contain a code point.
  2454. // If the code_point is not a valid Unicode code point
  2455. // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
  2456. // to "(Invalid Unicode 0xXXXXXXXX)".
  2457. std::string CodePointToUtf8(UInt32 code_point) {
  2458. if (code_point > kMaxCodePoint4) {
  2459. return "(Invalid Unicode 0x" + String::FormatHexInt(code_point) + ")";
  2460. }
  2461. char str[5]; // Big enough for the largest valid code point.
  2462. if (code_point <= kMaxCodePoint1) {
  2463. str[1] = '\0';
  2464. str[0] = static_cast<char>(code_point); // 0xxxxxxx
  2465. } else if (code_point <= kMaxCodePoint2) {
  2466. str[2] = '\0';
  2467. str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  2468. str[0] = static_cast<char>(0xC0 | code_point); // 110xxxxx
  2469. } else if (code_point <= kMaxCodePoint3) {
  2470. str[3] = '\0';
  2471. str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  2472. str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  2473. str[0] = static_cast<char>(0xE0 | code_point); // 1110xxxx
  2474. } else { // code_point <= kMaxCodePoint4
  2475. str[4] = '\0';
  2476. str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  2477. str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  2478. str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
  2479. str[0] = static_cast<char>(0xF0 | code_point); // 11110xxx
  2480. }
  2481. return str;
  2482. }
  2483. // The following two functions only make sense if the the system
  2484. // uses UTF-16 for wide string encoding. All supported systems
  2485. // with 16 bit wchar_t (Windows, Cygwin, Symbian OS) do use UTF-16.
  2486. // Determines if the arguments constitute UTF-16 surrogate pair
  2487. // and thus should be combined into a single Unicode code point
  2488. // using CreateCodePointFromUtf16SurrogatePair.
  2489. inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
  2490. return sizeof(wchar_t) == 2 &&
  2491. (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;
  2492. }
  2493. // Creates a Unicode code point from UTF16 surrogate pair.
  2494. inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first,
  2495. wchar_t second) {
  2496. const UInt32 mask = (1 << 10) - 1;
  2497. return (sizeof(wchar_t) == 2) ?
  2498. (((first & mask) << 10) | (second & mask)) + 0x10000 :
  2499. // This function should not be called when the condition is
  2500. // false, but we provide a sensible default in case it is.
  2501. static_cast<UInt32>(first);
  2502. }
  2503. // Converts a wide string to a narrow string in UTF-8 encoding.
  2504. // The wide string is assumed to have the following encoding:
  2505. // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
  2506. // UTF-32 if sizeof(wchar_t) == 4 (on Linux)
  2507. // Parameter str points to a null-terminated wide string.
  2508. // Parameter num_chars may additionally limit the number
  2509. // of wchar_t characters processed. -1 is used when the entire string
  2510. // should be processed.
  2511. // If the string contains code points that are not valid Unicode code points
  2512. // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
  2513. // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
  2514. // and contains invalid UTF-16 surrogate pairs, values in those pairs
  2515. // will be encoded as individual Unicode characters from Basic Normal Plane.
  2516. std::string WideStringToUtf8(const wchar_t* str, int num_chars) {
  2517. if (num_chars == -1)
  2518. num_chars = static_cast<int>(wcslen(str));
  2519. ::std::stringstream stream;
  2520. for (int i = 0; i < num_chars; ++i) {
  2521. UInt32 unicode_code_point;
  2522. if (str[i] == L'\0') {
  2523. break;
  2524. } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
  2525. unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i],
  2526. str[i + 1]);
  2527. i++;
  2528. } else {
  2529. unicode_code_point = static_cast<UInt32>(str[i]);
  2530. }
  2531. stream << CodePointToUtf8(unicode_code_point);
  2532. }
  2533. return StringStreamToString(&stream);
  2534. }
  2535. // Converts a wide C string to an std::string using the UTF-8 encoding.
  2536. // NULL will be converted to "(null)".
  2537. std::string String::ShowWideCString(const wchar_t * wide_c_str) {
  2538. if (wide_c_str == NULL) return "(null)";
  2539. return internal::WideStringToUtf8(wide_c_str, -1);
  2540. }
  2541. // Compares two wide C strings. Returns true iff they have the same
  2542. // content.
  2543. //
  2544. // Unlike wcscmp(), this function can handle NULL argument(s). A NULL
  2545. // C string is considered different to any non-NULL C string,
  2546. // including the empty string.
  2547. bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {
  2548. if (lhs == NULL) return rhs == NULL;
  2549. if (rhs == NULL) return false;
  2550. return wcscmp(lhs, rhs) == 0;
  2551. }
  2552. // Helper function for *_STREQ on wide strings.
  2553. AssertionResult CmpHelperSTREQ(const char* expected_expression,
  2554. const char* actual_expression,
  2555. const wchar_t* expected,
  2556. const wchar_t* actual) {
  2557. if (String::WideCStringEquals(expected, actual)) {
  2558. return AssertionSuccess();
  2559. }
  2560. return EqFailure(expected_expression,
  2561. actual_expression,
  2562. PrintToString(expected),
  2563. PrintToString(actual),
  2564. false);
  2565. }
  2566. // Helper function for *_STRNE on wide strings.
  2567. AssertionResult CmpHelperSTRNE(const char* s1_expression,
  2568. const char* s2_expression,
  2569. const wchar_t* s1,
  2570. const wchar_t* s2) {
  2571. if (!String::WideCStringEquals(s1, s2)) {
  2572. return AssertionSuccess();
  2573. }
  2574. return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
  2575. << s2_expression << "), actual: "
  2576. << PrintToString(s1)
  2577. << " vs " << PrintToString(s2);
  2578. }
  2579. // Compares two C strings, ignoring case. Returns true iff they have
  2580. // the same content.
  2581. //
  2582. // Unlike strcasecmp(), this function can handle NULL argument(s). A
  2583. // NULL C string is considered different to any non-NULL C string,
  2584. // including the empty string.
  2585. bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) {
  2586. if (lhs == NULL)
  2587. return rhs == NULL;
  2588. if (rhs == NULL)
  2589. return false;
  2590. return posix::StrCaseCmp(lhs, rhs) == 0;
  2591. }
  2592. // Compares two wide C strings, ignoring case. Returns true iff they
  2593. // have the same content.
  2594. //
  2595. // Unlike wcscasecmp(), this function can handle NULL argument(s).
  2596. // A NULL C string is considered different to any non-NULL wide C string,
  2597. // including the empty string.
  2598. // NB: The implementations on different platforms slightly differ.
  2599. // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
  2600. // environment variable. On GNU platform this method uses wcscasecmp
  2601. // which compares according to LC_CTYPE category of the current locale.
  2602. // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
  2603. // current locale.
  2604. bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
  2605. const wchar_t* rhs) {
  2606. if (lhs == NULL) return rhs == NULL;
  2607. if (rhs == NULL) return false;
  2608. #if GTEST_OS_WINDOWS
  2609. return _wcsicmp(lhs, rhs) == 0;
  2610. #elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID
  2611. return wcscasecmp(lhs, rhs) == 0;
  2612. #else
  2613. // Android, Mac OS X and Cygwin don't define wcscasecmp.
  2614. // Other unknown OSes may not define it either.
  2615. wint_t left, right;
  2616. do {
  2617. left = towlower(*lhs++);
  2618. right = towlower(*rhs++);
  2619. } while (left && left == right);
  2620. return left == right;
  2621. #endif // OS selector
  2622. }
  2623. // Returns true iff str ends with the given suffix, ignoring case.
  2624. // Any string is considered to end with an empty suffix.
  2625. bool String::EndsWithCaseInsensitive(
  2626. const std::string& str, const std::string& suffix) {
  2627. const size_t str_len = str.length();
  2628. const size_t suffix_len = suffix.length();
  2629. return (str_len >= suffix_len) &&
  2630. CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len,
  2631. suffix.c_str());
  2632. }
  2633. // Formats an int value as "%02d".
  2634. std::string String::FormatIntWidth2(int value) {
  2635. std::stringstream ss;
  2636. ss << std::setfill('0') << std::setw(2) << value;
  2637. return ss.str();
  2638. }
  2639. // Formats an int value as "%X".
  2640. std::string String::FormatHexInt(int value) {
  2641. std::stringstream ss;
  2642. ss << std::hex << std::uppercase << value;
  2643. return ss.str();
  2644. }
  2645. // Formats a byte as "%02X".
  2646. std::string String::FormatByte(unsigned char value) {
  2647. std::stringstream ss;
  2648. ss << std::setfill('0') << std::setw(2) << std::hex << std::uppercase
  2649. << static_cast<unsigned int>(value);
  2650. return ss.str();
  2651. }
  2652. // Converts the buffer in a stringstream to an std::string, converting NUL
  2653. // bytes to "\\0" along the way.
  2654. std::string StringStreamToString(::std::stringstream* ss) {
  2655. const ::std::string& str = ss->str();
  2656. const char* const start = str.c_str();
  2657. const char* const end = start + str.length();
  2658. std::string result;
  2659. result.reserve(2 * (end - start));
  2660. for (const char* ch = start; ch != end; ++ch) {
  2661. if (*ch == '\0') {
  2662. result += "\\0"; // Replaces NUL with "\\0";
  2663. } else {
  2664. result += *ch;
  2665. }
  2666. }
  2667. return result;
  2668. }
  2669. // Appends the user-supplied message to the Google-Test-generated message.
  2670. std::string AppendUserMessage(const std::string& gtest_msg,
  2671. const Message& user_msg) {
  2672. // Appends the user message if it's non-empty.
  2673. const std::string user_msg_string = user_msg.GetString();
  2674. if (user_msg_string.empty()) {
  2675. return gtest_msg;
  2676. }
  2677. return gtest_msg + "\n" + user_msg_string;
  2678. }
  2679. } // namespace internal
  2680. // class TestResult
  2681. // Creates an empty TestResult.
  2682. TestResult::TestResult()
  2683. : death_test_count_(0),
  2684. elapsed_time_(0) {
  2685. }
  2686. // D'tor.
  2687. TestResult::~TestResult() {
  2688. }
  2689. // Returns the i-th test part result among all the results. i can
  2690. // range from 0 to total_part_count() - 1. If i is not in that range,
  2691. // aborts the program.
  2692. const TestPartResult& TestResult::GetTestPartResult(int i) const {
  2693. if (i < 0 || i >= total_part_count())
  2694. internal::posix::Abort();
  2695. return test_part_results_.at(i);
  2696. }
  2697. // Returns the i-th test property. i can range from 0 to
  2698. // test_property_count() - 1. If i is not in that range, aborts the
  2699. // program.
  2700. const TestProperty& TestResult::GetTestProperty(int i) const {
  2701. if (i < 0 || i >= test_property_count())
  2702. internal::posix::Abort();
  2703. return test_properties_.at(i);
  2704. }
  2705. // Clears the test part results.
  2706. void TestResult::ClearTestPartResults() {
  2707. test_part_results_.clear();
  2708. }
  2709. // Adds a test part result to the list.
  2710. void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
  2711. test_part_results_.push_back(test_part_result);
  2712. }
  2713. // Adds a test property to the list. If a property with the same key as the
  2714. // supplied property is already represented, the value of this test_property
  2715. // replaces the old value for that key.
  2716. void TestResult::RecordProperty(const std::string& xml_element,
  2717. const TestProperty& test_property) {
  2718. if (!ValidateTestProperty(xml_element, test_property)) {
  2719. return;
  2720. }
  2721. internal::MutexLock lock(&test_properites_mutex_);
  2722. const std::vector<TestProperty>::iterator property_with_matching_key =
  2723. std::find_if(test_properties_.begin(), test_properties_.end(),
  2724. internal::TestPropertyKeyIs(test_property.key()));
  2725. if (property_with_matching_key == test_properties_.end()) {
  2726. test_properties_.push_back(test_property);
  2727. return;
  2728. }
  2729. property_with_matching_key->SetValue(test_property.value());
  2730. }
  2731. // The list of reserved attributes used in the <testsuites> element of XML
  2732. // output.
  2733. static const char* const kReservedTestSuitesAttributes[] = {
  2734. "disabled",
  2735. "errors",
  2736. "failures",
  2737. "name",
  2738. "random_seed",
  2739. "tests",
  2740. "time",
  2741. "timestamp"
  2742. };
  2743. // The list of reserved attributes used in the <testsuite> element of XML
  2744. // output.
  2745. static const char* const kReservedTestSuiteAttributes[] = {
  2746. "disabled",
  2747. "errors",
  2748. "failures",
  2749. "name",
  2750. "tests",
  2751. "time"
  2752. };
  2753. // The list of reserved attributes used in the <testcase> element of XML output.
  2754. static const char* const kReservedTestCaseAttributes[] = {
  2755. "classname",
  2756. "name",
  2757. "status",
  2758. "time",
  2759. "type_param",
  2760. "value_param"
  2761. };
  2762. template <int kSize>
  2763. std::vector<std::string> ArrayAsVector(const char* const (&array)[kSize]) {
  2764. return std::vector<std::string>(array, array + kSize);
  2765. }
  2766. static std::vector<std::string> GetReservedAttributesForElement(
  2767. const std::string& xml_element) {
  2768. if (xml_element == "testsuites") {
  2769. return ArrayAsVector(kReservedTestSuitesAttributes);
  2770. } else if (xml_element == "testsuite") {
  2771. return ArrayAsVector(kReservedTestSuiteAttributes);
  2772. } else if (xml_element == "testcase") {
  2773. return ArrayAsVector(kReservedTestCaseAttributes);
  2774. } else {
  2775. GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element;
  2776. }
  2777. // This code is unreachable but some compilers may not realizes that.
  2778. return std::vector<std::string>();
  2779. }
  2780. static std::string FormatWordList(const std::vector<std::string>& words) {
  2781. Message word_list;
  2782. for (size_t i = 0; i < words.size(); ++i) {
  2783. if (i > 0 && words.size() > 2) {
  2784. word_list << ", ";
  2785. }
  2786. if (i == words.size() - 1) {
  2787. word_list << "and ";
  2788. }
  2789. word_list << "'" << words[i] << "'";
  2790. }
  2791. return word_list.GetString();
  2792. }
  2793. bool ValidateTestPropertyName(const std::string& property_name,
  2794. const std::vector<std::string>& reserved_names) {
  2795. if (std::find(reserved_names.begin(), reserved_names.end(), property_name) !=
  2796. reserved_names.end()) {
  2797. ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name
  2798. << " (" << FormatWordList(reserved_names)
  2799. << " are reserved by " << GTEST_NAME_ << ")";
  2800. return false;
  2801. }
  2802. return true;
  2803. }
  2804. // Adds a failure if the key is a reserved attribute of the element named
  2805. // xml_element. Returns true if the property is valid.
  2806. bool TestResult::ValidateTestProperty(const std::string& xml_element,
  2807. const TestProperty& test_property) {
  2808. return ValidateTestPropertyName(test_property.key(),
  2809. GetReservedAttributesForElement(xml_element));
  2810. }
  2811. // Clears the object.
  2812. void TestResult::Clear() {
  2813. test_part_results_.clear();
  2814. test_properties_.clear();
  2815. death_test_count_ = 0;
  2816. elapsed_time_ = 0;
  2817. }
  2818. // Returns true iff the test failed.
  2819. bool TestResult::Failed() const {
  2820. for (int i = 0; i < total_part_count(); ++i) {
  2821. if (GetTestPartResult(i).failed())
  2822. return true;
  2823. }
  2824. return false;
  2825. }
  2826. // Returns true iff the test part fatally failed.
  2827. static bool TestPartFatallyFailed(const TestPartResult& result) {
  2828. return result.fatally_failed();
  2829. }
  2830. // Returns true iff the test fatally failed.
  2831. bool TestResult::HasFatalFailure() const {
  2832. return CountIf(test_part_results_, TestPartFatallyFailed) > 0;
  2833. }
  2834. // Returns true iff the test part non-fatally failed.
  2835. static bool TestPartNonfatallyFailed(const TestPartResult& result) {
  2836. return result.nonfatally_failed();
  2837. }
  2838. // Returns true iff the test has a non-fatal failure.
  2839. bool TestResult::HasNonfatalFailure() const {
  2840. return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0;
  2841. }
  2842. // Gets the number of all test parts. This is the sum of the number
  2843. // of successful test parts and the number of failed test parts.
  2844. int TestResult::total_part_count() const {
  2845. return static_cast<int>(test_part_results_.size());
  2846. }
  2847. // Returns the number of the test properties.
  2848. int TestResult::test_property_count() const {
  2849. return static_cast<int>(test_properties_.size());
  2850. }
  2851. // class Test
  2852. // Creates a Test object.
  2853. // The c'tor saves the values of all Google Test flags.
  2854. Test::Test()
  2855. : gtest_flag_saver_(new internal::GTestFlagSaver) {
  2856. }
  2857. // The d'tor restores the values of all Google Test flags.
  2858. Test::~Test() {
  2859. delete gtest_flag_saver_;
  2860. }
  2861. // Sets up the test fixture.
  2862. //
  2863. // A sub-class may override this.
  2864. void Test::SetUp() {
  2865. }
  2866. // Tears down the test fixture.
  2867. //
  2868. // A sub-class may override this.
  2869. void Test::TearDown() {
  2870. }
  2871. // Allows user supplied key value pairs to be recorded for later output.
  2872. void Test::RecordProperty(const std::string& key, const std::string& value) {
  2873. UnitTest::GetInstance()->RecordProperty(key, value);
  2874. }
  2875. // Allows user supplied key value pairs to be recorded for later output.
  2876. void Test::RecordProperty(const std::string& key, int value) {
  2877. Message value_message;
  2878. value_message << value;
  2879. RecordProperty(key, value_message.GetString().c_str());
  2880. }
  2881. namespace internal {
  2882. void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
  2883. const std::string& message) {
  2884. // This function is a friend of UnitTest and as such has access to
  2885. // AddTestPartResult.
  2886. UnitTest::GetInstance()->AddTestPartResult(
  2887. result_type,
  2888. NULL, // No info about the source file where the exception occurred.
  2889. -1, // We have no info on which line caused the exception.
  2890. message,
  2891. ""); // No stack trace, either.
  2892. }
  2893. } // namespace internal
  2894. // Google Test requires all tests in the same test case to use the same test
  2895. // fixture class. This function checks if the current test has the
  2896. // same fixture class as the first test in the current test case. If
  2897. // yes, it returns true; otherwise it generates a Google Test failure and
  2898. // returns false.
  2899. bool Test::HasSameFixtureClass() {
  2900. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  2901. const TestCase* const test_case = impl->current_test_case();
  2902. // Info about the first test in the current test case.
  2903. const TestInfo* const first_test_info = test_case->test_info_list()[0];
  2904. const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_;
  2905. const char* const first_test_name = first_test_info->name();
  2906. // Info about the current test.
  2907. const TestInfo* const this_test_info = impl->current_test_info();
  2908. const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_;
  2909. const char* const this_test_name = this_test_info->name();
  2910. if (this_fixture_id != first_fixture_id) {
  2911. // Is the first test defined using TEST?
  2912. const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();
  2913. // Is this test defined using TEST?
  2914. const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();
  2915. if (first_is_TEST || this_is_TEST) {
  2916. // The user mixed TEST and TEST_F in this test case - we'll tell
  2917. // him/her how to fix it.
  2918. // Gets the name of the TEST and the name of the TEST_F. Note
  2919. // that first_is_TEST and this_is_TEST cannot both be true, as
  2920. // the fixture IDs are different for the two tests.
  2921. const char* const TEST_name =
  2922. first_is_TEST ? first_test_name : this_test_name;
  2923. const char* const TEST_F_name =
  2924. first_is_TEST ? this_test_name : first_test_name;
  2925. ADD_FAILURE()
  2926. << "All tests in the same test case must use the same test fixture\n"
  2927. << "class, so mixing TEST_F and TEST in the same test case is\n"
  2928. << "illegal. In test case " << this_test_info->test_case_name()
  2929. << ",\n"
  2930. << "test " << TEST_F_name << " is defined using TEST_F but\n"
  2931. << "test " << TEST_name << " is defined using TEST. You probably\n"
  2932. << "want to change the TEST to TEST_F or move it to another test\n"
  2933. << "case.";
  2934. } else {
  2935. // The user defined two fixture classes with the same name in
  2936. // two namespaces - we'll tell him/her how to fix it.
  2937. ADD_FAILURE()
  2938. << "All tests in the same test case must use the same test fixture\n"
  2939. << "class. However, in test case "
  2940. << this_test_info->test_case_name() << ",\n"
  2941. << "you defined test " << first_test_name
  2942. << " and test " << this_test_name << "\n"
  2943. << "using two different test fixture classes. This can happen if\n"
  2944. << "the two classes are from different namespaces or translation\n"
  2945. << "units and have the same name. You should probably rename one\n"
  2946. << "of the classes to put the tests into different test cases.";
  2947. }
  2948. return false;
  2949. }
  2950. return true;
  2951. }
  2952. #if GTEST_HAS_SEH
  2953. // Adds an "exception thrown" fatal failure to the current test. This
  2954. // function returns its result via an output parameter pointer because VC++
  2955. // prohibits creation of objects with destructors on stack in functions
  2956. // using __try (see error C2712).
  2957. static std::string* FormatSehExceptionMessage(DWORD exception_code,
  2958. const char* location) {
  2959. Message message;
  2960. message << "SEH exception with code 0x" << std::setbase(16) <<
  2961. exception_code << std::setbase(10) << " thrown in " << location << ".";
  2962. return new std::string(message.GetString());
  2963. }
  2964. #endif // GTEST_HAS_SEH
  2965. namespace internal {
  2966. #if GTEST_HAS_EXCEPTIONS
  2967. // Adds an "exception thrown" fatal failure to the current test.
  2968. static std::string FormatCxxExceptionMessage(const char* description,
  2969. const char* location) {
  2970. Message message;
  2971. if (description != NULL) {
  2972. message << "C++ exception with description \"" << description << "\"";
  2973. } else {
  2974. message << "Unknown C++ exception";
  2975. }
  2976. message << " thrown in " << location << ".";
  2977. return message.GetString();
  2978. }
  2979. static std::string PrintTestPartResultToString(
  2980. const TestPartResult& test_part_result);
  2981. GoogleTestFailureException::GoogleTestFailureException(
  2982. const TestPartResult& failure)
  2983. : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
  2984. #endif // GTEST_HAS_EXCEPTIONS
  2985. // We put these helper functions in the internal namespace as IBM's xlC
  2986. // compiler rejects the code if they were declared static.
  2987. // Runs the given method and handles SEH exceptions it throws, when
  2988. // SEH is supported; returns the 0-value for type Result in case of an
  2989. // SEH exception. (Microsoft compilers cannot handle SEH and C++
  2990. // exceptions in the same function. Therefore, we provide a separate
  2991. // wrapper function for handling SEH exceptions.)
  2992. template <class T, typename Result>
  2993. Result HandleSehExceptionsInMethodIfSupported(
  2994. T* object, Result (T::*method)(), const char* location) {
  2995. #if GTEST_HAS_SEH
  2996. __try {
  2997. return (object->*method)();
  2998. } __except (internal::UnitTestOptions::GTestShouldProcessSEH( // NOLINT
  2999. GetExceptionCode())) {
  3000. // We create the exception message on the heap because VC++ prohibits
  3001. // creation of objects with destructors on stack in functions using __try
  3002. // (see error C2712).
  3003. std::string* exception_message = FormatSehExceptionMessage(
  3004. GetExceptionCode(), location);
  3005. internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
  3006. *exception_message);
  3007. delete exception_message;
  3008. return static_cast<Result>(0);
  3009. }
  3010. #else
  3011. (void)location;
  3012. return (object->*method)();
  3013. #endif // GTEST_HAS_SEH
  3014. }
  3015. // Runs the given method and catches and reports C++ and/or SEH-style
  3016. // exceptions, if they are supported; returns the 0-value for type
  3017. // Result in case of an SEH exception.
  3018. template <class T, typename Result>
  3019. Result HandleExceptionsInMethodIfSupported(
  3020. T* object, Result (T::*method)(), const char* location) {
  3021. // NOTE: The user code can affect the way in which Google Test handles
  3022. // exceptions by setting GTEST_FLAG(catch_exceptions), but only before
  3023. // RUN_ALL_TESTS() starts. It is technically possible to check the flag
  3024. // after the exception is caught and either report or re-throw the
  3025. // exception based on the flag's value:
  3026. //
  3027. // try {
  3028. // // Perform the test method.
  3029. // } catch (...) {
  3030. // if (GTEST_FLAG(catch_exceptions))
  3031. // // Report the exception as failure.
  3032. // else
  3033. // throw; // Re-throws the original exception.
  3034. // }
  3035. //
  3036. // However, the purpose of this flag is to allow the program to drop into
  3037. // the debugger when the exception is thrown. On most platforms, once the
  3038. // control enters the catch block, the exception origin information is
  3039. // lost and the debugger will stop the program at the point of the
  3040. // re-throw in this function -- instead of at the point of the original
  3041. // throw statement in the code under test. For this reason, we perform
  3042. // the check early, sacrificing the ability to affect Google Test's
  3043. // exception handling in the method where the exception is thrown.
  3044. if (internal::GetUnitTestImpl()->catch_exceptions()) {
  3045. #if GTEST_HAS_EXCEPTIONS
  3046. try {
  3047. return HandleSehExceptionsInMethodIfSupported(object, method, location);
  3048. } catch (const internal::GoogleTestFailureException&) { // NOLINT
  3049. // This exception type can only be thrown by a failed Google
  3050. // Test assertion with the intention of letting another testing
  3051. // framework catch it. Therefore we just re-throw it.
  3052. throw;
  3053. } catch (const std::exception& e) { // NOLINT
  3054. internal::ReportFailureInUnknownLocation(
  3055. TestPartResult::kFatalFailure,
  3056. FormatCxxExceptionMessage(e.what(), location));
  3057. } catch (...) { // NOLINT
  3058. internal::ReportFailureInUnknownLocation(
  3059. TestPartResult::kFatalFailure,
  3060. FormatCxxExceptionMessage(NULL, location));
  3061. }
  3062. return static_cast<Result>(0);
  3063. #else
  3064. return HandleSehExceptionsInMethodIfSupported(object, method, location);
  3065. #endif // GTEST_HAS_EXCEPTIONS
  3066. } else {
  3067. return (object->*method)();
  3068. }
  3069. }
  3070. } // namespace internal
  3071. // Runs the test and updates the test result.
  3072. void Test::Run() {
  3073. if (!HasSameFixtureClass()) return;
  3074. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  3075. impl->os_stack_trace_getter()->UponLeavingGTest();
  3076. internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()");
  3077. // We will run the test only if SetUp() was successful.
  3078. if (!HasFatalFailure()) {
  3079. impl->os_stack_trace_getter()->UponLeavingGTest();
  3080. internal::HandleExceptionsInMethodIfSupported(
  3081. this, &Test::TestBody, "the test body");
  3082. }
  3083. // However, we want to clean up as much as possible. Hence we will
  3084. // always call TearDown(), even if SetUp() or the test body has
  3085. // failed.
  3086. impl->os_stack_trace_getter()->UponLeavingGTest();
  3087. internal::HandleExceptionsInMethodIfSupported(
  3088. this, &Test::TearDown, "TearDown()");
  3089. }
  3090. // Returns true iff the current test has a fatal failure.
  3091. bool Test::HasFatalFailure() {
  3092. return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
  3093. }
  3094. // Returns true iff the current test has a non-fatal failure.
  3095. bool Test::HasNonfatalFailure() {
  3096. return internal::GetUnitTestImpl()->current_test_result()->
  3097. HasNonfatalFailure();
  3098. }
  3099. // class TestInfo
  3100. // Constructs a TestInfo object. It assumes ownership of the test factory
  3101. // object.
  3102. TestInfo::TestInfo(const std::string& a_test_case_name,
  3103. const std::string& a_name,
  3104. const char* a_type_param,
  3105. const char* a_value_param,
  3106. internal::TypeId fixture_class_id,
  3107. internal::TestFactoryBase* factory)
  3108. : test_case_name_(a_test_case_name),
  3109. name_(a_name),
  3110. type_param_(a_type_param ? new std::string(a_type_param) : NULL),
  3111. value_param_(a_value_param ? new std::string(a_value_param) : NULL),
  3112. fixture_class_id_(fixture_class_id),
  3113. should_run_(false),
  3114. is_disabled_(false),
  3115. matches_filter_(false),
  3116. factory_(factory),
  3117. result_() {}
  3118. // Destructs a TestInfo object.
  3119. TestInfo::~TestInfo() { delete factory_; }
  3120. namespace internal {
  3121. // Creates a new TestInfo object and registers it with Google Test;
  3122. // returns the created object.
  3123. //
  3124. // Arguments:
  3125. //
  3126. // test_case_name: name of the test case
  3127. // name: name of the test
  3128. // type_param: the name of the test's type parameter, or NULL if
  3129. // this is not a typed or a type-parameterized test.
  3130. // value_param: text representation of the test's value parameter,
  3131. // or NULL if this is not a value-parameterized test.
  3132. // fixture_class_id: ID of the test fixture class
  3133. // set_up_tc: pointer to the function that sets up the test case
  3134. // tear_down_tc: pointer to the function that tears down the test case
  3135. // factory: pointer to the factory that creates a test object.
  3136. // The newly created TestInfo instance will assume
  3137. // ownership of the factory object.
  3138. TestInfo* MakeAndRegisterTestInfo(
  3139. const char* test_case_name,
  3140. const char* name,
  3141. const char* type_param,
  3142. const char* value_param,
  3143. TypeId fixture_class_id,
  3144. SetUpTestCaseFunc set_up_tc,
  3145. TearDownTestCaseFunc tear_down_tc,
  3146. TestFactoryBase* factory) {
  3147. TestInfo* const test_info =
  3148. new TestInfo(test_case_name, name, type_param, value_param,
  3149. fixture_class_id, factory);
  3150. GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
  3151. return test_info;
  3152. }
  3153. #if GTEST_HAS_PARAM_TEST
  3154. void ReportInvalidTestCaseType(const char* test_case_name,
  3155. const char* file, int line) {
  3156. Message errors;
  3157. errors
  3158. << "Attempted redefinition of test case " << test_case_name << ".\n"
  3159. << "All tests in the same test case must use the same test fixture\n"
  3160. << "class. However, in test case " << test_case_name << ", you tried\n"
  3161. << "to define a test using a fixture class different from the one\n"
  3162. << "used earlier. This can happen if the two fixture classes are\n"
  3163. << "from different namespaces and have the same name. You should\n"
  3164. << "probably rename one of the classes to put the tests into different\n"
  3165. << "test cases.";
  3166. fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
  3167. errors.GetString().c_str());
  3168. }
  3169. #endif // GTEST_HAS_PARAM_TEST
  3170. } // namespace internal
  3171. namespace {
  3172. // A predicate that checks the test name of a TestInfo against a known
  3173. // value.
  3174. //
  3175. // This is used for implementation of the TestCase class only. We put
  3176. // it in the anonymous namespace to prevent polluting the outer
  3177. // namespace.
  3178. //
  3179. // TestNameIs is copyable.
  3180. class TestNameIs {
  3181. public:
  3182. // Constructor.
  3183. //
  3184. // TestNameIs has NO default constructor.
  3185. explicit TestNameIs(const char* name)
  3186. : name_(name) {}
  3187. // Returns true iff the test name of test_info matches name_.
  3188. bool operator()(const TestInfo * test_info) const {
  3189. return test_info && test_info->name() == name_;
  3190. }
  3191. private:
  3192. std::string name_;
  3193. };
  3194. } // namespace
  3195. namespace internal {
  3196. // This method expands all parameterized tests registered with macros TEST_P
  3197. // and INSTANTIATE_TEST_CASE_P into regular tests and registers those.
  3198. // This will be done just once during the program runtime.
  3199. void UnitTestImpl::RegisterParameterizedTests() {
  3200. #if GTEST_HAS_PARAM_TEST
  3201. if (!parameterized_tests_registered_) {
  3202. parameterized_test_registry_.RegisterTests();
  3203. parameterized_tests_registered_ = true;
  3204. }
  3205. #endif
  3206. }
  3207. } // namespace internal
  3208. // Creates the test object, runs it, records its result, and then
  3209. // deletes it.
  3210. void TestInfo::Run() {
  3211. if (!should_run_) return;
  3212. // Tells UnitTest where to store test result.
  3213. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  3214. impl->set_current_test_info(this);
  3215. TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
  3216. // Notifies the unit test event listeners that a test is about to start.
  3217. repeater->OnTestStart(*this);
  3218. const TimeInMillis start = internal::GetTimeInMillis();
  3219. impl->os_stack_trace_getter()->UponLeavingGTest();
  3220. // Creates the test object.
  3221. Test* const test = internal::HandleExceptionsInMethodIfSupported(
  3222. factory_, &internal::TestFactoryBase::CreateTest,
  3223. "the test fixture's constructor");
  3224. // Runs the test only if the test object was created and its
  3225. // constructor didn't generate a fatal failure.
  3226. if ((test != NULL) && !Test::HasFatalFailure()) {
  3227. // This doesn't throw as all user code that can throw are wrapped into
  3228. // exception handling code.
  3229. test->Run();
  3230. }
  3231. // Deletes the test object.
  3232. impl->os_stack_trace_getter()->UponLeavingGTest();
  3233. internal::HandleExceptionsInMethodIfSupported(
  3234. test, &Test::DeleteSelf_, "the test fixture's destructor");
  3235. result_.set_elapsed_time(internal::GetTimeInMillis() - start);
  3236. // Notifies the unit test event listener that a test has just finished.
  3237. repeater->OnTestEnd(*this);
  3238. // Tells UnitTest to stop associating assertion results to this
  3239. // test.
  3240. impl->set_current_test_info(NULL);
  3241. }
  3242. // class TestCase
  3243. // Gets the number of successful tests in this test case.
  3244. int TestCase::successful_test_count() const {
  3245. return CountIf(test_info_list_, TestPassed);
  3246. }
  3247. // Gets the number of failed tests in this test case.
  3248. int TestCase::failed_test_count() const {
  3249. return CountIf(test_info_list_, TestFailed);
  3250. }
  3251. // Gets the number of disabled tests that will be reported in the XML report.
  3252. int TestCase::reportable_disabled_test_count() const {
  3253. return CountIf(test_info_list_, TestReportableDisabled);
  3254. }
  3255. // Gets the number of disabled tests in this test case.
  3256. int TestCase::disabled_test_count() const {
  3257. return CountIf(test_info_list_, TestDisabled);
  3258. }
  3259. // Gets the number of tests to be printed in the XML report.
  3260. int TestCase::reportable_test_count() const {
  3261. return CountIf(test_info_list_, TestReportable);
  3262. }
  3263. // Get the number of tests in this test case that should run.
  3264. int TestCase::test_to_run_count() const {
  3265. return CountIf(test_info_list_, ShouldRunTest);
  3266. }
  3267. // Gets the number of all tests.
  3268. int TestCase::total_test_count() const {
  3269. return static_cast<int>(test_info_list_.size());
  3270. }
  3271. // Creates a TestCase with the given name.
  3272. //
  3273. // Arguments:
  3274. //
  3275. // name: name of the test case
  3276. // a_type_param: the name of the test case's type parameter, or NULL if
  3277. // this is not a typed or a type-parameterized test case.
  3278. // set_up_tc: pointer to the function that sets up the test case
  3279. // tear_down_tc: pointer to the function that tears down the test case
  3280. TestCase::TestCase(const char* a_name, const char* a_type_param,
  3281. Test::SetUpTestCaseFunc set_up_tc,
  3282. Test::TearDownTestCaseFunc tear_down_tc)
  3283. : name_(a_name),
  3284. type_param_(a_type_param ? new std::string(a_type_param) : NULL),
  3285. set_up_tc_(set_up_tc),
  3286. tear_down_tc_(tear_down_tc),
  3287. should_run_(false),
  3288. elapsed_time_(0) {
  3289. }
  3290. // Destructor of TestCase.
  3291. TestCase::~TestCase() {
  3292. // Deletes every Test in the collection.
  3293. ForEach(test_info_list_, internal::Delete<TestInfo>);
  3294. }
  3295. // Returns the i-th test among all the tests. i can range from 0 to
  3296. // total_test_count() - 1. If i is not in that range, returns NULL.
  3297. const TestInfo* TestCase::GetTestInfo(int i) const {
  3298. const int index = GetElementOr(test_indices_, i, -1);
  3299. return index < 0 ? NULL : test_info_list_[index];
  3300. }
  3301. // Returns the i-th test among all the tests. i can range from 0 to
  3302. // total_test_count() - 1. If i is not in that range, returns NULL.
  3303. TestInfo* TestCase::GetMutableTestInfo(int i) {
  3304. const int index = GetElementOr(test_indices_, i, -1);
  3305. return index < 0 ? NULL : test_info_list_[index];
  3306. }
  3307. // Adds a test to this test case. Will delete the test upon
  3308. // destruction of the TestCase object.
  3309. void TestCase::AddTestInfo(TestInfo * test_info) {
  3310. test_info_list_.push_back(test_info);
  3311. test_indices_.push_back(static_cast<int>(test_indices_.size()));
  3312. }
  3313. // Runs every test in this TestCase.
  3314. void TestCase::Run() {
  3315. if (!should_run_) return;
  3316. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  3317. impl->set_current_test_case(this);
  3318. TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
  3319. repeater->OnTestCaseStart(*this);
  3320. impl->os_stack_trace_getter()->UponLeavingGTest();
  3321. internal::HandleExceptionsInMethodIfSupported(
  3322. this, &TestCase::RunSetUpTestCase, "SetUpTestCase()");
  3323. const internal::TimeInMillis start = internal::GetTimeInMillis();
  3324. for (int i = 0; i < total_test_count(); i++) {
  3325. GetMutableTestInfo(i)->Run();
  3326. }
  3327. elapsed_time_ = internal::GetTimeInMillis() - start;
  3328. impl->os_stack_trace_getter()->UponLeavingGTest();
  3329. internal::HandleExceptionsInMethodIfSupported(
  3330. this, &TestCase::RunTearDownTestCase, "TearDownTestCase()");
  3331. repeater->OnTestCaseEnd(*this);
  3332. impl->set_current_test_case(NULL);
  3333. }
  3334. // Clears the results of all tests in this test case.
  3335. void TestCase::ClearResult() {
  3336. ad_hoc_test_result_.Clear();
  3337. ForEach(test_info_list_, TestInfo::ClearTestResult);
  3338. }
  3339. // Shuffles the tests in this test case.
  3340. void TestCase::ShuffleTests(internal::Random* random) {
  3341. Shuffle(random, &test_indices_);
  3342. }
  3343. // Restores the test order to before the first shuffle.
  3344. void TestCase::UnshuffleTests() {
  3345. for (size_t i = 0; i < test_indices_.size(); i++) {
  3346. test_indices_[i] = static_cast<int>(i);
  3347. }
  3348. }
  3349. // Formats a countable noun. Depending on its quantity, either the
  3350. // singular form or the plural form is used. e.g.
  3351. //
  3352. // FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
  3353. // FormatCountableNoun(5, "book", "books") returns "5 books".
  3354. static std::string FormatCountableNoun(int count,
  3355. const char * singular_form,
  3356. const char * plural_form) {
  3357. return internal::StreamableToString(count) + " " +
  3358. (count == 1 ? singular_form : plural_form);
  3359. }
  3360. // Formats the count of tests.
  3361. static std::string FormatTestCount(int test_count) {
  3362. return FormatCountableNoun(test_count, "test", "tests");
  3363. }
  3364. // Formats the count of test cases.
  3365. static std::string FormatTestCaseCount(int test_case_count) {
  3366. return FormatCountableNoun(test_case_count, "test case", "test cases");
  3367. }
  3368. // Converts a TestPartResult::Type enum to human-friendly string
  3369. // representation. Both kNonFatalFailure and kFatalFailure are translated
  3370. // to "Failure", as the user usually doesn't care about the difference
  3371. // between the two when viewing the test result.
  3372. static const char * TestPartResultTypeToString(TestPartResult::Type type) {
  3373. switch (type) {
  3374. case TestPartResult::kSuccess:
  3375. return "Success";
  3376. case TestPartResult::kNonFatalFailure:
  3377. case TestPartResult::kFatalFailure:
  3378. #ifdef _MSC_VER
  3379. return "error: ";
  3380. #else
  3381. return "Failure\n";
  3382. #endif
  3383. default:
  3384. return "Unknown result type";
  3385. }
  3386. }
  3387. namespace internal {
  3388. // Prints a TestPartResult to an std::string.
  3389. static std::string PrintTestPartResultToString(
  3390. const TestPartResult& test_part_result) {
  3391. return (Message()
  3392. << internal::FormatFileLocation(test_part_result.file_name(),
  3393. test_part_result.line_number())
  3394. << " " << TestPartResultTypeToString(test_part_result.type())
  3395. << test_part_result.message()).GetString();
  3396. }
  3397. // Prints a TestPartResult.
  3398. static void PrintTestPartResult(const TestPartResult& test_part_result) {
  3399. const std::string& result =
  3400. PrintTestPartResultToString(test_part_result);
  3401. printf("%s\n", result.c_str());
  3402. fflush(stdout);
  3403. // If the test program runs in Visual Studio or a debugger, the
  3404. // following statements add the test part result message to the Output
  3405. // window such that the user can double-click on it to jump to the
  3406. // corresponding source code location; otherwise they do nothing.
  3407. #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
  3408. // We don't call OutputDebugString*() on Windows Mobile, as printing
  3409. // to stdout is done by OutputDebugString() there already - we don't
  3410. // want the same message printed twice.
  3411. ::OutputDebugStringA(result.c_str());
  3412. ::OutputDebugStringA("\n");
  3413. #endif
  3414. }
  3415. // class PrettyUnitTestResultPrinter
  3416. enum GTestColor {
  3417. COLOR_DEFAULT,
  3418. COLOR_RED,
  3419. COLOR_GREEN,
  3420. COLOR_YELLOW
  3421. };
  3422. #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
  3423. // Returns the character attribute for the given color.
  3424. WORD GetColorAttribute(GTestColor color) {
  3425. switch (color) {
  3426. case COLOR_RED: return FOREGROUND_RED;
  3427. case COLOR_GREEN: return FOREGROUND_GREEN;
  3428. case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
  3429. default: return 0;
  3430. }
  3431. }
  3432. #else
  3433. // Returns the ANSI color code for the given color. COLOR_DEFAULT is
  3434. // an invalid input.
  3435. const char* GetAnsiColorCode(GTestColor color) {
  3436. switch (color) {
  3437. case COLOR_RED: return "1";
  3438. case COLOR_GREEN: return "2";
  3439. case COLOR_YELLOW: return "3";
  3440. default: return NULL;
  3441. };
  3442. }
  3443. #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
  3444. // Returns true iff Google Test should use colors in the output.
  3445. bool ShouldUseColor(bool stdout_is_tty) {
  3446. const char* const gtest_color = GTEST_FLAG(color).c_str();
  3447. if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
  3448. #if GTEST_OS_WINDOWS
  3449. // On Windows the TERM variable is usually not set, but the
  3450. // console there does support colors.
  3451. return stdout_is_tty;
  3452. #else
  3453. // On non-Windows platforms, we rely on the TERM variable.
  3454. const char* const term = posix::GetEnv("TERM");
  3455. const bool term_supports_color =
  3456. String::CStringEquals(term, "xterm") ||
  3457. String::CStringEquals(term, "xterm-color") ||
  3458. String::CStringEquals(term, "xterm-256color") ||
  3459. String::CStringEquals(term, "screen") ||
  3460. String::CStringEquals(term, "screen-256color") ||
  3461. String::CStringEquals(term, "linux") ||
  3462. String::CStringEquals(term, "cygwin");
  3463. return stdout_is_tty && term_supports_color;
  3464. #endif // GTEST_OS_WINDOWS
  3465. }
  3466. return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
  3467. String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
  3468. String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
  3469. String::CStringEquals(gtest_color, "1");
  3470. // We take "yes", "true", "t", and "1" as meaning "yes". If the
  3471. // value is neither one of these nor "auto", we treat it as "no" to
  3472. // be conservative.
  3473. }
  3474. // Helpers for printing colored strings to stdout. Note that on Windows, we
  3475. // cannot simply emit special characters and have the terminal change colors.
  3476. // This routine must actually emit the characters rather than return a string
  3477. // that would be colored when printed, as can be done on Linux.
  3478. void ColoredPrintf(GTestColor color, const char* fmt, ...) {
  3479. va_list args;
  3480. va_start(args, fmt);
  3481. #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS || GTEST_OS_IOS
  3482. const bool use_color = false;
  3483. #else
  3484. static const bool in_color_mode =
  3485. ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
  3486. const bool use_color = in_color_mode && (color != COLOR_DEFAULT);
  3487. #endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
  3488. // The '!= 0' comparison is necessary to satisfy MSVC 7.1.
  3489. if (!use_color) {
  3490. vprintf(fmt, args);
  3491. va_end(args);
  3492. return;
  3493. }
  3494. #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
  3495. const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
  3496. // Gets the current text color.
  3497. CONSOLE_SCREEN_BUFFER_INFO buffer_info;
  3498. GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
  3499. const WORD old_color_attrs = buffer_info.wAttributes;
  3500. // We need to flush the stream buffers into the console before each
  3501. // SetConsoleTextAttribute call lest it affect the text that is already
  3502. // printed but has not yet reached the console.
  3503. fflush(stdout);
  3504. SetConsoleTextAttribute(stdout_handle,
  3505. GetColorAttribute(color) | FOREGROUND_INTENSITY);
  3506. vprintf(fmt, args);
  3507. fflush(stdout);
  3508. // Restores the text color.
  3509. SetConsoleTextAttribute(stdout_handle, old_color_attrs);
  3510. #else
  3511. printf("\033[0;3%sm", GetAnsiColorCode(color));
  3512. vprintf(fmt, args);
  3513. printf("\033[m"); // Resets the terminal to default.
  3514. #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
  3515. va_end(args);
  3516. }
  3517. // Text printed in Google Test's text output and --gunit_list_tests
  3518. // output to label the type parameter and value parameter for a test.
  3519. static const char kTypeParamLabel[] = "TypeParam";
  3520. static const char kValueParamLabel[] = "GetParam()";
  3521. void PrintFullTestCommentIfPresent(const TestInfo& test_info) {
  3522. const char* const type_param = test_info.type_param();
  3523. const char* const value_param = test_info.value_param();
  3524. if (type_param != NULL || value_param != NULL) {
  3525. printf(", where ");
  3526. if (type_param != NULL) {
  3527. printf("%s = %s", kTypeParamLabel, type_param);
  3528. if (value_param != NULL)
  3529. printf(" and ");
  3530. }
  3531. if (value_param != NULL) {
  3532. printf("%s = %s", kValueParamLabel, value_param);
  3533. }
  3534. }
  3535. }
  3536. // This class implements the TestEventListener interface.
  3537. //
  3538. // Class PrettyUnitTestResultPrinter is copyable.
  3539. class PrettyUnitTestResultPrinter : public TestEventListener {
  3540. public:
  3541. PrettyUnitTestResultPrinter() {}
  3542. static void PrintTestName(const char * test_case, const char * test) {
  3543. printf("%s.%s", test_case, test);
  3544. }
  3545. // The following methods override what's in the TestEventListener class.
  3546. virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {}
  3547. virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
  3548. virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
  3549. virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {}
  3550. virtual void OnTestCaseStart(const TestCase& test_case);
  3551. virtual void OnTestStart(const TestInfo& test_info);
  3552. virtual void OnTestPartResult(const TestPartResult& result);
  3553. virtual void OnTestEnd(const TestInfo& test_info);
  3554. virtual void OnTestCaseEnd(const TestCase& test_case);
  3555. virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
  3556. virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {}
  3557. virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
  3558. virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {}
  3559. private:
  3560. static void PrintFailedTests(const UnitTest& unit_test);
  3561. };
  3562. // Fired before each iteration of tests starts.
  3563. void PrettyUnitTestResultPrinter::OnTestIterationStart(
  3564. const UnitTest& unit_test, int iteration) {
  3565. if (GTEST_FLAG(repeat) != 1)
  3566. printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
  3567. const char* const filter = GTEST_FLAG(filter).c_str();
  3568. // Prints the filter if it's not *. This reminds the user that some
  3569. // tests may be skipped.
  3570. if (!String::CStringEquals(filter, kUniversalFilter)) {
  3571. ColoredPrintf(COLOR_YELLOW,
  3572. "Note: %s filter = %s\n", GTEST_NAME_, filter);
  3573. }
  3574. if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
  3575. const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
  3576. ColoredPrintf(COLOR_YELLOW,
  3577. "Note: This is test shard %d of %s.\n",
  3578. static_cast<int>(shard_index) + 1,
  3579. internal::posix::GetEnv(kTestTotalShards));
  3580. }
  3581. if (GTEST_FLAG(shuffle)) {
  3582. ColoredPrintf(COLOR_YELLOW,
  3583. "Note: Randomizing tests' orders with a seed of %d .\n",
  3584. unit_test.random_seed());
  3585. }
  3586. ColoredPrintf(COLOR_GREEN, "[==========] ");
  3587. printf("Running %s from %s.\n",
  3588. FormatTestCount(unit_test.test_to_run_count()).c_str(),
  3589. FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
  3590. fflush(stdout);
  3591. }
  3592. void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
  3593. const UnitTest& /*unit_test*/) {
  3594. ColoredPrintf(COLOR_GREEN, "[----------] ");
  3595. printf("Global test environment set-up.\n");
  3596. fflush(stdout);
  3597. }
  3598. void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {
  3599. const std::string counts =
  3600. FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
  3601. ColoredPrintf(COLOR_GREEN, "[----------] ");
  3602. printf("%s from %s", counts.c_str(), test_case.name());
  3603. if (test_case.type_param() == NULL) {
  3604. printf("\n");
  3605. } else {
  3606. printf(", where %s = %s\n", kTypeParamLabel, test_case.type_param());
  3607. }
  3608. fflush(stdout);
  3609. }
  3610. void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
  3611. ColoredPrintf(COLOR_GREEN, "[ RUN ] ");
  3612. PrintTestName(test_info.test_case_name(), test_info.name());
  3613. printf("\n");
  3614. fflush(stdout);
  3615. }
  3616. // Called after an assertion failure.
  3617. void PrettyUnitTestResultPrinter::OnTestPartResult(
  3618. const TestPartResult& result) {
  3619. // If the test part succeeded, we don't need to do anything.
  3620. if (result.type() == TestPartResult::kSuccess)
  3621. return;
  3622. // Print failure message from the assertion (e.g. expected this and got that).
  3623. PrintTestPartResult(result);
  3624. fflush(stdout);
  3625. }
  3626. void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
  3627. if (test_info.result()->Passed()) {
  3628. ColoredPrintf(COLOR_GREEN, "[ OK ] ");
  3629. } else {
  3630. ColoredPrintf(COLOR_RED, "[ FAILED ] ");
  3631. }
  3632. PrintTestName(test_info.test_case_name(), test_info.name());
  3633. if (test_info.result()->Failed())
  3634. PrintFullTestCommentIfPresent(test_info);
  3635. if (GTEST_FLAG(print_time)) {
  3636. printf(" (%s ms)\n", internal::StreamableToString(
  3637. test_info.result()->elapsed_time()).c_str());
  3638. } else {
  3639. printf("\n");
  3640. }
  3641. fflush(stdout);
  3642. }
  3643. void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {
  3644. if (!GTEST_FLAG(print_time)) return;
  3645. const std::string counts =
  3646. FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
  3647. ColoredPrintf(COLOR_GREEN, "[----------] ");
  3648. printf("%s from %s (%s ms total)\n\n",
  3649. counts.c_str(), test_case.name(),
  3650. internal::StreamableToString(test_case.elapsed_time()).c_str());
  3651. fflush(stdout);
  3652. }
  3653. void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
  3654. const UnitTest& /*unit_test*/) {
  3655. ColoredPrintf(COLOR_GREEN, "[----------] ");
  3656. printf("Global test environment tear-down\n");
  3657. fflush(stdout);
  3658. }
  3659. // Internal helper for printing the list of failed tests.
  3660. void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
  3661. const int failed_test_count = unit_test.failed_test_count();
  3662. if (failed_test_count == 0) {
  3663. return;
  3664. }
  3665. for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
  3666. const TestCase& test_case = *unit_test.GetTestCase(i);
  3667. if (!test_case.should_run() || (test_case.failed_test_count() == 0)) {
  3668. continue;
  3669. }
  3670. for (int j = 0; j < test_case.total_test_count(); ++j) {
  3671. const TestInfo& test_info = *test_case.GetTestInfo(j);
  3672. if (!test_info.should_run() || test_info.result()->Passed()) {
  3673. continue;
  3674. }
  3675. ColoredPrintf(COLOR_RED, "[ FAILED ] ");
  3676. printf("%s.%s", test_case.name(), test_info.name());
  3677. PrintFullTestCommentIfPresent(test_info);
  3678. printf("\n");
  3679. }
  3680. }
  3681. }
  3682. void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
  3683. int /*iteration*/) {
  3684. ColoredPrintf(COLOR_GREEN, "[==========] ");
  3685. printf("%s from %s ran.",
  3686. FormatTestCount(unit_test.test_to_run_count()).c_str(),
  3687. FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
  3688. if (GTEST_FLAG(print_time)) {
  3689. printf(" (%s ms total)",
  3690. internal::StreamableToString(unit_test.elapsed_time()).c_str());
  3691. }
  3692. printf("\n");
  3693. ColoredPrintf(COLOR_GREEN, "[ PASSED ] ");
  3694. printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
  3695. int num_failures = unit_test.failed_test_count();
  3696. if (!unit_test.Passed()) {
  3697. const int failed_test_count = unit_test.failed_test_count();
  3698. ColoredPrintf(COLOR_RED, "[ FAILED ] ");
  3699. printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
  3700. PrintFailedTests(unit_test);
  3701. printf("\n%2d FAILED %s\n", num_failures,
  3702. num_failures == 1 ? "TEST" : "TESTS");
  3703. }
  3704. int num_disabled = unit_test.reportable_disabled_test_count();
  3705. if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
  3706. if (!num_failures) {
  3707. printf("\n"); // Add a spacer if no FAILURE banner is displayed.
  3708. }
  3709. ColoredPrintf(COLOR_YELLOW,
  3710. " YOU HAVE %d DISABLED %s\n\n",
  3711. num_disabled,
  3712. num_disabled == 1 ? "TEST" : "TESTS");
  3713. }
  3714. // Ensure that Google Test output is printed before, e.g., heapchecker output.
  3715. fflush(stdout);
  3716. }
  3717. // End PrettyUnitTestResultPrinter
  3718. // class TestEventRepeater
  3719. //
  3720. // This class forwards events to other event listeners.
  3721. class TestEventRepeater : public TestEventListener {
  3722. public:
  3723. TestEventRepeater() : forwarding_enabled_(true) {}
  3724. virtual ~TestEventRepeater();
  3725. void Append(TestEventListener *listener);
  3726. TestEventListener* Release(TestEventListener* listener);
  3727. // Controls whether events will be forwarded to listeners_. Set to false
  3728. // in death test child processes.
  3729. bool forwarding_enabled() const { return forwarding_enabled_; }
  3730. void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }
  3731. virtual void OnTestProgramStart(const UnitTest& unit_test);
  3732. virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
  3733. virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
  3734. virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test);
  3735. virtual void OnTestCaseStart(const TestCase& test_case);
  3736. virtual void OnTestStart(const TestInfo& test_info);
  3737. virtual void OnTestPartResult(const TestPartResult& result);
  3738. virtual void OnTestEnd(const TestInfo& test_info);
  3739. virtual void OnTestCaseEnd(const TestCase& test_case);
  3740. virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
  3741. virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test);
  3742. virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
  3743. virtual void OnTestProgramEnd(const UnitTest& unit_test);
  3744. private:
  3745. // Controls whether events will be forwarded to listeners_. Set to false
  3746. // in death test child processes.
  3747. bool forwarding_enabled_;
  3748. // The list of listeners that receive events.
  3749. std::vector<TestEventListener*> listeners_;
  3750. GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater);
  3751. };
  3752. TestEventRepeater::~TestEventRepeater() {
  3753. ForEach(listeners_, Delete<TestEventListener>);
  3754. }
  3755. void TestEventRepeater::Append(TestEventListener *listener) {
  3756. listeners_.push_back(listener);
  3757. }
  3758. // TODO(vladl@google.com): Factor the search functionality into Vector::Find.
  3759. TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {
  3760. for (size_t i = 0; i < listeners_.size(); ++i) {
  3761. if (listeners_[i] == listener) {
  3762. listeners_.erase(listeners_.begin() + i);
  3763. return listener;
  3764. }
  3765. }
  3766. return NULL;
  3767. }
  3768. // Since most methods are very similar, use macros to reduce boilerplate.
  3769. // This defines a member that forwards the call to all listeners.
  3770. #define GTEST_REPEATER_METHOD_(Name, Type) \
  3771. void TestEventRepeater::Name(const Type& parameter) { \
  3772. if (forwarding_enabled_) { \
  3773. for (size_t i = 0; i < listeners_.size(); i++) { \
  3774. listeners_[i]->Name(parameter); \
  3775. } \
  3776. } \
  3777. }
  3778. // This defines a member that forwards the call to all listeners in reverse
  3779. // order.
  3780. #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
  3781. void TestEventRepeater::Name(const Type& parameter) { \
  3782. if (forwarding_enabled_) { \
  3783. for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \
  3784. listeners_[i]->Name(parameter); \
  3785. } \
  3786. } \
  3787. }
  3788. GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)
  3789. GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)
  3790. GTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase)
  3791. GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
  3792. GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)
  3793. GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)
  3794. GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)
  3795. GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)
  3796. GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)
  3797. GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestCase)
  3798. GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)
  3799. #undef GTEST_REPEATER_METHOD_
  3800. #undef GTEST_REVERSE_REPEATER_METHOD_
  3801. void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,
  3802. int iteration) {
  3803. if (forwarding_enabled_) {
  3804. for (size_t i = 0; i < listeners_.size(); i++) {
  3805. listeners_[i]->OnTestIterationStart(unit_test, iteration);
  3806. }
  3807. }
  3808. }
  3809. void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,
  3810. int iteration) {
  3811. if (forwarding_enabled_) {
  3812. for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) {
  3813. listeners_[i]->OnTestIterationEnd(unit_test, iteration);
  3814. }
  3815. }
  3816. }
  3817. // End TestEventRepeater
  3818. // This class generates an XML output file.
  3819. class XmlUnitTestResultPrinter : public EmptyTestEventListener {
  3820. public:
  3821. explicit XmlUnitTestResultPrinter(const char* output_file);
  3822. virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
  3823. private:
  3824. // Is c a whitespace character that is normalized to a space character
  3825. // when it appears in an XML attribute value?
  3826. static bool IsNormalizableWhitespace(char c) {
  3827. return c == 0x9 || c == 0xA || c == 0xD;
  3828. }
  3829. // May c appear in a well-formed XML document?
  3830. static bool IsValidXmlCharacter(char c) {
  3831. return IsNormalizableWhitespace(c) || c >= 0x20;
  3832. }
  3833. // Returns an XML-escaped copy of the input string str. If
  3834. // is_attribute is true, the text is meant to appear as an attribute
  3835. // value, and normalizable whitespace is preserved by replacing it
  3836. // with character references.
  3837. static std::string EscapeXml(const std::string& str, bool is_attribute);
  3838. // Returns the given string with all characters invalid in XML removed.
  3839. static std::string RemoveInvalidXmlCharacters(const std::string& str);
  3840. // Convenience wrapper around EscapeXml when str is an attribute value.
  3841. static std::string EscapeXmlAttribute(const std::string& str) {
  3842. return EscapeXml(str, true);
  3843. }
  3844. // Convenience wrapper around EscapeXml when str is not an attribute value.
  3845. static std::string EscapeXmlText(const char* str) {
  3846. return EscapeXml(str, false);
  3847. }
  3848. // Verifies that the given attribute belongs to the given element and
  3849. // streams the attribute as XML.
  3850. static void OutputXmlAttribute(std::ostream* stream,
  3851. const std::string& element_name,
  3852. const std::string& name,
  3853. const std::string& value);
  3854. // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
  3855. static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
  3856. // Streams an XML representation of a TestInfo object.
  3857. static void OutputXmlTestInfo(::std::ostream* stream,
  3858. const char* test_case_name,
  3859. const TestInfo& test_info);
  3860. // Prints an XML representation of a TestCase object
  3861. static void PrintXmlTestCase(::std::ostream* stream,
  3862. const TestCase& test_case);
  3863. // Prints an XML summary of unit_test to output stream out.
  3864. static void PrintXmlUnitTest(::std::ostream* stream,
  3865. const UnitTest& unit_test);
  3866. // Produces a string representing the test properties in a result as space
  3867. // delimited XML attributes based on the property key="value" pairs.
  3868. // When the std::string is not empty, it includes a space at the beginning,
  3869. // to delimit this attribute from prior attributes.
  3870. static std::string TestPropertiesAsXmlAttributes(const TestResult& result);
  3871. // The output file.
  3872. const std::string output_file_;
  3873. GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);
  3874. };
  3875. // Creates a new XmlUnitTestResultPrinter.
  3876. XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
  3877. : output_file_(output_file) {
  3878. if (output_file_.c_str() == NULL || output_file_.empty()) {
  3879. fprintf(stderr, "XML output file may not be null\n");
  3880. fflush(stderr);
  3881. exit(EXIT_FAILURE);
  3882. }
  3883. }
  3884. // Called after the unit test ends.
  3885. void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
  3886. int /*iteration*/) {
  3887. FILE* xmlout = NULL;
  3888. FilePath output_file(output_file_);
  3889. FilePath output_dir(output_file.RemoveFileName());
  3890. if (output_dir.CreateDirectoriesRecursively()) {
  3891. xmlout = posix::FOpen(output_file_.c_str(), "w");
  3892. }
  3893. if (xmlout == NULL) {
  3894. // TODO(wan): report the reason of the failure.
  3895. //
  3896. // We don't do it for now as:
  3897. //
  3898. // 1. There is no urgent need for it.
  3899. // 2. It's a bit involved to make the errno variable thread-safe on
  3900. // all three operating systems (Linux, Windows, and Mac OS).
  3901. // 3. To interpret the meaning of errno in a thread-safe way,
  3902. // we need the strerror_r() function, which is not available on
  3903. // Windows.
  3904. fprintf(stderr,
  3905. "Unable to open file \"%s\"\n",
  3906. output_file_.c_str());
  3907. fflush(stderr);
  3908. exit(EXIT_FAILURE);
  3909. }
  3910. std::stringstream stream;
  3911. PrintXmlUnitTest(&stream, unit_test);
  3912. fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
  3913. fclose(xmlout);
  3914. }
  3915. // Returns an XML-escaped copy of the input string str. If is_attribute
  3916. // is true, the text is meant to appear as an attribute value, and
  3917. // normalizable whitespace is preserved by replacing it with character
  3918. // references.
  3919. //
  3920. // Invalid XML characters in str, if any, are stripped from the output.
  3921. // It is expected that most, if not all, of the text processed by this
  3922. // module will consist of ordinary English text.
  3923. // If this module is ever modified to produce version 1.1 XML output,
  3924. // most invalid characters can be retained using character references.
  3925. // TODO(wan): It might be nice to have a minimally invasive, human-readable
  3926. // escaping scheme for invalid characters, rather than dropping them.
  3927. std::string XmlUnitTestResultPrinter::EscapeXml(
  3928. const std::string& str, bool is_attribute) {
  3929. Message m;
  3930. for (size_t i = 0; i < str.size(); ++i) {
  3931. const char ch = str[i];
  3932. switch (ch) {
  3933. case '<':
  3934. m << "&lt;";
  3935. break;
  3936. case '>':
  3937. m << "&gt;";
  3938. break;
  3939. case '&':
  3940. m << "&amp;";
  3941. break;
  3942. case '\'':
  3943. if (is_attribute)
  3944. m << "&apos;";
  3945. else
  3946. m << '\'';
  3947. break;
  3948. case '"':
  3949. if (is_attribute)
  3950. m << "&quot;";
  3951. else
  3952. m << '"';
  3953. break;
  3954. default:
  3955. if (IsValidXmlCharacter(ch)) {
  3956. if (is_attribute && IsNormalizableWhitespace(ch))
  3957. m << "&#x" << String::FormatByte(static_cast<unsigned char>(ch))
  3958. << ";";
  3959. else
  3960. m << ch;
  3961. }
  3962. break;
  3963. }
  3964. }
  3965. return m.GetString();
  3966. }
  3967. // Returns the given string with all characters invalid in XML removed.
  3968. // Currently invalid characters are dropped from the string. An
  3969. // alternative is to replace them with certain characters such as . or ?.
  3970. std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(
  3971. const std::string& str) {
  3972. std::string output;
  3973. output.reserve(str.size());
  3974. for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
  3975. if (IsValidXmlCharacter(*it))
  3976. output.push_back(*it);
  3977. return output;
  3978. }
  3979. // The following routines generate an XML representation of a UnitTest
  3980. // object.
  3981. //
  3982. // This is how Google Test concepts map to the DTD:
  3983. //
  3984. // <testsuites name="AllTests"> <-- corresponds to a UnitTest object
  3985. // <testsuite name="testcase-name"> <-- corresponds to a TestCase object
  3986. // <testcase name="test-name"> <-- corresponds to a TestInfo object
  3987. // <failure message="...">...</failure>
  3988. // <failure message="...">...</failure>
  3989. // <failure message="...">...</failure>
  3990. // <-- individual assertion failures
  3991. // </testcase>
  3992. // </testsuite>
  3993. // </testsuites>
  3994. // Formats the given time in milliseconds as seconds.
  3995. std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {
  3996. ::std::stringstream ss;
  3997. ss << ms/1000.0;
  3998. return ss.str();
  3999. }
  4000. // Converts the given epoch time in milliseconds to a date string in the ISO
  4001. // 8601 format, without the timezone information.
  4002. std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) {
  4003. // Using non-reentrant version as localtime_r is not portable.
  4004. time_t seconds = static_cast<time_t>(ms / 1000);
  4005. #ifdef _MSC_VER
  4006. # pragma warning(push) // Saves the current warning state.
  4007. # pragma warning(disable:4996) // Temporarily disables warning 4996
  4008. // (function or variable may be unsafe).
  4009. const struct tm* const time_struct = localtime(&seconds); // NOLINT
  4010. # pragma warning(pop) // Restores the warning state again.
  4011. #else
  4012. const struct tm* const time_struct = localtime(&seconds); // NOLINT
  4013. #endif
  4014. if (time_struct == NULL)
  4015. return ""; // Invalid ms value
  4016. // YYYY-MM-DDThh:mm:ss
  4017. return StreamableToString(time_struct->tm_year + 1900) + "-" +
  4018. String::FormatIntWidth2(time_struct->tm_mon + 1) + "-" +
  4019. String::FormatIntWidth2(time_struct->tm_mday) + "T" +
  4020. String::FormatIntWidth2(time_struct->tm_hour) + ":" +
  4021. String::FormatIntWidth2(time_struct->tm_min) + ":" +
  4022. String::FormatIntWidth2(time_struct->tm_sec);
  4023. }
  4024. // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
  4025. void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
  4026. const char* data) {
  4027. const char* segment = data;
  4028. *stream << "<![CDATA[";
  4029. for (;;) {
  4030. const char* const next_segment = strstr(segment, "]]>");
  4031. if (next_segment != NULL) {
  4032. stream->write(
  4033. segment, static_cast<std::streamsize>(next_segment - segment));
  4034. *stream << "]]>]]&gt;<![CDATA[";
  4035. segment = next_segment + strlen("]]>");
  4036. } else {
  4037. *stream << segment;
  4038. break;
  4039. }
  4040. }
  4041. *stream << "]]>";
  4042. }
  4043. void XmlUnitTestResultPrinter::OutputXmlAttribute(
  4044. std::ostream* stream,
  4045. const std::string& element_name,
  4046. const std::string& name,
  4047. const std::string& value) {
  4048. const std::vector<std::string>& allowed_names =
  4049. GetReservedAttributesForElement(element_name);
  4050. GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
  4051. allowed_names.end())
  4052. << "Attribute " << name << " is not allowed for element <" << element_name
  4053. << ">.";
  4054. *stream << " " << name << "=\"" << EscapeXmlAttribute(value) << "\"";
  4055. }
  4056. // Prints an XML representation of a TestInfo object.
  4057. // TODO(wan): There is also value in printing properties with the plain printer.
  4058. void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
  4059. const char* test_case_name,
  4060. const TestInfo& test_info) {
  4061. const TestResult& result = *test_info.result();
  4062. const std::string kTestcase = "testcase";
  4063. *stream << " <testcase";
  4064. OutputXmlAttribute(stream, kTestcase, "name", test_info.name());
  4065. if (test_info.value_param() != NULL) {
  4066. OutputXmlAttribute(stream, kTestcase, "value_param",
  4067. test_info.value_param());
  4068. }
  4069. if (test_info.type_param() != NULL) {
  4070. OutputXmlAttribute(stream, kTestcase, "type_param", test_info.type_param());
  4071. }
  4072. OutputXmlAttribute(stream, kTestcase, "status",
  4073. test_info.should_run() ? "run" : "notrun");
  4074. OutputXmlAttribute(stream, kTestcase, "time",
  4075. FormatTimeInMillisAsSeconds(result.elapsed_time()));
  4076. OutputXmlAttribute(stream, kTestcase, "classname", test_case_name);
  4077. *stream << TestPropertiesAsXmlAttributes(result);
  4078. int failures = 0;
  4079. for (int i = 0; i < result.total_part_count(); ++i) {
  4080. const TestPartResult& part = result.GetTestPartResult(i);
  4081. if (part.failed()) {
  4082. if (++failures == 1) {
  4083. *stream << ">\n";
  4084. }
  4085. const string location = internal::FormatCompilerIndependentFileLocation(
  4086. part.file_name(), part.line_number());
  4087. const string summary = location + "\n" + part.summary();
  4088. *stream << " <failure message=\""
  4089. << EscapeXmlAttribute(summary.c_str())
  4090. << "\" type=\"\">";
  4091. const string detail = location + "\n" + part.message();
  4092. OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
  4093. *stream << "</failure>\n";
  4094. }
  4095. }
  4096. if (failures == 0)
  4097. *stream << " />\n";
  4098. else
  4099. *stream << " </testcase>\n";
  4100. }
  4101. // Prints an XML representation of a TestCase object
  4102. void XmlUnitTestResultPrinter::PrintXmlTestCase(std::ostream* stream,
  4103. const TestCase& test_case) {
  4104. const std::string kTestsuite = "testsuite";
  4105. *stream << " <" << kTestsuite;
  4106. OutputXmlAttribute(stream, kTestsuite, "name", test_case.name());
  4107. OutputXmlAttribute(stream, kTestsuite, "tests",
  4108. StreamableToString(test_case.reportable_test_count()));
  4109. OutputXmlAttribute(stream, kTestsuite, "failures",
  4110. StreamableToString(test_case.failed_test_count()));
  4111. OutputXmlAttribute(
  4112. stream, kTestsuite, "disabled",
  4113. StreamableToString(test_case.reportable_disabled_test_count()));
  4114. OutputXmlAttribute(stream, kTestsuite, "errors", "0");
  4115. OutputXmlAttribute(stream, kTestsuite, "time",
  4116. FormatTimeInMillisAsSeconds(test_case.elapsed_time()));
  4117. *stream << TestPropertiesAsXmlAttributes(test_case.ad_hoc_test_result())
  4118. << ">\n";
  4119. for (int i = 0; i < test_case.total_test_count(); ++i) {
  4120. if (test_case.GetTestInfo(i)->is_reportable())
  4121. OutputXmlTestInfo(stream, test_case.name(), *test_case.GetTestInfo(i));
  4122. }
  4123. *stream << " </" << kTestsuite << ">\n";
  4124. }
  4125. // Prints an XML summary of unit_test to output stream out.
  4126. void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream,
  4127. const UnitTest& unit_test) {
  4128. const std::string kTestsuites = "testsuites";
  4129. *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
  4130. *stream << "<" << kTestsuites;
  4131. OutputXmlAttribute(stream, kTestsuites, "tests",
  4132. StreamableToString(unit_test.reportable_test_count()));
  4133. OutputXmlAttribute(stream, kTestsuites, "failures",
  4134. StreamableToString(unit_test.failed_test_count()));
  4135. OutputXmlAttribute(
  4136. stream, kTestsuites, "disabled",
  4137. StreamableToString(unit_test.reportable_disabled_test_count()));
  4138. OutputXmlAttribute(stream, kTestsuites, "errors", "0");
  4139. OutputXmlAttribute(
  4140. stream, kTestsuites, "timestamp",
  4141. FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp()));
  4142. OutputXmlAttribute(stream, kTestsuites, "time",
  4143. FormatTimeInMillisAsSeconds(unit_test.elapsed_time()));
  4144. if (GTEST_FLAG(shuffle)) {
  4145. OutputXmlAttribute(stream, kTestsuites, "random_seed",
  4146. StreamableToString(unit_test.random_seed()));
  4147. }
  4148. *stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result());
  4149. OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
  4150. *stream << ">\n";
  4151. for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
  4152. if (unit_test.GetTestCase(i)->reportable_test_count() > 0)
  4153. PrintXmlTestCase(stream, *unit_test.GetTestCase(i));
  4154. }
  4155. *stream << "</" << kTestsuites << ">\n";
  4156. }
  4157. // Produces a string representing the test properties in a result as space
  4158. // delimited XML attributes based on the property key="value" pairs.
  4159. std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
  4160. const TestResult& result) {
  4161. Message attributes;
  4162. for (int i = 0; i < result.test_property_count(); ++i) {
  4163. const TestProperty& property = result.GetTestProperty(i);
  4164. attributes << " " << property.key() << "="
  4165. << "\"" << EscapeXmlAttribute(property.value()) << "\"";
  4166. }
  4167. return attributes.GetString();
  4168. }
  4169. // End XmlUnitTestResultPrinter
  4170. #if GTEST_CAN_STREAM_RESULTS_
  4171. // Checks if str contains '=', '&', '%' or '\n' characters. If yes,
  4172. // replaces them by "%xx" where xx is their hexadecimal value. For
  4173. // example, replaces "=" with "%3D". This algorithm is O(strlen(str))
  4174. // in both time and space -- important as the input str may contain an
  4175. // arbitrarily long test failure message and stack trace.
  4176. string StreamingListener::UrlEncode(const char* str) {
  4177. string result;
  4178. result.reserve(strlen(str) + 1);
  4179. for (char ch = *str; ch != '\0'; ch = *++str) {
  4180. switch (ch) {
  4181. case '%':
  4182. case '=':
  4183. case '&':
  4184. case '\n':
  4185. result.append("%" + String::FormatByte(static_cast<unsigned char>(ch)));
  4186. break;
  4187. default:
  4188. result.push_back(ch);
  4189. break;
  4190. }
  4191. }
  4192. return result;
  4193. }
  4194. void StreamingListener::SocketWriter::MakeConnection() {
  4195. GTEST_CHECK_(sockfd_ == -1)
  4196. << "MakeConnection() can't be called when there is already a connection.";
  4197. addrinfo hints;
  4198. memset(&hints, 0, sizeof(hints));
  4199. hints.ai_family = AF_UNSPEC; // To allow both IPv4 and IPv6 addresses.
  4200. hints.ai_socktype = SOCK_STREAM;
  4201. addrinfo* servinfo = NULL;
  4202. // Use the getaddrinfo() to get a linked list of IP addresses for
  4203. // the given host name.
  4204. const int error_num = getaddrinfo(
  4205. host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
  4206. if (error_num != 0) {
  4207. GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: "
  4208. << gai_strerror(error_num);
  4209. }
  4210. // Loop through all the results and connect to the first we can.
  4211. for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != NULL;
  4212. cur_addr = cur_addr->ai_next) {
  4213. sockfd_ = socket(
  4214. cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol);
  4215. if (sockfd_ != -1) {
  4216. // Connect the client socket to the server socket.
  4217. if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
  4218. close(sockfd_);
  4219. sockfd_ = -1;
  4220. }
  4221. }
  4222. }
  4223. freeaddrinfo(servinfo); // all done with this structure
  4224. if (sockfd_ == -1) {
  4225. GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to "
  4226. << host_name_ << ":" << port_num_;
  4227. }
  4228. }
  4229. // End of class Streaming Listener
  4230. #endif // GTEST_CAN_STREAM_RESULTS__
  4231. // Class ScopedTrace
  4232. // Pushes the given source file location and message onto a per-thread
  4233. // trace stack maintained by Google Test.
  4234. ScopedTrace::ScopedTrace(const char* file, int line, const Message& message)
  4235. GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
  4236. TraceInfo trace;
  4237. trace.file = file;
  4238. trace.line = line;
  4239. trace.message = message.GetString();
  4240. UnitTest::GetInstance()->PushGTestTrace(trace);
  4241. }
  4242. // Pops the info pushed by the c'tor.
  4243. ScopedTrace::~ScopedTrace()
  4244. GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
  4245. UnitTest::GetInstance()->PopGTestTrace();
  4246. }
  4247. // class OsStackTraceGetter
  4248. // Returns the current OS stack trace as an std::string. Parameters:
  4249. //
  4250. // max_depth - the maximum number of stack frames to be included
  4251. // in the trace.
  4252. // skip_count - the number of top frames to be skipped; doesn't count
  4253. // against max_depth.
  4254. //
  4255. string OsStackTraceGetter::CurrentStackTrace(int /* max_depth */,
  4256. int /* skip_count */)
  4257. GTEST_LOCK_EXCLUDED_(mutex_) {
  4258. return "";
  4259. }
  4260. void OsStackTraceGetter::UponLeavingGTest()
  4261. GTEST_LOCK_EXCLUDED_(mutex_) {
  4262. }
  4263. const char* const
  4264. OsStackTraceGetter::kElidedFramesMarker =
  4265. "... " GTEST_NAME_ " internal frames ...";
  4266. // A helper class that creates the premature-exit file in its
  4267. // constructor and deletes the file in its destructor.
  4268. class ScopedPrematureExitFile {
  4269. public:
  4270. explicit ScopedPrematureExitFile(const char* premature_exit_filepath)
  4271. : premature_exit_filepath_(premature_exit_filepath) {
  4272. // If a path to the premature-exit file is specified...
  4273. if (premature_exit_filepath != NULL && *premature_exit_filepath != '\0') {
  4274. // create the file with a single "0" character in it. I/O
  4275. // errors are ignored as there's nothing better we can do and we
  4276. // don't want to fail the test because of this.
  4277. FILE* pfile = posix::FOpen(premature_exit_filepath, "w");
  4278. fwrite("0", 1, 1, pfile);
  4279. fclose(pfile);
  4280. }
  4281. }
  4282. ~ScopedPrematureExitFile() {
  4283. if (premature_exit_filepath_ != NULL && *premature_exit_filepath_ != '\0') {
  4284. remove(premature_exit_filepath_);
  4285. }
  4286. }
  4287. private:
  4288. const char* const premature_exit_filepath_;
  4289. GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedPrematureExitFile);
  4290. };
  4291. } // namespace internal
  4292. // class TestEventListeners
  4293. TestEventListeners::TestEventListeners()
  4294. : repeater_(new internal::TestEventRepeater()),
  4295. default_result_printer_(NULL),
  4296. default_xml_generator_(NULL) {
  4297. }
  4298. TestEventListeners::~TestEventListeners() { delete repeater_; }
  4299. // Returns the standard listener responsible for the default console
  4300. // output. Can be removed from the listeners list to shut down default
  4301. // console output. Note that removing this object from the listener list
  4302. // with Release transfers its ownership to the user.
  4303. void TestEventListeners::Append(TestEventListener* listener) {
  4304. repeater_->Append(listener);
  4305. }
  4306. // Removes the given event listener from the list and returns it. It then
  4307. // becomes the caller's responsibility to delete the listener. Returns
  4308. // NULL if the listener is not found in the list.
  4309. TestEventListener* TestEventListeners::Release(TestEventListener* listener) {
  4310. if (listener == default_result_printer_)
  4311. default_result_printer_ = NULL;
  4312. else if (listener == default_xml_generator_)
  4313. default_xml_generator_ = NULL;
  4314. return repeater_->Release(listener);
  4315. }
  4316. // Returns repeater that broadcasts the TestEventListener events to all
  4317. // subscribers.
  4318. TestEventListener* TestEventListeners::repeater() { return repeater_; }
  4319. // Sets the default_result_printer attribute to the provided listener.
  4320. // The listener is also added to the listener list and previous
  4321. // default_result_printer is removed from it and deleted. The listener can
  4322. // also be NULL in which case it will not be added to the list. Does
  4323. // nothing if the previous and the current listener objects are the same.
  4324. void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
  4325. if (default_result_printer_ != listener) {
  4326. // It is an error to pass this method a listener that is already in the
  4327. // list.
  4328. delete Release(default_result_printer_);
  4329. default_result_printer_ = listener;
  4330. if (listener != NULL)
  4331. Append(listener);
  4332. }
  4333. }
  4334. // Sets the default_xml_generator attribute to the provided listener. The
  4335. // listener is also added to the listener list and previous
  4336. // default_xml_generator is removed from it and deleted. The listener can
  4337. // also be NULL in which case it will not be added to the list. Does
  4338. // nothing if the previous and the current listener objects are the same.
  4339. void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
  4340. if (default_xml_generator_ != listener) {
  4341. // It is an error to pass this method a listener that is already in the
  4342. // list.
  4343. delete Release(default_xml_generator_);
  4344. default_xml_generator_ = listener;
  4345. if (listener != NULL)
  4346. Append(listener);
  4347. }
  4348. }
  4349. // Controls whether events will be forwarded by the repeater to the
  4350. // listeners in the list.
  4351. bool TestEventListeners::EventForwardingEnabled() const {
  4352. return repeater_->forwarding_enabled();
  4353. }
  4354. void TestEventListeners::SuppressEventForwarding() {
  4355. repeater_->set_forwarding_enabled(false);
  4356. }
  4357. // class UnitTest
  4358. // Gets the singleton UnitTest object. The first time this method is
  4359. // called, a UnitTest object is constructed and returned. Consecutive
  4360. // calls will return the same object.
  4361. //
  4362. // We don't protect this under mutex_ as a user is not supposed to
  4363. // call this before main() starts, from which point on the return
  4364. // value will never change.
  4365. UnitTest* UnitTest::GetInstance() {
  4366. // When compiled with MSVC 7.1 in optimized mode, destroying the
  4367. // UnitTest object upon exiting the program messes up the exit code,
  4368. // causing successful tests to appear failed. We have to use a
  4369. // different implementation in this case to bypass the compiler bug.
  4370. // This implementation makes the compiler happy, at the cost of
  4371. // leaking the UnitTest object.
  4372. // CodeGear C++Builder insists on a public destructor for the
  4373. // default implementation. Use this implementation to keep good OO
  4374. // design with private destructor.
  4375. #if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
  4376. static UnitTest* const instance = new UnitTest;
  4377. return instance;
  4378. #else
  4379. static UnitTest instance;
  4380. return &instance;
  4381. #endif // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
  4382. }
  4383. // Gets the number of successful test cases.
  4384. int UnitTest::successful_test_case_count() const {
  4385. return impl()->successful_test_case_count();
  4386. }
  4387. // Gets the number of failed test cases.
  4388. int UnitTest::failed_test_case_count() const {
  4389. return impl()->failed_test_case_count();
  4390. }
  4391. // Gets the number of all test cases.
  4392. int UnitTest::total_test_case_count() const {
  4393. return impl()->total_test_case_count();
  4394. }
  4395. // Gets the number of all test cases that contain at least one test
  4396. // that should run.
  4397. int UnitTest::test_case_to_run_count() const {
  4398. return impl()->test_case_to_run_count();
  4399. }
  4400. // Gets the number of successful tests.
  4401. int UnitTest::successful_test_count() const {
  4402. return impl()->successful_test_count();
  4403. }
  4404. // Gets the number of failed tests.
  4405. int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
  4406. // Gets the number of disabled tests that will be reported in the XML report.
  4407. int UnitTest::reportable_disabled_test_count() const {
  4408. return impl()->reportable_disabled_test_count();
  4409. }
  4410. // Gets the number of disabled tests.
  4411. int UnitTest::disabled_test_count() const {
  4412. return impl()->disabled_test_count();
  4413. }
  4414. // Gets the number of tests to be printed in the XML report.
  4415. int UnitTest::reportable_test_count() const {
  4416. return impl()->reportable_test_count();
  4417. }
  4418. // Gets the number of all tests.
  4419. int UnitTest::total_test_count() const { return impl()->total_test_count(); }
  4420. // Gets the number of tests that should run.
  4421. int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
  4422. // Gets the time of the test program start, in ms from the start of the
  4423. // UNIX epoch.
  4424. internal::TimeInMillis UnitTest::start_timestamp() const {
  4425. return impl()->start_timestamp();
  4426. }
  4427. // Gets the elapsed time, in milliseconds.
  4428. internal::TimeInMillis UnitTest::elapsed_time() const {
  4429. return impl()->elapsed_time();
  4430. }
  4431. // Returns true iff the unit test passed (i.e. all test cases passed).
  4432. bool UnitTest::Passed() const { return impl()->Passed(); }
  4433. // Returns true iff the unit test failed (i.e. some test case failed
  4434. // or something outside of all tests failed).
  4435. bool UnitTest::Failed() const { return impl()->Failed(); }
  4436. // Gets the i-th test case among all the test cases. i can range from 0 to
  4437. // total_test_case_count() - 1. If i is not in that range, returns NULL.
  4438. const TestCase* UnitTest::GetTestCase(int i) const {
  4439. return impl()->GetTestCase(i);
  4440. }
  4441. // Returns the TestResult containing information on test failures and
  4442. // properties logged outside of individual test cases.
  4443. const TestResult& UnitTest::ad_hoc_test_result() const {
  4444. return *impl()->ad_hoc_test_result();
  4445. }
  4446. // Gets the i-th test case among all the test cases. i can range from 0 to
  4447. // total_test_case_count() - 1. If i is not in that range, returns NULL.
  4448. TestCase* UnitTest::GetMutableTestCase(int i) {
  4449. return impl()->GetMutableTestCase(i);
  4450. }
  4451. // Returns the list of event listeners that can be used to track events
  4452. // inside Google Test.
  4453. TestEventListeners& UnitTest::listeners() {
  4454. return *impl()->listeners();
  4455. }
  4456. // Registers and returns a global test environment. When a test
  4457. // program is run, all global test environments will be set-up in the
  4458. // order they were registered. After all tests in the program have
  4459. // finished, all global test environments will be torn-down in the
  4460. // *reverse* order they were registered.
  4461. //
  4462. // The UnitTest object takes ownership of the given environment.
  4463. //
  4464. // We don't protect this under mutex_, as we only support calling it
  4465. // from the main thread.
  4466. Environment* UnitTest::AddEnvironment(Environment* env) {
  4467. if (env == NULL) {
  4468. return NULL;
  4469. }
  4470. impl_->environments().push_back(env);
  4471. return env;
  4472. }
  4473. // Adds a TestPartResult to the current TestResult object. All Google Test
  4474. // assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
  4475. // this to report their results. The user code should use the
  4476. // assertion macros instead of calling this directly.
  4477. void UnitTest::AddTestPartResult(
  4478. TestPartResult::Type result_type,
  4479. const char* file_name,
  4480. int line_number,
  4481. const std::string& message,
  4482. const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_) {
  4483. Message msg;
  4484. msg << message;
  4485. internal::MutexLock lock(&mutex_);
  4486. if (impl_->gtest_trace_stack().size() > 0) {
  4487. msg << "\n" << GTEST_NAME_ << " trace:";
  4488. for (int i = static_cast<int>(impl_->gtest_trace_stack().size());
  4489. i > 0; --i) {
  4490. const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
  4491. msg << "\n" << internal::FormatFileLocation(trace.file, trace.line)
  4492. << " " << trace.message;
  4493. }
  4494. }
  4495. if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) {
  4496. msg << internal::kStackTraceMarker << os_stack_trace;
  4497. }
  4498. const TestPartResult result =
  4499. TestPartResult(result_type, file_name, line_number,
  4500. msg.GetString().c_str());
  4501. impl_->GetTestPartResultReporterForCurrentThread()->
  4502. ReportTestPartResult(result);
  4503. if (result_type != TestPartResult::kSuccess) {
  4504. // gtest_break_on_failure takes precedence over
  4505. // gtest_throw_on_failure. This allows a user to set the latter
  4506. // in the code (perhaps in order to use Google Test assertions
  4507. // with another testing framework) and specify the former on the
  4508. // command line for debugging.
  4509. if (GTEST_FLAG(break_on_failure)) {
  4510. #if GTEST_OS_WINDOWS
  4511. // Using DebugBreak on Windows allows gtest to still break into a debugger
  4512. // when a failure happens and both the --gtest_break_on_failure and
  4513. // the --gtest_catch_exceptions flags are specified.
  4514. DebugBreak();
  4515. #else
  4516. // Dereference NULL through a volatile pointer to prevent the compiler
  4517. // from removing. We use this rather than abort() or __builtin_trap() for
  4518. // portability: Symbian doesn't implement abort() well, and some debuggers
  4519. // don't correctly trap abort().
  4520. *static_cast<volatile int*>(NULL) = 1;
  4521. #endif // GTEST_OS_WINDOWS
  4522. } else if (GTEST_FLAG(throw_on_failure)) {
  4523. #if GTEST_HAS_EXCEPTIONS
  4524. throw internal::GoogleTestFailureException(result);
  4525. #else
  4526. // We cannot call abort() as it generates a pop-up in debug mode
  4527. // that cannot be suppressed in VC 7.1 or below.
  4528. exit(1);
  4529. #endif
  4530. }
  4531. }
  4532. }
  4533. // Adds a TestProperty to the current TestResult object when invoked from
  4534. // inside a test, to current TestCase's ad_hoc_test_result_ when invoked
  4535. // from SetUpTestCase or TearDownTestCase, or to the global property set
  4536. // when invoked elsewhere. If the result already contains a property with
  4537. // the same key, the value will be updated.
  4538. void UnitTest::RecordProperty(const std::string& key,
  4539. const std::string& value) {
  4540. impl_->RecordProperty(TestProperty(key, value));
  4541. }
  4542. // Runs all tests in this UnitTest object and prints the result.
  4543. // Returns 0 if successful, or 1 otherwise.
  4544. //
  4545. // We don't protect this under mutex_, as we only support calling it
  4546. // from the main thread.
  4547. int UnitTest::Run() {
  4548. const bool in_death_test_child_process =
  4549. internal::GTEST_FLAG(internal_run_death_test).length() > 0;
  4550. // Google Test implements this protocol for catching that a test
  4551. // program exits before returning control to Google Test:
  4552. //
  4553. // 1. Upon start, Google Test creates a file whose absolute path
  4554. // is specified by the environment variable
  4555. // TEST_PREMATURE_EXIT_FILE.
  4556. // 2. When Google Test has finished its work, it deletes the file.
  4557. //
  4558. // This allows a test runner to set TEST_PREMATURE_EXIT_FILE before
  4559. // running a Google-Test-based test program and check the existence
  4560. // of the file at the end of the test execution to see if it has
  4561. // exited prematurely.
  4562. // If we are in the child process of a death test, don't
  4563. // create/delete the premature exit file, as doing so is unnecessary
  4564. // and will confuse the parent process. Otherwise, create/delete
  4565. // the file upon entering/leaving this function. If the program
  4566. // somehow exits before this function has a chance to return, the
  4567. // premature-exit file will be left undeleted, causing a test runner
  4568. // that understands the premature-exit-file protocol to report the
  4569. // test as having failed.
  4570. const internal::ScopedPrematureExitFile premature_exit_file(
  4571. in_death_test_child_process ?
  4572. NULL : internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE"));
  4573. // Captures the value of GTEST_FLAG(catch_exceptions). This value will be
  4574. // used for the duration of the program.
  4575. impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions));
  4576. #if GTEST_HAS_SEH
  4577. // Either the user wants Google Test to catch exceptions thrown by the
  4578. // tests or this is executing in the context of death test child
  4579. // process. In either case the user does not want to see pop-up dialogs
  4580. // about crashes - they are expected.
  4581. if (impl()->catch_exceptions() || in_death_test_child_process) {
  4582. # if !GTEST_OS_WINDOWS_MOBILE
  4583. // SetErrorMode doesn't exist on CE.
  4584. SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
  4585. SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
  4586. # endif // !GTEST_OS_WINDOWS_MOBILE
  4587. # if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
  4588. // Death test children can be terminated with _abort(). On Windows,
  4589. // _abort() can show a dialog with a warning message. This forces the
  4590. // abort message to go to stderr instead.
  4591. _set_error_mode(_OUT_TO_STDERR);
  4592. # endif
  4593. # if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
  4594. // In the debug version, Visual Studio pops up a separate dialog
  4595. // offering a choice to debug the aborted program. We need to suppress
  4596. // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
  4597. // executed. Google Test will notify the user of any unexpected
  4598. // failure via stderr.
  4599. //
  4600. // VC++ doesn't define _set_abort_behavior() prior to the version 8.0.
  4601. // Users of prior VC versions shall suffer the agony and pain of
  4602. // clicking through the countless debug dialogs.
  4603. // TODO(vladl@google.com): find a way to suppress the abort dialog() in the
  4604. // debug mode when compiled with VC 7.1 or lower.
  4605. if (!GTEST_FLAG(break_on_failure))
  4606. _set_abort_behavior(
  4607. 0x0, // Clear the following flags:
  4608. _WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump.
  4609. # endif
  4610. }
  4611. #endif // GTEST_HAS_SEH
  4612. return internal::HandleExceptionsInMethodIfSupported(
  4613. impl(),
  4614. &internal::UnitTestImpl::RunAllTests,
  4615. "auxiliary test code (environments or event listeners)") ? 0 : 1;
  4616. }
  4617. // Returns the working directory when the first TEST() or TEST_F() was
  4618. // executed.
  4619. const char* UnitTest::original_working_dir() const {
  4620. return impl_->original_working_dir_.c_str();
  4621. }
  4622. // Returns the TestCase object for the test that's currently running,
  4623. // or NULL if no test is running.
  4624. const TestCase* UnitTest::current_test_case() const
  4625. GTEST_LOCK_EXCLUDED_(mutex_) {
  4626. internal::MutexLock lock(&mutex_);
  4627. return impl_->current_test_case();
  4628. }
  4629. // Returns the TestInfo object for the test that's currently running,
  4630. // or NULL if no test is running.
  4631. const TestInfo* UnitTest::current_test_info() const
  4632. GTEST_LOCK_EXCLUDED_(mutex_) {
  4633. internal::MutexLock lock(&mutex_);
  4634. return impl_->current_test_info();
  4635. }
  4636. // Returns the random seed used at the start of the current test run.
  4637. int UnitTest::random_seed() const { return impl_->random_seed(); }
  4638. #if GTEST_HAS_PARAM_TEST
  4639. // Returns ParameterizedTestCaseRegistry object used to keep track of
  4640. // value-parameterized tests and instantiate and register them.
  4641. internal::ParameterizedTestCaseRegistry&
  4642. UnitTest::parameterized_test_registry()
  4643. GTEST_LOCK_EXCLUDED_(mutex_) {
  4644. return impl_->parameterized_test_registry();
  4645. }
  4646. #endif // GTEST_HAS_PARAM_TEST
  4647. // Creates an empty UnitTest.
  4648. UnitTest::UnitTest() {
  4649. impl_ = new internal::UnitTestImpl(this);
  4650. }
  4651. // Destructor of UnitTest.
  4652. UnitTest::~UnitTest() {
  4653. delete impl_;
  4654. }
  4655. // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
  4656. // Google Test trace stack.
  4657. void UnitTest::PushGTestTrace(const internal::TraceInfo& trace)
  4658. GTEST_LOCK_EXCLUDED_(mutex_) {
  4659. internal::MutexLock lock(&mutex_);
  4660. impl_->gtest_trace_stack().push_back(trace);
  4661. }
  4662. // Pops a trace from the per-thread Google Test trace stack.
  4663. void UnitTest::PopGTestTrace()
  4664. GTEST_LOCK_EXCLUDED_(mutex_) {
  4665. internal::MutexLock lock(&mutex_);
  4666. impl_->gtest_trace_stack().pop_back();
  4667. }
  4668. namespace internal {
  4669. UnitTestImpl::UnitTestImpl(UnitTest* parent)
  4670. : parent_(parent),
  4671. #ifdef _MSC_VER
  4672. # pragma warning(push) // Saves the current warning state.
  4673. # pragma warning(disable:4355) // Temporarily disables warning 4355
  4674. // (using this in initializer).
  4675. default_global_test_part_result_reporter_(this),
  4676. default_per_thread_test_part_result_reporter_(this),
  4677. # pragma warning(pop) // Restores the warning state again.
  4678. #else
  4679. default_global_test_part_result_reporter_(this),
  4680. default_per_thread_test_part_result_reporter_(this),
  4681. #endif // _MSC_VER
  4682. global_test_part_result_repoter_(
  4683. &default_global_test_part_result_reporter_),
  4684. per_thread_test_part_result_reporter_(
  4685. &default_per_thread_test_part_result_reporter_),
  4686. #if GTEST_HAS_PARAM_TEST
  4687. parameterized_test_registry_(),
  4688. parameterized_tests_registered_(false),
  4689. #endif // GTEST_HAS_PARAM_TEST
  4690. last_death_test_case_(-1),
  4691. current_test_case_(NULL),
  4692. current_test_info_(NULL),
  4693. ad_hoc_test_result_(),
  4694. os_stack_trace_getter_(NULL),
  4695. post_flag_parse_init_performed_(false),
  4696. random_seed_(0), // Will be overridden by the flag before first use.
  4697. random_(0), // Will be reseeded before first use.
  4698. start_timestamp_(0),
  4699. elapsed_time_(0),
  4700. #if GTEST_HAS_DEATH_TEST
  4701. death_test_factory_(new DefaultDeathTestFactory),
  4702. #endif
  4703. // Will be overridden by the flag before first use.
  4704. catch_exceptions_(false) {
  4705. listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);
  4706. }
  4707. UnitTestImpl::~UnitTestImpl() {
  4708. // Deletes every TestCase.
  4709. ForEach(test_cases_, internal::Delete<TestCase>);
  4710. // Deletes every Environment.
  4711. ForEach(environments_, internal::Delete<Environment>);
  4712. delete os_stack_trace_getter_;
  4713. }
  4714. // Adds a TestProperty to the current TestResult object when invoked in a
  4715. // context of a test, to current test case's ad_hoc_test_result when invoke
  4716. // from SetUpTestCase/TearDownTestCase, or to the global property set
  4717. // otherwise. If the result already contains a property with the same key,
  4718. // the value will be updated.
  4719. void UnitTestImpl::RecordProperty(const TestProperty& test_property) {
  4720. std::string xml_element;
  4721. TestResult* test_result; // TestResult appropriate for property recording.
  4722. if (current_test_info_ != NULL) {
  4723. xml_element = "testcase";
  4724. test_result = &(current_test_info_->result_);
  4725. } else if (current_test_case_ != NULL) {
  4726. xml_element = "testsuite";
  4727. test_result = &(current_test_case_->ad_hoc_test_result_);
  4728. } else {
  4729. xml_element = "testsuites";
  4730. test_result = &ad_hoc_test_result_;
  4731. }
  4732. test_result->RecordProperty(xml_element, test_property);
  4733. }
  4734. #if GTEST_HAS_DEATH_TEST
  4735. // Disables event forwarding if the control is currently in a death test
  4736. // subprocess. Must not be called before InitGoogleTest.
  4737. void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
  4738. if (internal_run_death_test_flag_.get() != NULL)
  4739. listeners()->SuppressEventForwarding();
  4740. }
  4741. #endif // GTEST_HAS_DEATH_TEST
  4742. // Initializes event listeners performing XML output as specified by
  4743. // UnitTestOptions. Must not be called before InitGoogleTest.
  4744. void UnitTestImpl::ConfigureXmlOutput() {
  4745. const std::string& output_format = UnitTestOptions::GetOutputFormat();
  4746. if (output_format == "xml") {
  4747. listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
  4748. UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
  4749. } else if (output_format != "") {
  4750. printf("WARNING: unrecognized output format \"%s\" ignored.\n",
  4751. output_format.c_str());
  4752. fflush(stdout);
  4753. }
  4754. }
  4755. #if GTEST_CAN_STREAM_RESULTS_
  4756. // Initializes event listeners for streaming test results in string form.
  4757. // Must not be called before InitGoogleTest.
  4758. void UnitTestImpl::ConfigureStreamingOutput() {
  4759. const std::string& target = GTEST_FLAG(stream_result_to);
  4760. if (!target.empty()) {
  4761. const size_t pos = target.find(':');
  4762. if (pos != std::string::npos) {
  4763. listeners()->Append(new StreamingListener(target.substr(0, pos),
  4764. target.substr(pos+1)));
  4765. } else {
  4766. printf("WARNING: unrecognized streaming target \"%s\" ignored.\n",
  4767. target.c_str());
  4768. fflush(stdout);
  4769. }
  4770. }
  4771. }
  4772. #endif // GTEST_CAN_STREAM_RESULTS_
  4773. // Performs initialization dependent upon flag values obtained in
  4774. // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
  4775. // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
  4776. // this function is also called from RunAllTests. Since this function can be
  4777. // called more than once, it has to be idempotent.
  4778. void UnitTestImpl::PostFlagParsingInit() {
  4779. // Ensures that this function does not execute more than once.
  4780. if (!post_flag_parse_init_performed_) {
  4781. post_flag_parse_init_performed_ = true;
  4782. #if GTEST_HAS_DEATH_TEST
  4783. InitDeathTestSubprocessControlInfo();
  4784. SuppressTestEventsIfInSubprocess();
  4785. #endif // GTEST_HAS_DEATH_TEST
  4786. // Registers parameterized tests. This makes parameterized tests
  4787. // available to the UnitTest reflection API without running
  4788. // RUN_ALL_TESTS.
  4789. RegisterParameterizedTests();
  4790. // Configures listeners for XML output. This makes it possible for users
  4791. // to shut down the default XML output before invoking RUN_ALL_TESTS.
  4792. ConfigureXmlOutput();
  4793. #if GTEST_CAN_STREAM_RESULTS_
  4794. // Configures listeners for streaming test results to the specified server.
  4795. ConfigureStreamingOutput();
  4796. #endif // GTEST_CAN_STREAM_RESULTS_
  4797. }
  4798. }
  4799. // A predicate that checks the name of a TestCase against a known
  4800. // value.
  4801. //
  4802. // This is used for implementation of the UnitTest class only. We put
  4803. // it in the anonymous namespace to prevent polluting the outer
  4804. // namespace.
  4805. //
  4806. // TestCaseNameIs is copyable.
  4807. class TestCaseNameIs {
  4808. public:
  4809. // Constructor.
  4810. explicit TestCaseNameIs(const std::string& name)
  4811. : name_(name) {}
  4812. // Returns true iff the name of test_case matches name_.
  4813. bool operator()(const TestCase* test_case) const {
  4814. return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0;
  4815. }
  4816. private:
  4817. std::string name_;
  4818. };
  4819. // Finds and returns a TestCase with the given name. If one doesn't
  4820. // exist, creates one and returns it. It's the CALLER'S
  4821. // RESPONSIBILITY to ensure that this function is only called WHEN THE
  4822. // TESTS ARE NOT SHUFFLED.
  4823. //
  4824. // Arguments:
  4825. //
  4826. // test_case_name: name of the test case
  4827. // type_param: the name of the test case's type parameter, or NULL if
  4828. // this is not a typed or a type-parameterized test case.
  4829. // set_up_tc: pointer to the function that sets up the test case
  4830. // tear_down_tc: pointer to the function that tears down the test case
  4831. TestCase* UnitTestImpl::GetTestCase(const char* test_case_name,
  4832. const char* type_param,
  4833. Test::SetUpTestCaseFunc set_up_tc,
  4834. Test::TearDownTestCaseFunc tear_down_tc) {
  4835. // Can we find a TestCase with the given name?
  4836. const std::vector<TestCase*>::const_iterator test_case =
  4837. std::find_if(test_cases_.begin(), test_cases_.end(),
  4838. TestCaseNameIs(test_case_name));
  4839. if (test_case != test_cases_.end())
  4840. return *test_case;
  4841. // No. Let's create one.
  4842. TestCase* const new_test_case =
  4843. new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc);
  4844. // Is this a death test case?
  4845. if (internal::UnitTestOptions::MatchesFilter(test_case_name,
  4846. kDeathTestCaseFilter)) {
  4847. // Yes. Inserts the test case after the last death test case
  4848. // defined so far. This only works when the test cases haven't
  4849. // been shuffled. Otherwise we may end up running a death test
  4850. // after a non-death test.
  4851. ++last_death_test_case_;
  4852. test_cases_.insert(test_cases_.begin() + last_death_test_case_,
  4853. new_test_case);
  4854. } else {
  4855. // No. Appends to the end of the list.
  4856. test_cases_.push_back(new_test_case);
  4857. }
  4858. test_case_indices_.push_back(static_cast<int>(test_case_indices_.size()));
  4859. return new_test_case;
  4860. }
  4861. // Helpers for setting up / tearing down the given environment. They
  4862. // are for use in the ForEach() function.
  4863. static void SetUpEnvironment(Environment* env) { env->SetUp(); }
  4864. static void TearDownEnvironment(Environment* env) { env->TearDown(); }
  4865. // Runs all tests in this UnitTest object, prints the result, and
  4866. // returns true if all tests are successful. If any exception is
  4867. // thrown during a test, the test is considered to be failed, but the
  4868. // rest of the tests will still be run.
  4869. //
  4870. // When parameterized tests are enabled, it expands and registers
  4871. // parameterized tests first in RegisterParameterizedTests().
  4872. // All other functions called from RunAllTests() may safely assume that
  4873. // parameterized tests are ready to be counted and run.
  4874. bool UnitTestImpl::RunAllTests() {
  4875. // Makes sure InitGoogleTest() was called.
  4876. if (!GTestIsInitialized()) {
  4877. printf("%s",
  4878. "\nThis test program did NOT call ::testing::InitGoogleTest "
  4879. "before calling RUN_ALL_TESTS(). Please fix it.\n");
  4880. return false;
  4881. }
  4882. // Do not run any test if the --help flag was specified.
  4883. if (g_help_flag)
  4884. return true;
  4885. // Repeats the call to the post-flag parsing initialization in case the
  4886. // user didn't call InitGoogleTest.
  4887. PostFlagParsingInit();
  4888. // Even if sharding is not on, test runners may want to use the
  4889. // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
  4890. // protocol.
  4891. internal::WriteToShardStatusFileIfNeeded();
  4892. // True iff we are in a subprocess for running a thread-safe-style
  4893. // death test.
  4894. bool in_subprocess_for_death_test = false;
  4895. #if GTEST_HAS_DEATH_TEST
  4896. in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL);
  4897. #endif // GTEST_HAS_DEATH_TEST
  4898. const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
  4899. in_subprocess_for_death_test);
  4900. // Compares the full test names with the filter to decide which
  4901. // tests to run.
  4902. const bool has_tests_to_run = FilterTests(should_shard
  4903. ? HONOR_SHARDING_PROTOCOL
  4904. : IGNORE_SHARDING_PROTOCOL) > 0;
  4905. // Lists the tests and exits if the --gtest_list_tests flag was specified.
  4906. if (GTEST_FLAG(list_tests)) {
  4907. // This must be called *after* FilterTests() has been called.
  4908. ListTestsMatchingFilter();
  4909. return true;
  4910. }
  4911. random_seed_ = GTEST_FLAG(shuffle) ?
  4912. GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;
  4913. // True iff at least one test has failed.
  4914. bool failed = false;
  4915. TestEventListener* repeater = listeners()->repeater();
  4916. start_timestamp_ = GetTimeInMillis();
  4917. repeater->OnTestProgramStart(*parent_);
  4918. // How many times to repeat the tests? We don't want to repeat them
  4919. // when we are inside the subprocess of a death test.
  4920. const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);
  4921. // Repeats forever if the repeat count is negative.
  4922. const bool forever = repeat < 0;
  4923. for (int i = 0; forever || i != repeat; i++) {
  4924. // We want to preserve failures generated by ad-hoc test
  4925. // assertions executed before RUN_ALL_TESTS().
  4926. ClearNonAdHocTestResult();
  4927. const TimeInMillis start = GetTimeInMillis();
  4928. // Shuffles test cases and tests if requested.
  4929. if (has_tests_to_run && GTEST_FLAG(shuffle)) {
  4930. random()->Reseed(random_seed_);
  4931. // This should be done before calling OnTestIterationStart(),
  4932. // such that a test event listener can see the actual test order
  4933. // in the event.
  4934. ShuffleTests();
  4935. }
  4936. // Tells the unit test event listeners that the tests are about to start.
  4937. repeater->OnTestIterationStart(*parent_, i);
  4938. // Runs each test case if there is at least one test to run.
  4939. if (has_tests_to_run) {
  4940. // Sets up all environments beforehand.
  4941. repeater->OnEnvironmentsSetUpStart(*parent_);
  4942. ForEach(environments_, SetUpEnvironment);
  4943. repeater->OnEnvironmentsSetUpEnd(*parent_);
  4944. // Runs the tests only if there was no fatal failure during global
  4945. // set-up.
  4946. if (!Test::HasFatalFailure()) {
  4947. for (int test_index = 0; test_index < total_test_case_count();
  4948. test_index++) {
  4949. GetMutableTestCase(test_index)->Run();
  4950. }
  4951. }
  4952. // Tears down all environments in reverse order afterwards.
  4953. repeater->OnEnvironmentsTearDownStart(*parent_);
  4954. std::for_each(environments_.rbegin(), environments_.rend(),
  4955. TearDownEnvironment);
  4956. repeater->OnEnvironmentsTearDownEnd(*parent_);
  4957. }
  4958. elapsed_time_ = GetTimeInMillis() - start;
  4959. // Tells the unit test event listener that the tests have just finished.
  4960. repeater->OnTestIterationEnd(*parent_, i);
  4961. // Gets the result and clears it.
  4962. if (!Passed()) {
  4963. failed = true;
  4964. }
  4965. // Restores the original test order after the iteration. This
  4966. // allows the user to quickly repro a failure that happens in the
  4967. // N-th iteration without repeating the first (N - 1) iterations.
  4968. // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in
  4969. // case the user somehow changes the value of the flag somewhere
  4970. // (it's always safe to unshuffle the tests).
  4971. UnshuffleTests();
  4972. if (GTEST_FLAG(shuffle)) {
  4973. // Picks a new random seed for each iteration.
  4974. random_seed_ = GetNextRandomSeed(random_seed_);
  4975. }
  4976. }
  4977. repeater->OnTestProgramEnd(*parent_);
  4978. return !failed;
  4979. }
  4980. // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
  4981. // if the variable is present. If a file already exists at this location, this
  4982. // function will write over it. If the variable is present, but the file cannot
  4983. // be created, prints an error and exits.
  4984. void WriteToShardStatusFileIfNeeded() {
  4985. const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);
  4986. if (test_shard_file != NULL) {
  4987. FILE* const file = posix::FOpen(test_shard_file, "w");
  4988. if (file == NULL) {
  4989. ColoredPrintf(COLOR_RED,
  4990. "Could not write to the test shard status file \"%s\" "
  4991. "specified by the %s environment variable.\n",
  4992. test_shard_file, kTestShardStatusFile);
  4993. fflush(stdout);
  4994. exit(EXIT_FAILURE);
  4995. }
  4996. fclose(file);
  4997. }
  4998. }
  4999. // Checks whether sharding is enabled by examining the relevant
  5000. // environment variable values. If the variables are present,
  5001. // but inconsistent (i.e., shard_index >= total_shards), prints
  5002. // an error and exits. If in_subprocess_for_death_test, sharding is
  5003. // disabled because it must only be applied to the original test
  5004. // process. Otherwise, we could filter out death tests we intended to execute.
  5005. bool ShouldShard(const char* total_shards_env,
  5006. const char* shard_index_env,
  5007. bool in_subprocess_for_death_test) {
  5008. if (in_subprocess_for_death_test) {
  5009. return false;
  5010. }
  5011. const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1);
  5012. const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1);
  5013. if (total_shards == -1 && shard_index == -1) {
  5014. return false;
  5015. } else if (total_shards == -1 && shard_index != -1) {
  5016. const Message msg = Message()
  5017. << "Invalid environment variables: you have "
  5018. << kTestShardIndex << " = " << shard_index
  5019. << ", but have left " << kTestTotalShards << " unset.\n";
  5020. ColoredPrintf(COLOR_RED, msg.GetString().c_str());
  5021. fflush(stdout);
  5022. exit(EXIT_FAILURE);
  5023. } else if (total_shards != -1 && shard_index == -1) {
  5024. const Message msg = Message()
  5025. << "Invalid environment variables: you have "
  5026. << kTestTotalShards << " = " << total_shards
  5027. << ", but have left " << kTestShardIndex << " unset.\n";
  5028. ColoredPrintf(COLOR_RED, msg.GetString().c_str());
  5029. fflush(stdout);
  5030. exit(EXIT_FAILURE);
  5031. } else if (shard_index < 0 || shard_index >= total_shards) {
  5032. const Message msg = Message()
  5033. << "Invalid environment variables: we require 0 <= "
  5034. << kTestShardIndex << " < " << kTestTotalShards
  5035. << ", but you have " << kTestShardIndex << "=" << shard_index
  5036. << ", " << kTestTotalShards << "=" << total_shards << ".\n";
  5037. ColoredPrintf(COLOR_RED, msg.GetString().c_str());
  5038. fflush(stdout);
  5039. exit(EXIT_FAILURE);
  5040. }
  5041. return total_shards > 1;
  5042. }
  5043. // Parses the environment variable var as an Int32. If it is unset,
  5044. // returns default_val. If it is not an Int32, prints an error
  5045. // and aborts.
  5046. Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) {
  5047. const char* str_val = posix::GetEnv(var);
  5048. if (str_val == NULL) {
  5049. return default_val;
  5050. }
  5051. Int32 result;
  5052. if (!ParseInt32(Message() << "The value of environment variable " << var,
  5053. str_val, &result)) {
  5054. exit(EXIT_FAILURE);
  5055. }
  5056. return result;
  5057. }
  5058. // Given the total number of shards, the shard index, and the test id,
  5059. // returns true iff the test should be run on this shard. The test id is
  5060. // some arbitrary but unique non-negative integer assigned to each test
  5061. // method. Assumes that 0 <= shard_index < total_shards.
  5062. bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
  5063. return (test_id % total_shards) == shard_index;
  5064. }
  5065. // Compares the name of each test with the user-specified filter to
  5066. // decide whether the test should be run, then records the result in
  5067. // each TestCase and TestInfo object.
  5068. // If shard_tests == true, further filters tests based on sharding
  5069. // variables in the environment - see
  5070. // http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide.
  5071. // Returns the number of tests that should run.
  5072. int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
  5073. const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?
  5074. Int32FromEnvOrDie(kTestTotalShards, -1) : -1;
  5075. const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?
  5076. Int32FromEnvOrDie(kTestShardIndex, -1) : -1;
  5077. // num_runnable_tests are the number of tests that will
  5078. // run across all shards (i.e., match filter and are not disabled).
  5079. // num_selected_tests are the number of tests to be run on
  5080. // this shard.
  5081. int num_runnable_tests = 0;
  5082. int num_selected_tests = 0;
  5083. for (size_t i = 0; i < test_cases_.size(); i++) {
  5084. TestCase* const test_case = test_cases_[i];
  5085. const std::string &test_case_name = test_case->name();
  5086. test_case->set_should_run(false);
  5087. for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
  5088. TestInfo* const test_info = test_case->test_info_list()[j];
  5089. const std::string test_name(test_info->name());
  5090. // A test is disabled if test case name or test name matches
  5091. // kDisableTestFilter.
  5092. const bool is_disabled =
  5093. internal::UnitTestOptions::MatchesFilter(test_case_name,
  5094. kDisableTestFilter) ||
  5095. internal::UnitTestOptions::MatchesFilter(test_name,
  5096. kDisableTestFilter);
  5097. test_info->is_disabled_ = is_disabled;
  5098. const bool matches_filter =
  5099. internal::UnitTestOptions::FilterMatchesTest(test_case_name,
  5100. test_name);
  5101. test_info->matches_filter_ = matches_filter;
  5102. const bool is_runnable =
  5103. (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
  5104. matches_filter;
  5105. const bool is_selected = is_runnable &&
  5106. (shard_tests == IGNORE_SHARDING_PROTOCOL ||
  5107. ShouldRunTestOnShard(total_shards, shard_index,
  5108. num_runnable_tests));
  5109. num_runnable_tests += is_runnable;
  5110. num_selected_tests += is_selected;
  5111. test_info->should_run_ = is_selected;
  5112. test_case->set_should_run(test_case->should_run() || is_selected);
  5113. }
  5114. }
  5115. return num_selected_tests;
  5116. }
  5117. // Prints the given C-string on a single line by replacing all '\n'
  5118. // characters with string "\\n". If the output takes more than
  5119. // max_length characters, only prints the first max_length characters
  5120. // and "...".
  5121. static void PrintOnOneLine(const char* str, int max_length) {
  5122. if (str != NULL) {
  5123. for (int i = 0; *str != '\0'; ++str) {
  5124. if (i >= max_length) {
  5125. printf("...");
  5126. break;
  5127. }
  5128. if (*str == '\n') {
  5129. printf("\\n");
  5130. i += 2;
  5131. } else {
  5132. printf("%c", *str);
  5133. ++i;
  5134. }
  5135. }
  5136. }
  5137. }
  5138. // Prints the names of the tests matching the user-specified filter flag.
  5139. void UnitTestImpl::ListTestsMatchingFilter() {
  5140. // Print at most this many characters for each type/value parameter.
  5141. const int kMaxParamLength = 250;
  5142. for (size_t i = 0; i < test_cases_.size(); i++) {
  5143. const TestCase* const test_case = test_cases_[i];
  5144. bool printed_test_case_name = false;
  5145. for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
  5146. const TestInfo* const test_info =
  5147. test_case->test_info_list()[j];
  5148. if (test_info->matches_filter_) {
  5149. if (!printed_test_case_name) {
  5150. printed_test_case_name = true;
  5151. printf("%s.", test_case->name());
  5152. if (test_case->type_param() != NULL) {
  5153. printf(" # %s = ", kTypeParamLabel);
  5154. // We print the type parameter on a single line to make
  5155. // the output easy to parse by a program.
  5156. PrintOnOneLine(test_case->type_param(), kMaxParamLength);
  5157. }
  5158. printf("\n");
  5159. }
  5160. printf(" %s", test_info->name());
  5161. if (test_info->value_param() != NULL) {
  5162. printf(" # %s = ", kValueParamLabel);
  5163. // We print the value parameter on a single line to make the
  5164. // output easy to parse by a program.
  5165. PrintOnOneLine(test_info->value_param(), kMaxParamLength);
  5166. }
  5167. printf("\n");
  5168. }
  5169. }
  5170. }
  5171. fflush(stdout);
  5172. }
  5173. // Sets the OS stack trace getter.
  5174. //
  5175. // Does nothing if the input and the current OS stack trace getter are
  5176. // the same; otherwise, deletes the old getter and makes the input the
  5177. // current getter.
  5178. void UnitTestImpl::set_os_stack_trace_getter(
  5179. OsStackTraceGetterInterface* getter) {
  5180. if (os_stack_trace_getter_ != getter) {
  5181. delete os_stack_trace_getter_;
  5182. os_stack_trace_getter_ = getter;
  5183. }
  5184. }
  5185. // Returns the current OS stack trace getter if it is not NULL;
  5186. // otherwise, creates an OsStackTraceGetter, makes it the current
  5187. // getter, and returns it.
  5188. OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
  5189. if (os_stack_trace_getter_ == NULL) {
  5190. os_stack_trace_getter_ = new OsStackTraceGetter;
  5191. }
  5192. return os_stack_trace_getter_;
  5193. }
  5194. // Returns the TestResult for the test that's currently running, or
  5195. // the TestResult for the ad hoc test if no test is running.
  5196. TestResult* UnitTestImpl::current_test_result() {
  5197. return current_test_info_ ?
  5198. &(current_test_info_->result_) : &ad_hoc_test_result_;
  5199. }
  5200. // Shuffles all test cases, and the tests within each test case,
  5201. // making sure that death tests are still run first.
  5202. void UnitTestImpl::ShuffleTests() {
  5203. // Shuffles the death test cases.
  5204. ShuffleRange(random(), 0, last_death_test_case_ + 1, &test_case_indices_);
  5205. // Shuffles the non-death test cases.
  5206. ShuffleRange(random(), last_death_test_case_ + 1,
  5207. static_cast<int>(test_cases_.size()), &test_case_indices_);
  5208. // Shuffles the tests inside each test case.
  5209. for (size_t i = 0; i < test_cases_.size(); i++) {
  5210. test_cases_[i]->ShuffleTests(random());
  5211. }
  5212. }
  5213. // Restores the test cases and tests to their order before the first shuffle.
  5214. void UnitTestImpl::UnshuffleTests() {
  5215. for (size_t i = 0; i < test_cases_.size(); i++) {
  5216. // Unshuffles the tests in each test case.
  5217. test_cases_[i]->UnshuffleTests();
  5218. // Resets the index of each test case.
  5219. test_case_indices_[i] = static_cast<int>(i);
  5220. }
  5221. }
  5222. // Returns the current OS stack trace as an std::string.
  5223. //
  5224. // The maximum number of stack frames to be included is specified by
  5225. // the gtest_stack_trace_depth flag. The skip_count parameter
  5226. // specifies the number of top frames to be skipped, which doesn't
  5227. // count against the number of frames to be included.
  5228. //
  5229. // For example, if Foo() calls Bar(), which in turn calls
  5230. // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
  5231. // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
  5232. std::string GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/,
  5233. int skip_count) {
  5234. // We pass skip_count + 1 to skip this wrapper function in addition
  5235. // to what the user really wants to skip.
  5236. return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
  5237. }
  5238. // Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to
  5239. // suppress unreachable code warnings.
  5240. namespace {
  5241. class ClassUniqueToAlwaysTrue {};
  5242. }
  5243. bool IsTrue(bool condition) { return condition; }
  5244. bool AlwaysTrue() {
  5245. #if GTEST_HAS_EXCEPTIONS
  5246. // This condition is always false so AlwaysTrue() never actually throws,
  5247. // but it makes the compiler think that it may throw.
  5248. if (IsTrue(false))
  5249. throw ClassUniqueToAlwaysTrue();
  5250. #endif // GTEST_HAS_EXCEPTIONS
  5251. return true;
  5252. }
  5253. // If *pstr starts with the given prefix, modifies *pstr to be right
  5254. // past the prefix and returns true; otherwise leaves *pstr unchanged
  5255. // and returns false. None of pstr, *pstr, and prefix can be NULL.
  5256. bool SkipPrefix(const char* prefix, const char** pstr) {
  5257. const size_t prefix_len = strlen(prefix);
  5258. if (strncmp(*pstr, prefix, prefix_len) == 0) {
  5259. *pstr += prefix_len;
  5260. return true;
  5261. }
  5262. return false;
  5263. }
  5264. // Parses a string as a command line flag. The string should have
  5265. // the format "--flag=value". When def_optional is true, the "=value"
  5266. // part can be omitted.
  5267. //
  5268. // Returns the value of the flag, or NULL if the parsing failed.
  5269. const char* ParseFlagValue(const char* str,
  5270. const char* flag,
  5271. bool def_optional) {
  5272. // str and flag must not be NULL.
  5273. if (str == NULL || flag == NULL) return NULL;
  5274. // The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
  5275. const std::string flag_str = std::string("--") + GTEST_FLAG_PREFIX_ + flag;
  5276. const size_t flag_len = flag_str.length();
  5277. if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;
  5278. // Skips the flag name.
  5279. const char* flag_end = str + flag_len;
  5280. // When def_optional is true, it's OK to not have a "=value" part.
  5281. if (def_optional && (flag_end[0] == '\0')) {
  5282. return flag_end;
  5283. }
  5284. // If def_optional is true and there are more characters after the
  5285. // flag name, or if def_optional is false, there must be a '=' after
  5286. // the flag name.
  5287. if (flag_end[0] != '=') return NULL;
  5288. // Returns the string after "=".
  5289. return flag_end + 1;
  5290. }
  5291. // Parses a string for a bool flag, in the form of either
  5292. // "--flag=value" or "--flag".
  5293. //
  5294. // In the former case, the value is taken as true as long as it does
  5295. // not start with '0', 'f', or 'F'.
  5296. //
  5297. // In the latter case, the value is taken as true.
  5298. //
  5299. // On success, stores the value of the flag in *value, and returns
  5300. // true. On failure, returns false without changing *value.
  5301. bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
  5302. // Gets the value of the flag as a string.
  5303. const char* const value_str = ParseFlagValue(str, flag, true);
  5304. // Aborts if the parsing failed.
  5305. if (value_str == NULL) return false;
  5306. // Converts the string value to a bool.
  5307. *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
  5308. return true;
  5309. }
  5310. // Parses a string for an Int32 flag, in the form of
  5311. // "--flag=value".
  5312. //
  5313. // On success, stores the value of the flag in *value, and returns
  5314. // true. On failure, returns false without changing *value.
  5315. bool ParseInt32Flag(const char* str, const char* flag, Int32* value) {
  5316. // Gets the value of the flag as a string.
  5317. const char* const value_str = ParseFlagValue(str, flag, false);
  5318. // Aborts if the parsing failed.
  5319. if (value_str == NULL) return false;
  5320. // Sets *value to the value of the flag.
  5321. return ParseInt32(Message() << "The value of flag --" << flag,
  5322. value_str, value);
  5323. }
  5324. // Parses a string for a string flag, in the form of
  5325. // "--flag=value".
  5326. //
  5327. // On success, stores the value of the flag in *value, and returns
  5328. // true. On failure, returns false without changing *value.
  5329. bool ParseStringFlag(const char* str, const char* flag, std::string* value) {
  5330. // Gets the value of the flag as a string.
  5331. const char* const value_str = ParseFlagValue(str, flag, false);
  5332. // Aborts if the parsing failed.
  5333. if (value_str == NULL) return false;
  5334. // Sets *value to the value of the flag.
  5335. *value = value_str;
  5336. return true;
  5337. }
  5338. // Determines whether a string has a prefix that Google Test uses for its
  5339. // flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.
  5340. // If Google Test detects that a command line flag has its prefix but is not
  5341. // recognized, it will print its help message. Flags starting with
  5342. // GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
  5343. // internal flags and do not trigger the help message.
  5344. static bool HasGoogleTestFlagPrefix(const char* str) {
  5345. return (SkipPrefix("--", &str) ||
  5346. SkipPrefix("-", &str) ||
  5347. SkipPrefix("/", &str)) &&
  5348. !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
  5349. (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
  5350. SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str));
  5351. }
  5352. // Prints a string containing code-encoded text. The following escape
  5353. // sequences can be used in the string to control the text color:
  5354. //
  5355. // @@ prints a single '@' character.
  5356. // @R changes the color to red.
  5357. // @G changes the color to green.
  5358. // @Y changes the color to yellow.
  5359. // @D changes to the default terminal text color.
  5360. //
  5361. // TODO(wan@google.com): Write tests for this once we add stdout
  5362. // capturing to Google Test.
  5363. static void PrintColorEncoded(const char* str) {
  5364. GTestColor color = COLOR_DEFAULT; // The current color.
  5365. // Conceptually, we split the string into segments divided by escape
  5366. // sequences. Then we print one segment at a time. At the end of
  5367. // each iteration, the str pointer advances to the beginning of the
  5368. // next segment.
  5369. for (;;) {
  5370. const char* p = strchr(str, '@');
  5371. if (p == NULL) {
  5372. ColoredPrintf(color, "%s", str);
  5373. return;
  5374. }
  5375. ColoredPrintf(color, "%s", std::string(str, p).c_str());
  5376. const char ch = p[1];
  5377. str = p + 2;
  5378. if (ch == '@') {
  5379. ColoredPrintf(color, "@");
  5380. } else if (ch == 'D') {
  5381. color = COLOR_DEFAULT;
  5382. } else if (ch == 'R') {
  5383. color = COLOR_RED;
  5384. } else if (ch == 'G') {
  5385. color = COLOR_GREEN;
  5386. } else if (ch == 'Y') {
  5387. color = COLOR_YELLOW;
  5388. } else {
  5389. --str;
  5390. }
  5391. }
  5392. }
  5393. static const char kColorEncodedHelpMessage[] =
  5394. "This program contains tests written using " GTEST_NAME_ ". You can use the\n"
  5395. "following command line flags to control its behavior:\n"
  5396. "\n"
  5397. "Test Selection:\n"
  5398. " @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n"
  5399. " List the names of all tests instead of running them. The name of\n"
  5400. " TEST(Foo, Bar) is \"Foo.Bar\".\n"
  5401. " @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS"
  5402. "[@G-@YNEGATIVE_PATTERNS]@D\n"
  5403. " Run only the tests whose name matches one of the positive patterns but\n"
  5404. " none of the negative patterns. '?' matches any single character; '*'\n"
  5405. " matches any substring; ':' separates two patterns.\n"
  5406. " @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n"
  5407. " Run all disabled tests too.\n"
  5408. "\n"
  5409. "Test Execution:\n"
  5410. " @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n"
  5411. " Run the tests repeatedly; use a negative count to repeat forever.\n"
  5412. " @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n"
  5413. " Randomize tests' orders on every iteration.\n"
  5414. " @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n"
  5415. " Random number seed to use for shuffling test orders (between 1 and\n"
  5416. " 99999, or 0 to use a seed based on the current time).\n"
  5417. "\n"
  5418. "Test Output:\n"
  5419. " @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
  5420. " Enable/disable colored output. The default is @Gauto@D.\n"
  5421. " -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n"
  5422. " Don't print the elapsed time of each test.\n"
  5423. " @G--" GTEST_FLAG_PREFIX_ "output=xml@Y[@G:@YDIRECTORY_PATH@G"
  5424. GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n"
  5425. " Generate an XML report in the given directory or with the given file\n"
  5426. " name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n"
  5427. #if GTEST_CAN_STREAM_RESULTS_
  5428. " @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n"
  5429. " Stream test results to the given server.\n"
  5430. #endif // GTEST_CAN_STREAM_RESULTS_
  5431. "\n"
  5432. "Assertion Behavior:\n"
  5433. #if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
  5434. " @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
  5435. " Set the default death test style.\n"
  5436. #endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
  5437. " @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n"
  5438. " Turn assertion failures into debugger break-points.\n"
  5439. " @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n"
  5440. " Turn assertion failures into C++ exceptions.\n"
  5441. " @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n"
  5442. " Do not report exceptions as test failures. Instead, allow them\n"
  5443. " to crash the program or throw a pop-up (on Windows).\n"
  5444. "\n"
  5445. "Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set "
  5446. "the corresponding\n"
  5447. "environment variable of a flag (all letters in upper-case). For example, to\n"
  5448. "disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_
  5449. "color=no@D or set\n"
  5450. "the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n"
  5451. "\n"
  5452. "For more information, please read the " GTEST_NAME_ " documentation at\n"
  5453. "@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n"
  5454. "(not one in your own code or tests), please report it to\n"
  5455. "@G<" GTEST_DEV_EMAIL_ ">@D.\n";
  5456. // Parses the command line for Google Test flags, without initializing
  5457. // other parts of Google Test. The type parameter CharType can be
  5458. // instantiated to either char or wchar_t.
  5459. template <typename CharType>
  5460. void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
  5461. for (int i = 1; i < *argc; i++) {
  5462. const std::string arg_string = StreamableToString(argv[i]);
  5463. const char* const arg = arg_string.c_str();
  5464. using internal::ParseBoolFlag;
  5465. using internal::ParseInt32Flag;
  5466. using internal::ParseStringFlag;
  5467. // Do we see a Google Test flag?
  5468. if (ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,
  5469. &GTEST_FLAG(also_run_disabled_tests)) ||
  5470. ParseBoolFlag(arg, kBreakOnFailureFlag,
  5471. &GTEST_FLAG(break_on_failure)) ||
  5472. ParseBoolFlag(arg, kCatchExceptionsFlag,
  5473. &GTEST_FLAG(catch_exceptions)) ||
  5474. ParseStringFlag(arg, kColorFlag, &GTEST_FLAG(color)) ||
  5475. ParseStringFlag(arg, kDeathTestStyleFlag,
  5476. &GTEST_FLAG(death_test_style)) ||
  5477. ParseBoolFlag(arg, kDeathTestUseFork,
  5478. &GTEST_FLAG(death_test_use_fork)) ||
  5479. ParseStringFlag(arg, kFilterFlag, &GTEST_FLAG(filter)) ||
  5480. ParseStringFlag(arg, kInternalRunDeathTestFlag,
  5481. &GTEST_FLAG(internal_run_death_test)) ||
  5482. ParseBoolFlag(arg, kListTestsFlag, &GTEST_FLAG(list_tests)) ||
  5483. ParseStringFlag(arg, kOutputFlag, &GTEST_FLAG(output)) ||
  5484. ParseBoolFlag(arg, kPrintTimeFlag, &GTEST_FLAG(print_time)) ||
  5485. ParseInt32Flag(arg, kRandomSeedFlag, &GTEST_FLAG(random_seed)) ||
  5486. ParseInt32Flag(arg, kRepeatFlag, &GTEST_FLAG(repeat)) ||
  5487. ParseBoolFlag(arg, kShuffleFlag, &GTEST_FLAG(shuffle)) ||
  5488. ParseInt32Flag(arg, kStackTraceDepthFlag,
  5489. &GTEST_FLAG(stack_trace_depth)) ||
  5490. ParseStringFlag(arg, kStreamResultToFlag,
  5491. &GTEST_FLAG(stream_result_to)) ||
  5492. ParseBoolFlag(arg, kThrowOnFailureFlag,
  5493. &GTEST_FLAG(throw_on_failure))
  5494. ) {
  5495. // Yes. Shift the remainder of the argv list left by one. Note
  5496. // that argv has (*argc + 1) elements, the last one always being
  5497. // NULL. The following loop moves the trailing NULL element as
  5498. // well.
  5499. for (int j = i; j != *argc; j++) {
  5500. argv[j] = argv[j + 1];
  5501. }
  5502. // Decrements the argument count.
  5503. (*argc)--;
  5504. // We also need to decrement the iterator as we just removed
  5505. // an element.
  5506. i--;
  5507. } else if (arg_string == "--help" || arg_string == "-h" ||
  5508. arg_string == "-?" || arg_string == "/?" ||
  5509. HasGoogleTestFlagPrefix(arg)) {
  5510. // Both help flag and unrecognized Google Test flags (excluding
  5511. // internal ones) trigger help display.
  5512. g_help_flag = true;
  5513. }
  5514. }
  5515. if (g_help_flag) {
  5516. // We print the help here instead of in RUN_ALL_TESTS(), as the
  5517. // latter may not be called at all if the user is using Google
  5518. // Test with another testing framework.
  5519. PrintColorEncoded(kColorEncodedHelpMessage);
  5520. }
  5521. }
  5522. // Parses the command line for Google Test flags, without initializing
  5523. // other parts of Google Test.
  5524. void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
  5525. ParseGoogleTestFlagsOnlyImpl(argc, argv);
  5526. }
  5527. void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {
  5528. ParseGoogleTestFlagsOnlyImpl(argc, argv);
  5529. }
  5530. // The internal implementation of InitGoogleTest().
  5531. //
  5532. // The type parameter CharType can be instantiated to either char or
  5533. // wchar_t.
  5534. template <typename CharType>
  5535. void InitGoogleTestImpl(int* argc, CharType** argv) {
  5536. g_init_gtest_count++;
  5537. // We don't want to run the initialization code twice.
  5538. if (g_init_gtest_count != 1) return;
  5539. if (*argc <= 0) return;
  5540. internal::g_executable_path = internal::StreamableToString(argv[0]);
  5541. #if GTEST_HAS_DEATH_TEST
  5542. g_argvs.clear();
  5543. for (int i = 0; i != *argc; i++) {
  5544. g_argvs.push_back(StreamableToString(argv[i]));
  5545. }
  5546. #endif // GTEST_HAS_DEATH_TEST
  5547. ParseGoogleTestFlagsOnly(argc, argv);
  5548. GetUnitTestImpl()->PostFlagParsingInit();
  5549. }
  5550. } // namespace internal
  5551. // Initializes Google Test. This must be called before calling
  5552. // RUN_ALL_TESTS(). In particular, it parses a command line for the
  5553. // flags that Google Test recognizes. Whenever a Google Test flag is
  5554. // seen, it is removed from argv, and *argc is decremented.
  5555. //
  5556. // No value is returned. Instead, the Google Test flag variables are
  5557. // updated.
  5558. //
  5559. // Calling the function for the second time has no user-visible effect.
  5560. void InitGoogleTest(int* argc, char** argv) {
  5561. internal::InitGoogleTestImpl(argc, argv);
  5562. }
  5563. // This overloaded version can be used in Windows programs compiled in
  5564. // UNICODE mode.
  5565. void InitGoogleTest(int* argc, wchar_t** argv) {
  5566. internal::InitGoogleTestImpl(argc, argv);
  5567. }
  5568. } // namespace testing
  5569. // Copyright 2005, Google Inc.
  5570. // All rights reserved.
  5571. //
  5572. // Redistribution and use in source and binary forms, with or without
  5573. // modification, are permitted provided that the following conditions are
  5574. // met:
  5575. //
  5576. // * Redistributions of source code must retain the above copyright
  5577. // notice, this list of conditions and the following disclaimer.
  5578. // * Redistributions in binary form must reproduce the above
  5579. // copyright notice, this list of conditions and the following disclaimer
  5580. // in the documentation and/or other materials provided with the
  5581. // distribution.
  5582. // * Neither the name of Google Inc. nor the names of its
  5583. // contributors may be used to endorse or promote products derived from
  5584. // this software without specific prior written permission.
  5585. //
  5586. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  5587. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  5588. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  5589. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  5590. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  5591. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  5592. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  5593. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  5594. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  5595. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  5596. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  5597. //
  5598. // Author: wan@google.com (Zhanyong Wan), vladl@google.com (Vlad Losev)
  5599. //
  5600. // This file implements death tests.
  5601. #if GTEST_HAS_DEATH_TEST
  5602. # if GTEST_OS_MAC
  5603. # include <crt_externs.h>
  5604. # endif // GTEST_OS_MAC
  5605. # include <errno.h>
  5606. # include <fcntl.h>
  5607. # include <limits.h>
  5608. # if GTEST_OS_LINUX
  5609. # include <signal.h>
  5610. # endif // GTEST_OS_LINUX
  5611. # include <stdarg.h>
  5612. # if GTEST_OS_WINDOWS
  5613. # include <windows.h>
  5614. # else
  5615. # include <sys/mman.h>
  5616. # include <sys/wait.h>
  5617. # endif // GTEST_OS_WINDOWS
  5618. # if GTEST_OS_QNX
  5619. # include <spawn.h>
  5620. # endif // GTEST_OS_QNX
  5621. #endif // GTEST_HAS_DEATH_TEST
  5622. // Indicates that this translation unit is part of Google Test's
  5623. // implementation. It must come before gtest-internal-inl.h is
  5624. // included, or there will be a compiler error. This trick is to
  5625. // prevent a user from accidentally including gtest-internal-inl.h in
  5626. // his code.
  5627. #define GTEST_IMPLEMENTATION_ 1
  5628. #undef GTEST_IMPLEMENTATION_
  5629. namespace testing {
  5630. // Constants.
  5631. // The default death test style.
  5632. static const char kDefaultDeathTestStyle[] = "fast";
  5633. GTEST_DEFINE_string_(
  5634. death_test_style,
  5635. internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle),
  5636. "Indicates how to run a death test in a forked child process: "
  5637. "\"threadsafe\" (child process re-executes the test binary "
  5638. "from the beginning, running only the specific death test) or "
  5639. "\"fast\" (child process runs the death test immediately "
  5640. "after forking).");
  5641. GTEST_DEFINE_bool_(
  5642. death_test_use_fork,
  5643. internal::BoolFromGTestEnv("death_test_use_fork", false),
  5644. "Instructs to use fork()/_exit() instead of clone() in death tests. "
  5645. "Ignored and always uses fork() on POSIX systems where clone() is not "
  5646. "implemented. Useful when running under valgrind or similar tools if "
  5647. "those do not support clone(). Valgrind 3.3.1 will just fail if "
  5648. "it sees an unsupported combination of clone() flags. "
  5649. "It is not recommended to use this flag w/o valgrind though it will "
  5650. "work in 99% of the cases. Once valgrind is fixed, this flag will "
  5651. "most likely be removed.");
  5652. namespace internal {
  5653. GTEST_DEFINE_string_(
  5654. internal_run_death_test, "",
  5655. "Indicates the file, line number, temporal index of "
  5656. "the single death test to run, and a file descriptor to "
  5657. "which a success code may be sent, all separated by "
  5658. "the '|' characters. This flag is specified if and only if the current "
  5659. "process is a sub-process launched for running a thread-safe "
  5660. "death test. FOR INTERNAL USE ONLY.");
  5661. } // namespace internal
  5662. #if GTEST_HAS_DEATH_TEST
  5663. namespace internal {
  5664. // Valid only for fast death tests. Indicates the code is running in the
  5665. // child process of a fast style death test.
  5666. static bool g_in_fast_death_test_child = false;
  5667. // Returns a Boolean value indicating whether the caller is currently
  5668. // executing in the context of the death test child process. Tools such as
  5669. // Valgrind heap checkers may need this to modify their behavior in death
  5670. // tests. IMPORTANT: This is an internal utility. Using it may break the
  5671. // implementation of death tests. User code MUST NOT use it.
  5672. bool InDeathTestChild() {
  5673. # if GTEST_OS_WINDOWS
  5674. // On Windows, death tests are thread-safe regardless of the value of the
  5675. // death_test_style flag.
  5676. return !GTEST_FLAG(internal_run_death_test).empty();
  5677. # else
  5678. if (GTEST_FLAG(death_test_style) == "threadsafe")
  5679. return !GTEST_FLAG(internal_run_death_test).empty();
  5680. else
  5681. return g_in_fast_death_test_child;
  5682. #endif
  5683. }
  5684. } // namespace internal
  5685. // ExitedWithCode constructor.
  5686. ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {
  5687. }
  5688. // ExitedWithCode function-call operator.
  5689. bool ExitedWithCode::operator()(int exit_status) const {
  5690. # if GTEST_OS_WINDOWS
  5691. return exit_status == exit_code_;
  5692. # else
  5693. return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;
  5694. # endif // GTEST_OS_WINDOWS
  5695. }
  5696. # if !GTEST_OS_WINDOWS
  5697. // KilledBySignal constructor.
  5698. KilledBySignal::KilledBySignal(int signum) : signum_(signum) {
  5699. }
  5700. // KilledBySignal function-call operator.
  5701. bool KilledBySignal::operator()(int exit_status) const {
  5702. return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;
  5703. }
  5704. # endif // !GTEST_OS_WINDOWS
  5705. namespace internal {
  5706. // Utilities needed for death tests.
  5707. // Generates a textual description of a given exit code, in the format
  5708. // specified by wait(2).
  5709. static std::string ExitSummary(int exit_code) {
  5710. Message m;
  5711. # if GTEST_OS_WINDOWS
  5712. m << "Exited with exit status " << exit_code;
  5713. # else
  5714. if (WIFEXITED(exit_code)) {
  5715. m << "Exited with exit status " << WEXITSTATUS(exit_code);
  5716. } else if (WIFSIGNALED(exit_code)) {
  5717. m << "Terminated by signal " << WTERMSIG(exit_code);
  5718. }
  5719. # ifdef WCOREDUMP
  5720. if (WCOREDUMP(exit_code)) {
  5721. m << " (core dumped)";
  5722. }
  5723. # endif
  5724. # endif // GTEST_OS_WINDOWS
  5725. return m.GetString();
  5726. }
  5727. // Returns true if exit_status describes a process that was terminated
  5728. // by a signal, or exited normally with a nonzero exit code.
  5729. bool ExitedUnsuccessfully(int exit_status) {
  5730. return !ExitedWithCode(0)(exit_status);
  5731. }
  5732. # if !GTEST_OS_WINDOWS
  5733. // Generates a textual failure message when a death test finds more than
  5734. // one thread running, or cannot determine the number of threads, prior
  5735. // to executing the given statement. It is the responsibility of the
  5736. // caller not to pass a thread_count of 1.
  5737. static std::string DeathTestThreadWarning(size_t thread_count) {
  5738. Message msg;
  5739. msg << "Death tests use fork(), which is unsafe particularly"
  5740. << " in a threaded context. For this test, " << GTEST_NAME_ << " ";
  5741. if (thread_count == 0)
  5742. msg << "couldn't detect the number of threads.";
  5743. else
  5744. msg << "detected " << thread_count << " threads.";
  5745. return msg.GetString();
  5746. }
  5747. # endif // !GTEST_OS_WINDOWS
  5748. // Flag characters for reporting a death test that did not die.
  5749. static const char kDeathTestLived = 'L';
  5750. static const char kDeathTestReturned = 'R';
  5751. static const char kDeathTestThrew = 'T';
  5752. static const char kDeathTestInternalError = 'I';
  5753. // An enumeration describing all of the possible ways that a death test can
  5754. // conclude. DIED means that the process died while executing the test
  5755. // code; LIVED means that process lived beyond the end of the test code;
  5756. // RETURNED means that the test statement attempted to execute a return
  5757. // statement, which is not allowed; THREW means that the test statement
  5758. // returned control by throwing an exception. IN_PROGRESS means the test
  5759. // has not yet concluded.
  5760. // TODO(vladl@google.com): Unify names and possibly values for
  5761. // AbortReason, DeathTestOutcome, and flag characters above.
  5762. enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW };
  5763. // Routine for aborting the program which is safe to call from an
  5764. // exec-style death test child process, in which case the error
  5765. // message is propagated back to the parent process. Otherwise, the
  5766. // message is simply printed to stderr. In either case, the program
  5767. // then exits with status 1.
  5768. void DeathTestAbort(const std::string& message) {
  5769. // On a POSIX system, this function may be called from a threadsafe-style
  5770. // death test child process, which operates on a very small stack. Use
  5771. // the heap for any additional non-minuscule memory requirements.
  5772. const InternalRunDeathTestFlag* const flag =
  5773. GetUnitTestImpl()->internal_run_death_test_flag();
  5774. if (flag != NULL) {
  5775. FILE* parent = posix::FDOpen(flag->write_fd(), "w");
  5776. fputc(kDeathTestInternalError, parent);
  5777. fprintf(parent, "%s", message.c_str());
  5778. fflush(parent);
  5779. _exit(1);
  5780. } else {
  5781. fprintf(stderr, "%s", message.c_str());
  5782. fflush(stderr);
  5783. posix::Abort();
  5784. }
  5785. }
  5786. // A replacement for CHECK that calls DeathTestAbort if the assertion
  5787. // fails.
  5788. # define GTEST_DEATH_TEST_CHECK_(expression) \
  5789. do { \
  5790. if (!::testing::internal::IsTrue(expression)) { \
  5791. DeathTestAbort( \
  5792. ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
  5793. + ::testing::internal::StreamableToString(__LINE__) + ": " \
  5794. + #expression); \
  5795. } \
  5796. } while (::testing::internal::AlwaysFalse())
  5797. // This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for
  5798. // evaluating any system call that fulfills two conditions: it must return
  5799. // -1 on failure, and set errno to EINTR when it is interrupted and
  5800. // should be tried again. The macro expands to a loop that repeatedly
  5801. // evaluates the expression as long as it evaluates to -1 and sets
  5802. // errno to EINTR. If the expression evaluates to -1 but errno is
  5803. // something other than EINTR, DeathTestAbort is called.
  5804. # define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
  5805. do { \
  5806. int gtest_retval; \
  5807. do { \
  5808. gtest_retval = (expression); \
  5809. } while (gtest_retval == -1 && errno == EINTR); \
  5810. if (gtest_retval == -1) { \
  5811. DeathTestAbort( \
  5812. ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
  5813. + ::testing::internal::StreamableToString(__LINE__) + ": " \
  5814. + #expression + " != -1"); \
  5815. } \
  5816. } while (::testing::internal::AlwaysFalse())
  5817. // Returns the message describing the last system error in errno.
  5818. std::string GetLastErrnoDescription() {
  5819. return errno == 0 ? "" : posix::StrError(errno);
  5820. }
  5821. // This is called from a death test parent process to read a failure
  5822. // message from the death test child process and log it with the FATAL
  5823. // severity. On Windows, the message is read from a pipe handle. On other
  5824. // platforms, it is read from a file descriptor.
  5825. static void FailFromInternalError(int fd) {
  5826. Message error;
  5827. char buffer[256];
  5828. int num_read;
  5829. do {
  5830. while ((num_read = posix::Read(fd, buffer, 255)) > 0) {
  5831. buffer[num_read] = '\0';
  5832. error << buffer;
  5833. }
  5834. } while (num_read == -1 && errno == EINTR);
  5835. if (num_read == 0) {
  5836. GTEST_LOG_(FATAL) << error.GetString();
  5837. } else {
  5838. const int last_error = errno;
  5839. GTEST_LOG_(FATAL) << "Error while reading death test internal: "
  5840. << GetLastErrnoDescription() << " [" << last_error << "]";
  5841. }
  5842. }
  5843. // Death test constructor. Increments the running death test count
  5844. // for the current test.
  5845. DeathTest::DeathTest() {
  5846. TestInfo* const info = GetUnitTestImpl()->current_test_info();
  5847. if (info == NULL) {
  5848. DeathTestAbort("Cannot run a death test outside of a TEST or "
  5849. "TEST_F construct");
  5850. }
  5851. }
  5852. // Creates and returns a death test by dispatching to the current
  5853. // death test factory.
  5854. bool DeathTest::Create(const char* statement, const RE* regex,
  5855. const char* file, int line, DeathTest** test) {
  5856. return GetUnitTestImpl()->death_test_factory()->Create(
  5857. statement, regex, file, line, test);
  5858. }
  5859. const char* DeathTest::LastMessage() {
  5860. return last_death_test_message_.c_str();
  5861. }
  5862. void DeathTest::set_last_death_test_message(const std::string& message) {
  5863. last_death_test_message_ = message;
  5864. }
  5865. std::string DeathTest::last_death_test_message_;
  5866. // Provides cross platform implementation for some death functionality.
  5867. class DeathTestImpl : public DeathTest {
  5868. protected:
  5869. DeathTestImpl(const char* a_statement, const RE* a_regex)
  5870. : statement_(a_statement),
  5871. regex_(a_regex),
  5872. spawned_(false),
  5873. status_(-1),
  5874. outcome_(IN_PROGRESS),
  5875. read_fd_(-1),
  5876. write_fd_(-1) {}
  5877. // read_fd_ is expected to be closed and cleared by a derived class.
  5878. ~DeathTestImpl() { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); }
  5879. void Abort(AbortReason reason);
  5880. virtual bool Passed(bool status_ok);
  5881. const char* statement() const { return statement_; }
  5882. const RE* regex() const { return regex_; }
  5883. bool spawned() const { return spawned_; }
  5884. void set_spawned(bool is_spawned) { spawned_ = is_spawned; }
  5885. int status() const { return status_; }
  5886. void set_status(int a_status) { status_ = a_status; }
  5887. DeathTestOutcome outcome() const { return outcome_; }
  5888. void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; }
  5889. int read_fd() const { return read_fd_; }
  5890. void set_read_fd(int fd) { read_fd_ = fd; }
  5891. int write_fd() const { return write_fd_; }
  5892. void set_write_fd(int fd) { write_fd_ = fd; }
  5893. // Called in the parent process only. Reads the result code of the death
  5894. // test child process via a pipe, interprets it to set the outcome_
  5895. // member, and closes read_fd_. Outputs diagnostics and terminates in
  5896. // case of unexpected codes.
  5897. void ReadAndInterpretStatusByte();
  5898. private:
  5899. // The textual content of the code this object is testing. This class
  5900. // doesn't own this string and should not attempt to delete it.
  5901. const char* const statement_;
  5902. // The regular expression which test output must match. DeathTestImpl
  5903. // doesn't own this object and should not attempt to delete it.
  5904. const RE* const regex_;
  5905. // True if the death test child process has been successfully spawned.
  5906. bool spawned_;
  5907. // The exit status of the child process.
  5908. int status_;
  5909. // How the death test concluded.
  5910. DeathTestOutcome outcome_;
  5911. // Descriptor to the read end of the pipe to the child process. It is
  5912. // always -1 in the child process. The child keeps its write end of the
  5913. // pipe in write_fd_.
  5914. int read_fd_;
  5915. // Descriptor to the child's write end of the pipe to the parent process.
  5916. // It is always -1 in the parent process. The parent keeps its end of the
  5917. // pipe in read_fd_.
  5918. int write_fd_;
  5919. };
  5920. // Called in the parent process only. Reads the result code of the death
  5921. // test child process via a pipe, interprets it to set the outcome_
  5922. // member, and closes read_fd_. Outputs diagnostics and terminates in
  5923. // case of unexpected codes.
  5924. void DeathTestImpl::ReadAndInterpretStatusByte() {
  5925. char flag;
  5926. int bytes_read;
  5927. // The read() here blocks until data is available (signifying the
  5928. // failure of the death test) or until the pipe is closed (signifying
  5929. // its success), so it's okay to call this in the parent before
  5930. // the child process has exited.
  5931. do {
  5932. bytes_read = posix::Read(read_fd(), &flag, 1);
  5933. } while (bytes_read == -1 && errno == EINTR);
  5934. if (bytes_read == 0) {
  5935. set_outcome(DIED);
  5936. } else if (bytes_read == 1) {
  5937. switch (flag) {
  5938. case kDeathTestReturned:
  5939. set_outcome(RETURNED);
  5940. break;
  5941. case kDeathTestThrew:
  5942. set_outcome(THREW);
  5943. break;
  5944. case kDeathTestLived:
  5945. set_outcome(LIVED);
  5946. break;
  5947. case kDeathTestInternalError:
  5948. FailFromInternalError(read_fd()); // Does not return.
  5949. break;
  5950. default:
  5951. GTEST_LOG_(FATAL) << "Death test child process reported "
  5952. << "unexpected status byte ("
  5953. << static_cast<unsigned int>(flag) << ")";
  5954. }
  5955. } else {
  5956. GTEST_LOG_(FATAL) << "Read from death test child process failed: "
  5957. << GetLastErrnoDescription();
  5958. }
  5959. GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd()));
  5960. set_read_fd(-1);
  5961. }
  5962. // Signals that the death test code which should have exited, didn't.
  5963. // Should be called only in a death test child process.
  5964. // Writes a status byte to the child's status file descriptor, then
  5965. // calls _exit(1).
  5966. void DeathTestImpl::Abort(AbortReason reason) {
  5967. // The parent process considers the death test to be a failure if
  5968. // it finds any data in our pipe. So, here we write a single flag byte
  5969. // to the pipe, then exit.
  5970. const char status_ch =
  5971. reason == TEST_DID_NOT_DIE ? kDeathTestLived :
  5972. reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned;
  5973. GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1));
  5974. // We are leaking the descriptor here because on some platforms (i.e.,
  5975. // when built as Windows DLL), destructors of global objects will still
  5976. // run after calling _exit(). On such systems, write_fd_ will be
  5977. // indirectly closed from the destructor of UnitTestImpl, causing double
  5978. // close if it is also closed here. On debug configurations, double close
  5979. // may assert. As there are no in-process buffers to flush here, we are
  5980. // relying on the OS to close the descriptor after the process terminates
  5981. // when the destructors are not run.
  5982. _exit(1); // Exits w/o any normal exit hooks (we were supposed to crash)
  5983. }
  5984. // Returns an indented copy of stderr output for a death test.
  5985. // This makes distinguishing death test output lines from regular log lines
  5986. // much easier.
  5987. static ::std::string FormatDeathTestOutput(const ::std::string& output) {
  5988. ::std::string ret;
  5989. for (size_t at = 0; ; ) {
  5990. const size_t line_end = output.find('\n', at);
  5991. ret += "[ DEATH ] ";
  5992. if (line_end == ::std::string::npos) {
  5993. ret += output.substr(at);
  5994. break;
  5995. }
  5996. ret += output.substr(at, line_end + 1 - at);
  5997. at = line_end + 1;
  5998. }
  5999. return ret;
  6000. }
  6001. // Assesses the success or failure of a death test, using both private
  6002. // members which have previously been set, and one argument:
  6003. //
  6004. // Private data members:
  6005. // outcome: An enumeration describing how the death test
  6006. // concluded: DIED, LIVED, THREW, or RETURNED. The death test
  6007. // fails in the latter three cases.
  6008. // status: The exit status of the child process. On *nix, it is in the
  6009. // in the format specified by wait(2). On Windows, this is the
  6010. // value supplied to the ExitProcess() API or a numeric code
  6011. // of the exception that terminated the program.
  6012. // regex: A regular expression object to be applied to
  6013. // the test's captured standard error output; the death test
  6014. // fails if it does not match.
  6015. //
  6016. // Argument:
  6017. // status_ok: true if exit_status is acceptable in the context of
  6018. // this particular death test, which fails if it is false
  6019. //
  6020. // Returns true iff all of the above conditions are met. Otherwise, the
  6021. // first failing condition, in the order given above, is the one that is
  6022. // reported. Also sets the last death test message string.
  6023. bool DeathTestImpl::Passed(bool status_ok) {
  6024. if (!spawned())
  6025. return false;
  6026. const std::string error_message = GetCapturedStderr();
  6027. bool success = false;
  6028. Message buffer;
  6029. buffer << "Death test: " << statement() << "\n";
  6030. switch (outcome()) {
  6031. case LIVED:
  6032. buffer << " Result: failed to die.\n"
  6033. << " Error msg:\n" << FormatDeathTestOutput(error_message);
  6034. break;
  6035. case THREW:
  6036. buffer << " Result: threw an exception.\n"
  6037. << " Error msg:\n" << FormatDeathTestOutput(error_message);
  6038. break;
  6039. case RETURNED:
  6040. buffer << " Result: illegal return in test statement.\n"
  6041. << " Error msg:\n" << FormatDeathTestOutput(error_message);
  6042. break;
  6043. case DIED:
  6044. if (status_ok) {
  6045. const bool matched = RE::PartialMatch(error_message.c_str(), *regex());
  6046. if (matched) {
  6047. success = true;
  6048. } else {
  6049. buffer << " Result: died but not with expected error.\n"
  6050. << " Expected: " << regex()->pattern() << "\n"
  6051. << "Actual msg:\n" << FormatDeathTestOutput(error_message);
  6052. }
  6053. } else {
  6054. buffer << " Result: died but not with expected exit code:\n"
  6055. << " " << ExitSummary(status()) << "\n"
  6056. << "Actual msg:\n" << FormatDeathTestOutput(error_message);
  6057. }
  6058. break;
  6059. case IN_PROGRESS:
  6060. default:
  6061. GTEST_LOG_(FATAL)
  6062. << "DeathTest::Passed somehow called before conclusion of test";
  6063. }
  6064. DeathTest::set_last_death_test_message(buffer.GetString());
  6065. return success;
  6066. }
  6067. # if GTEST_OS_WINDOWS
  6068. // WindowsDeathTest implements death tests on Windows. Due to the
  6069. // specifics of starting new processes on Windows, death tests there are
  6070. // always threadsafe, and Google Test considers the
  6071. // --gtest_death_test_style=fast setting to be equivalent to
  6072. // --gtest_death_test_style=threadsafe there.
  6073. //
  6074. // A few implementation notes: Like the Linux version, the Windows
  6075. // implementation uses pipes for child-to-parent communication. But due to
  6076. // the specifics of pipes on Windows, some extra steps are required:
  6077. //
  6078. // 1. The parent creates a communication pipe and stores handles to both
  6079. // ends of it.
  6080. // 2. The parent starts the child and provides it with the information
  6081. // necessary to acquire the handle to the write end of the pipe.
  6082. // 3. The child acquires the write end of the pipe and signals the parent
  6083. // using a Windows event.
  6084. // 4. Now the parent can release the write end of the pipe on its side. If
  6085. // this is done before step 3, the object's reference count goes down to
  6086. // 0 and it is destroyed, preventing the child from acquiring it. The
  6087. // parent now has to release it, or read operations on the read end of
  6088. // the pipe will not return when the child terminates.
  6089. // 5. The parent reads child's output through the pipe (outcome code and
  6090. // any possible error messages) from the pipe, and its stderr and then
  6091. // determines whether to fail the test.
  6092. //
  6093. // Note: to distinguish Win32 API calls from the local method and function
  6094. // calls, the former are explicitly resolved in the global namespace.
  6095. //
  6096. class WindowsDeathTest : public DeathTestImpl {
  6097. public:
  6098. WindowsDeathTest(const char* a_statement,
  6099. const RE* a_regex,
  6100. const char* file,
  6101. int line)
  6102. : DeathTestImpl(a_statement, a_regex), file_(file), line_(line) {}
  6103. // All of these virtual functions are inherited from DeathTest.
  6104. virtual int Wait();
  6105. virtual TestRole AssumeRole();
  6106. private:
  6107. // The name of the file in which the death test is located.
  6108. const char* const file_;
  6109. // The line number on which the death test is located.
  6110. const int line_;
  6111. // Handle to the write end of the pipe to the child process.
  6112. AutoHandle write_handle_;
  6113. // Child process handle.
  6114. AutoHandle child_handle_;
  6115. // Event the child process uses to signal the parent that it has
  6116. // acquired the handle to the write end of the pipe. After seeing this
  6117. // event the parent can release its own handles to make sure its
  6118. // ReadFile() calls return when the child terminates.
  6119. AutoHandle event_handle_;
  6120. };
  6121. // Waits for the child in a death test to exit, returning its exit
  6122. // status, or 0 if no child process exists. As a side effect, sets the
  6123. // outcome data member.
  6124. int WindowsDeathTest::Wait() {
  6125. if (!spawned())
  6126. return 0;
  6127. // Wait until the child either signals that it has acquired the write end
  6128. // of the pipe or it dies.
  6129. const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() };
  6130. switch (::WaitForMultipleObjects(2,
  6131. wait_handles,
  6132. FALSE, // Waits for any of the handles.
  6133. INFINITE)) {
  6134. case WAIT_OBJECT_0:
  6135. case WAIT_OBJECT_0 + 1:
  6136. break;
  6137. default:
  6138. GTEST_DEATH_TEST_CHECK_(false); // Should not get here.
  6139. }
  6140. // The child has acquired the write end of the pipe or exited.
  6141. // We release the handle on our side and continue.
  6142. write_handle_.Reset();
  6143. event_handle_.Reset();
  6144. ReadAndInterpretStatusByte();
  6145. // Waits for the child process to exit if it haven't already. This
  6146. // returns immediately if the child has already exited, regardless of
  6147. // whether previous calls to WaitForMultipleObjects synchronized on this
  6148. // handle or not.
  6149. GTEST_DEATH_TEST_CHECK_(
  6150. WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(),
  6151. INFINITE));
  6152. DWORD status_code;
  6153. GTEST_DEATH_TEST_CHECK_(
  6154. ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE);
  6155. child_handle_.Reset();
  6156. set_status(static_cast<int>(status_code));
  6157. return status();
  6158. }
  6159. // The AssumeRole process for a Windows death test. It creates a child
  6160. // process with the same executable as the current process to run the
  6161. // death test. The child process is given the --gtest_filter and
  6162. // --gtest_internal_run_death_test flags such that it knows to run the
  6163. // current death test only.
  6164. DeathTest::TestRole WindowsDeathTest::AssumeRole() {
  6165. const UnitTestImpl* const impl = GetUnitTestImpl();
  6166. const InternalRunDeathTestFlag* const flag =
  6167. impl->internal_run_death_test_flag();
  6168. const TestInfo* const info = impl->current_test_info();
  6169. const int death_test_index = info->result()->death_test_count();
  6170. if (flag != NULL) {
  6171. // ParseInternalRunDeathTestFlag() has performed all the necessary
  6172. // processing.
  6173. set_write_fd(flag->write_fd());
  6174. return EXECUTE_TEST;
  6175. }
  6176. // WindowsDeathTest uses an anonymous pipe to communicate results of
  6177. // a death test.
  6178. SECURITY_ATTRIBUTES handles_are_inheritable = {
  6179. sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };
  6180. HANDLE read_handle, write_handle;
  6181. GTEST_DEATH_TEST_CHECK_(
  6182. ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable,
  6183. 0) // Default buffer size.
  6184. != FALSE);
  6185. set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle),
  6186. O_RDONLY));
  6187. write_handle_.Reset(write_handle);
  6188. event_handle_.Reset(::CreateEvent(
  6189. &handles_are_inheritable,
  6190. TRUE, // The event will automatically reset to non-signaled state.
  6191. FALSE, // The initial state is non-signalled.
  6192. NULL)); // The even is unnamed.
  6193. GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL);
  6194. const std::string filter_flag =
  6195. std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "=" +
  6196. info->test_case_name() + "." + info->name();
  6197. const std::string internal_flag =
  6198. std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag +
  6199. "=" + file_ + "|" + StreamableToString(line_) + "|" +
  6200. StreamableToString(death_test_index) + "|" +
  6201. StreamableToString(static_cast<unsigned int>(::GetCurrentProcessId())) +
  6202. // size_t has the same width as pointers on both 32-bit and 64-bit
  6203. // Windows platforms.
  6204. // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx.
  6205. "|" + StreamableToString(reinterpret_cast<size_t>(write_handle)) +
  6206. "|" + StreamableToString(reinterpret_cast<size_t>(event_handle_.Get()));
  6207. char executable_path[_MAX_PATH + 1]; // NOLINT
  6208. GTEST_DEATH_TEST_CHECK_(
  6209. _MAX_PATH + 1 != ::GetModuleFileNameA(NULL,
  6210. executable_path,
  6211. _MAX_PATH));
  6212. std::string command_line =
  6213. std::string(::GetCommandLineA()) + " " + filter_flag + " \"" +
  6214. internal_flag + "\"";
  6215. DeathTest::set_last_death_test_message("");
  6216. CaptureStderr();
  6217. // Flush the log buffers since the log streams are shared with the child.
  6218. FlushInfoLog();
  6219. // The child process will share the standard handles with the parent.
  6220. STARTUPINFOA startup_info;
  6221. memset(&startup_info, 0, sizeof(STARTUPINFO));
  6222. startup_info.dwFlags = STARTF_USESTDHANDLES;
  6223. startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE);
  6224. startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE);
  6225. startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE);
  6226. PROCESS_INFORMATION process_info;
  6227. GTEST_DEATH_TEST_CHECK_(::CreateProcessA(
  6228. executable_path,
  6229. const_cast<char*>(command_line.c_str()),
  6230. NULL, // Retuned process handle is not inheritable.
  6231. NULL, // Retuned thread handle is not inheritable.
  6232. TRUE, // Child inherits all inheritable handles (for write_handle_).
  6233. 0x0, // Default creation flags.
  6234. NULL, // Inherit the parent's environment.
  6235. UnitTest::GetInstance()->original_working_dir(),
  6236. &startup_info,
  6237. &process_info) != FALSE);
  6238. child_handle_.Reset(process_info.hProcess);
  6239. ::CloseHandle(process_info.hThread);
  6240. set_spawned(true);
  6241. return OVERSEE_TEST;
  6242. }
  6243. # else // We are not on Windows.
  6244. // ForkingDeathTest provides implementations for most of the abstract
  6245. // methods of the DeathTest interface. Only the AssumeRole method is
  6246. // left undefined.
  6247. class ForkingDeathTest : public DeathTestImpl {
  6248. public:
  6249. ForkingDeathTest(const char* statement, const RE* regex);
  6250. // All of these virtual functions are inherited from DeathTest.
  6251. virtual int Wait();
  6252. protected:
  6253. void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; }
  6254. private:
  6255. // PID of child process during death test; 0 in the child process itself.
  6256. pid_t child_pid_;
  6257. };
  6258. // Constructs a ForkingDeathTest.
  6259. ForkingDeathTest::ForkingDeathTest(const char* a_statement, const RE* a_regex)
  6260. : DeathTestImpl(a_statement, a_regex),
  6261. child_pid_(-1) {}
  6262. // Waits for the child in a death test to exit, returning its exit
  6263. // status, or 0 if no child process exists. As a side effect, sets the
  6264. // outcome data member.
  6265. int ForkingDeathTest::Wait() {
  6266. if (!spawned())
  6267. return 0;
  6268. ReadAndInterpretStatusByte();
  6269. int status_value;
  6270. GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0));
  6271. set_status(status_value);
  6272. return status_value;
  6273. }
  6274. // A concrete death test class that forks, then immediately runs the test
  6275. // in the child process.
  6276. class NoExecDeathTest : public ForkingDeathTest {
  6277. public:
  6278. NoExecDeathTest(const char* a_statement, const RE* a_regex) :
  6279. ForkingDeathTest(a_statement, a_regex) { }
  6280. virtual TestRole AssumeRole();
  6281. };
  6282. // The AssumeRole process for a fork-and-run death test. It implements a
  6283. // straightforward fork, with a simple pipe to transmit the status byte.
  6284. DeathTest::TestRole NoExecDeathTest::AssumeRole() {
  6285. const size_t thread_count = GetThreadCount();
  6286. if (thread_count != 1) {
  6287. GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count);
  6288. }
  6289. int pipe_fd[2];
  6290. GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
  6291. DeathTest::set_last_death_test_message("");
  6292. CaptureStderr();
  6293. // When we fork the process below, the log file buffers are copied, but the
  6294. // file descriptors are shared. We flush all log files here so that closing
  6295. // the file descriptors in the child process doesn't throw off the
  6296. // synchronization between descriptors and buffers in the parent process.
  6297. // This is as close to the fork as possible to avoid a race condition in case
  6298. // there are multiple threads running before the death test, and another
  6299. // thread writes to the log file.
  6300. FlushInfoLog();
  6301. const pid_t child_pid = fork();
  6302. GTEST_DEATH_TEST_CHECK_(child_pid != -1);
  6303. set_child_pid(child_pid);
  6304. if (child_pid == 0) {
  6305. GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0]));
  6306. set_write_fd(pipe_fd[1]);
  6307. // Redirects all logging to stderr in the child process to prevent
  6308. // concurrent writes to the log files. We capture stderr in the parent
  6309. // process and append the child process' output to a log.
  6310. LogToStderr();
  6311. // Event forwarding to the listeners of event listener API mush be shut
  6312. // down in death test subprocesses.
  6313. GetUnitTestImpl()->listeners()->SuppressEventForwarding();
  6314. g_in_fast_death_test_child = true;
  6315. return EXECUTE_TEST;
  6316. } else {
  6317. GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
  6318. set_read_fd(pipe_fd[0]);
  6319. set_spawned(true);
  6320. return OVERSEE_TEST;
  6321. }
  6322. }
  6323. // A concrete death test class that forks and re-executes the main
  6324. // program from the beginning, with command-line flags set that cause
  6325. // only this specific death test to be run.
  6326. class ExecDeathTest : public ForkingDeathTest {
  6327. public:
  6328. ExecDeathTest(const char* a_statement, const RE* a_regex,
  6329. const char* file, int line) :
  6330. ForkingDeathTest(a_statement, a_regex), file_(file), line_(line) { }
  6331. virtual TestRole AssumeRole();
  6332. private:
  6333. static ::std::vector<testing::internal::string>
  6334. GetArgvsForDeathTestChildProcess() {
  6335. ::std::vector<testing::internal::string> args = GetInjectableArgvs();
  6336. return args;
  6337. }
  6338. // The name of the file in which the death test is located.
  6339. const char* const file_;
  6340. // The line number on which the death test is located.
  6341. const int line_;
  6342. };
  6343. // Utility class for accumulating command-line arguments.
  6344. class Arguments {
  6345. public:
  6346. Arguments() {
  6347. args_.push_back(NULL);
  6348. }
  6349. ~Arguments() {
  6350. for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
  6351. ++i) {
  6352. free(*i);
  6353. }
  6354. }
  6355. void AddArgument(const char* argument) {
  6356. args_.insert(args_.end() - 1, posix::StrDup(argument));
  6357. }
  6358. template <typename Str>
  6359. void AddArguments(const ::std::vector<Str>& arguments) {
  6360. for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
  6361. i != arguments.end();
  6362. ++i) {
  6363. args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
  6364. }
  6365. }
  6366. char* const* Argv() {
  6367. return &args_[0];
  6368. }
  6369. private:
  6370. std::vector<char*> args_;
  6371. };
  6372. // A struct that encompasses the arguments to the child process of a
  6373. // threadsafe-style death test process.
  6374. struct ExecDeathTestArgs {
  6375. char* const* argv; // Command-line arguments for the child's call to exec
  6376. int close_fd; // File descriptor to close; the read end of a pipe
  6377. };
  6378. # if GTEST_OS_MAC
  6379. inline char** GetEnviron() {
  6380. // When Google Test is built as a framework on MacOS X, the environ variable
  6381. // is unavailable. Apple's documentation (man environ) recommends using
  6382. // _NSGetEnviron() instead.
  6383. return *_NSGetEnviron();
  6384. }
  6385. # else
  6386. // Some POSIX platforms expect you to declare environ. extern "C" makes
  6387. // it reside in the global namespace.
  6388. extern "C" char** environ;
  6389. inline char** GetEnviron() { return environ; }
  6390. # endif // GTEST_OS_MAC
  6391. # if !GTEST_OS_QNX
  6392. // The main function for a threadsafe-style death test child process.
  6393. // This function is called in a clone()-ed process and thus must avoid
  6394. // any potentially unsafe operations like malloc or libc functions.
  6395. static int ExecDeathTestChildMain(void* child_arg) {
  6396. ExecDeathTestArgs* const args = static_cast<ExecDeathTestArgs*>(child_arg);
  6397. GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd));
  6398. // We need to execute the test program in the same environment where
  6399. // it was originally invoked. Therefore we change to the original
  6400. // working directory first.
  6401. const char* const original_dir =
  6402. UnitTest::GetInstance()->original_working_dir();
  6403. // We can safely call chdir() as it's a direct system call.
  6404. if (chdir(original_dir) != 0) {
  6405. DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
  6406. GetLastErrnoDescription());
  6407. return EXIT_FAILURE;
  6408. }
  6409. // We can safely call execve() as it's a direct system call. We
  6410. // cannot use execvp() as it's a libc function and thus potentially
  6411. // unsafe. Since execve() doesn't search the PATH, the user must
  6412. // invoke the test program via a valid path that contains at least
  6413. // one path separator.
  6414. execve(args->argv[0], args->argv, GetEnviron());
  6415. DeathTestAbort(std::string("execve(") + args->argv[0] + ", ...) in " +
  6416. original_dir + " failed: " +
  6417. GetLastErrnoDescription());
  6418. return EXIT_FAILURE;
  6419. }
  6420. # endif // !GTEST_OS_QNX
  6421. // Two utility routines that together determine the direction the stack
  6422. // grows.
  6423. // This could be accomplished more elegantly by a single recursive
  6424. // function, but we want to guard against the unlikely possibility of
  6425. // a smart compiler optimizing the recursion away.
  6426. //
  6427. // GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining
  6428. // StackLowerThanAddress into StackGrowsDown, which then doesn't give
  6429. // correct answer.
  6430. void StackLowerThanAddress(const void* ptr, bool* result) GTEST_NO_INLINE_;
  6431. void StackLowerThanAddress(const void* ptr, bool* result) {
  6432. int dummy;
  6433. *result = (&dummy < ptr);
  6434. }
  6435. bool StackGrowsDown() {
  6436. int dummy;
  6437. bool result;
  6438. StackLowerThanAddress(&dummy, &result);
  6439. return result;
  6440. }
  6441. // Spawns a child process with the same executable as the current process in
  6442. // a thread-safe manner and instructs it to run the death test. The
  6443. // implementation uses fork(2) + exec. On systems where clone(2) is
  6444. // available, it is used instead, being slightly more thread-safe. On QNX,
  6445. // fork supports only single-threaded environments, so this function uses
  6446. // spawn(2) there instead. The function dies with an error message if
  6447. // anything goes wrong.
  6448. static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
  6449. ExecDeathTestArgs args = { argv, close_fd };
  6450. pid_t child_pid = -1;
  6451. # if GTEST_OS_QNX
  6452. // Obtains the current directory and sets it to be closed in the child
  6453. // process.
  6454. const int cwd_fd = open(".", O_RDONLY);
  6455. GTEST_DEATH_TEST_CHECK_(cwd_fd != -1);
  6456. GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC));
  6457. // We need to execute the test program in the same environment where
  6458. // it was originally invoked. Therefore we change to the original
  6459. // working directory first.
  6460. const char* const original_dir =
  6461. UnitTest::GetInstance()->original_working_dir();
  6462. // We can safely call chdir() as it's a direct system call.
  6463. if (chdir(original_dir) != 0) {
  6464. DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
  6465. GetLastErrnoDescription());
  6466. return EXIT_FAILURE;
  6467. }
  6468. int fd_flags;
  6469. // Set close_fd to be closed after spawn.
  6470. GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD));
  6471. GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD,
  6472. fd_flags | FD_CLOEXEC));
  6473. struct inheritance inherit = {0};
  6474. // spawn is a system call.
  6475. child_pid = spawn(args.argv[0], 0, NULL, &inherit, args.argv, GetEnviron());
  6476. // Restores the current working directory.
  6477. GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1);
  6478. GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));
  6479. # else // GTEST_OS_QNX
  6480. # if GTEST_OS_LINUX
  6481. // When a SIGPROF signal is received while fork() or clone() are executing,
  6482. // the process may hang. To avoid this, we ignore SIGPROF here and re-enable
  6483. // it after the call to fork()/clone() is complete.
  6484. struct sigaction saved_sigprof_action;
  6485. struct sigaction ignore_sigprof_action;
  6486. memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action));
  6487. sigemptyset(&ignore_sigprof_action.sa_mask);
  6488. ignore_sigprof_action.sa_handler = SIG_IGN;
  6489. GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction(
  6490. SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));
  6491. # endif // GTEST_OS_LINUX
  6492. # if GTEST_HAS_CLONE
  6493. const bool use_fork = GTEST_FLAG(death_test_use_fork);
  6494. if (!use_fork) {
  6495. static const bool stack_grows_down = StackGrowsDown();
  6496. const size_t stack_size = getpagesize();
  6497. // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead.
  6498. void* const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE,
  6499. MAP_ANON | MAP_PRIVATE, -1, 0);
  6500. GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED);
  6501. // Maximum stack alignment in bytes: For a downward-growing stack, this
  6502. // amount is subtracted from size of the stack space to get an address
  6503. // that is within the stack space and is aligned on all systems we care
  6504. // about. As far as I know there is no ABI with stack alignment greater
  6505. // than 64. We assume stack and stack_size already have alignment of
  6506. // kMaxStackAlignment.
  6507. const size_t kMaxStackAlignment = 64;
  6508. void* const stack_top =
  6509. static_cast<char*>(stack) +
  6510. (stack_grows_down ? stack_size - kMaxStackAlignment : 0);
  6511. GTEST_DEATH_TEST_CHECK_(stack_size > kMaxStackAlignment &&
  6512. reinterpret_cast<intptr_t>(stack_top) % kMaxStackAlignment == 0);
  6513. child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args);
  6514. GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);
  6515. }
  6516. # else
  6517. const bool use_fork = true;
  6518. # endif // GTEST_HAS_CLONE
  6519. if (use_fork && (child_pid = fork()) == 0) {
  6520. ExecDeathTestChildMain(&args);
  6521. _exit(0);
  6522. }
  6523. # endif // GTEST_OS_QNX
  6524. # if GTEST_OS_LINUX
  6525. GTEST_DEATH_TEST_CHECK_SYSCALL_(
  6526. sigaction(SIGPROF, &saved_sigprof_action, NULL));
  6527. # endif // GTEST_OS_LINUX
  6528. GTEST_DEATH_TEST_CHECK_(child_pid != -1);
  6529. return child_pid;
  6530. }
  6531. // The AssumeRole process for a fork-and-exec death test. It re-executes the
  6532. // main program from the beginning, setting the --gtest_filter
  6533. // and --gtest_internal_run_death_test flags to cause only the current
  6534. // death test to be re-run.
  6535. DeathTest::TestRole ExecDeathTest::AssumeRole() {
  6536. const UnitTestImpl* const impl = GetUnitTestImpl();
  6537. const InternalRunDeathTestFlag* const flag =
  6538. impl->internal_run_death_test_flag();
  6539. const TestInfo* const info = impl->current_test_info();
  6540. const int death_test_index = info->result()->death_test_count();
  6541. if (flag != NULL) {
  6542. set_write_fd(flag->write_fd());
  6543. return EXECUTE_TEST;
  6544. }
  6545. int pipe_fd[2];
  6546. GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
  6547. // Clear the close-on-exec flag on the write end of the pipe, lest
  6548. // it be closed when the child process does an exec:
  6549. GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
  6550. const std::string filter_flag =
  6551. std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "="
  6552. + info->test_case_name() + "." + info->name();
  6553. const std::string internal_flag =
  6554. std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "="
  6555. + file_ + "|" + StreamableToString(line_) + "|"
  6556. + StreamableToString(death_test_index) + "|"
  6557. + StreamableToString(pipe_fd[1]);
  6558. Arguments args;
  6559. args.AddArguments(GetArgvsForDeathTestChildProcess());
  6560. args.AddArgument(filter_flag.c_str());
  6561. args.AddArgument(internal_flag.c_str());
  6562. DeathTest::set_last_death_test_message("");
  6563. CaptureStderr();
  6564. // See the comment in NoExecDeathTest::AssumeRole for why the next line
  6565. // is necessary.
  6566. FlushInfoLog();
  6567. const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]);
  6568. GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
  6569. set_child_pid(child_pid);
  6570. set_read_fd(pipe_fd[0]);
  6571. set_spawned(true);
  6572. return OVERSEE_TEST;
  6573. }
  6574. # endif // !GTEST_OS_WINDOWS
  6575. // Creates a concrete DeathTest-derived class that depends on the
  6576. // --gtest_death_test_style flag, and sets the pointer pointed to
  6577. // by the "test" argument to its address. If the test should be
  6578. // skipped, sets that pointer to NULL. Returns true, unless the
  6579. // flag is set to an invalid value.
  6580. bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex,
  6581. const char* file, int line,
  6582. DeathTest** test) {
  6583. UnitTestImpl* const impl = GetUnitTestImpl();
  6584. const InternalRunDeathTestFlag* const flag =
  6585. impl->internal_run_death_test_flag();
  6586. const int death_test_index = impl->current_test_info()
  6587. ->increment_death_test_count();
  6588. if (flag != NULL) {
  6589. if (death_test_index > flag->index()) {
  6590. DeathTest::set_last_death_test_message(
  6591. "Death test count (" + StreamableToString(death_test_index)
  6592. + ") somehow exceeded expected maximum ("
  6593. + StreamableToString(flag->index()) + ")");
  6594. return false;
  6595. }
  6596. if (!(flag->file() == file && flag->line() == line &&
  6597. flag->index() == death_test_index)) {
  6598. *test = NULL;
  6599. return true;
  6600. }
  6601. }
  6602. # if GTEST_OS_WINDOWS
  6603. if (GTEST_FLAG(death_test_style) == "threadsafe" ||
  6604. GTEST_FLAG(death_test_style) == "fast") {
  6605. *test = new WindowsDeathTest(statement, regex, file, line);
  6606. }
  6607. # else
  6608. if (GTEST_FLAG(death_test_style) == "threadsafe") {
  6609. *test = new ExecDeathTest(statement, regex, file, line);
  6610. } else if (GTEST_FLAG(death_test_style) == "fast") {
  6611. *test = new NoExecDeathTest(statement, regex);
  6612. }
  6613. # endif // GTEST_OS_WINDOWS
  6614. else { // NOLINT - this is more readable than unbalanced brackets inside #if.
  6615. DeathTest::set_last_death_test_message(
  6616. "Unknown death test style \"" + GTEST_FLAG(death_test_style)
  6617. + "\" encountered");
  6618. return false;
  6619. }
  6620. return true;
  6621. }
  6622. // Splits a given string on a given delimiter, populating a given
  6623. // vector with the fields. GTEST_HAS_DEATH_TEST implies that we have
  6624. // ::std::string, so we can use it here.
  6625. static void SplitString(const ::std::string& str, char delimiter,
  6626. ::std::vector< ::std::string>* dest) {
  6627. ::std::vector< ::std::string> parsed;
  6628. ::std::string::size_type pos = 0;
  6629. while (::testing::internal::AlwaysTrue()) {
  6630. const ::std::string::size_type colon = str.find(delimiter, pos);
  6631. if (colon == ::std::string::npos) {
  6632. parsed.push_back(str.substr(pos));
  6633. break;
  6634. } else {
  6635. parsed.push_back(str.substr(pos, colon - pos));
  6636. pos = colon + 1;
  6637. }
  6638. }
  6639. dest->swap(parsed);
  6640. }
  6641. # if GTEST_OS_WINDOWS
  6642. // Recreates the pipe and event handles from the provided parameters,
  6643. // signals the event, and returns a file descriptor wrapped around the pipe
  6644. // handle. This function is called in the child process only.
  6645. int GetStatusFileDescriptor(unsigned int parent_process_id,
  6646. size_t write_handle_as_size_t,
  6647. size_t event_handle_as_size_t) {
  6648. AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,
  6649. FALSE, // Non-inheritable.
  6650. parent_process_id));
  6651. if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {
  6652. DeathTestAbort("Unable to open parent process " +
  6653. StreamableToString(parent_process_id));
  6654. }
  6655. // TODO(vladl@google.com): Replace the following check with a
  6656. // compile-time assertion when available.
  6657. GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t));
  6658. const HANDLE write_handle =
  6659. reinterpret_cast<HANDLE>(write_handle_as_size_t);
  6660. HANDLE dup_write_handle;
  6661. // The newly initialized handle is accessible only in in the parent
  6662. // process. To obtain one accessible within the child, we need to use
  6663. // DuplicateHandle.
  6664. if (!::DuplicateHandle(parent_process_handle.Get(), write_handle,
  6665. ::GetCurrentProcess(), &dup_write_handle,
  6666. 0x0, // Requested privileges ignored since
  6667. // DUPLICATE_SAME_ACCESS is used.
  6668. FALSE, // Request non-inheritable handler.
  6669. DUPLICATE_SAME_ACCESS)) {
  6670. DeathTestAbort("Unable to duplicate the pipe handle " +
  6671. StreamableToString(write_handle_as_size_t) +
  6672. " from the parent process " +
  6673. StreamableToString(parent_process_id));
  6674. }
  6675. const HANDLE event_handle = reinterpret_cast<HANDLE>(event_handle_as_size_t);
  6676. HANDLE dup_event_handle;
  6677. if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,
  6678. ::GetCurrentProcess(), &dup_event_handle,
  6679. 0x0,
  6680. FALSE,
  6681. DUPLICATE_SAME_ACCESS)) {
  6682. DeathTestAbort("Unable to duplicate the event handle " +
  6683. StreamableToString(event_handle_as_size_t) +
  6684. " from the parent process " +
  6685. StreamableToString(parent_process_id));
  6686. }
  6687. const int write_fd =
  6688. ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND);
  6689. if (write_fd == -1) {
  6690. DeathTestAbort("Unable to convert pipe handle " +
  6691. StreamableToString(write_handle_as_size_t) +
  6692. " to a file descriptor");
  6693. }
  6694. // Signals the parent that the write end of the pipe has been acquired
  6695. // so the parent can release its own write end.
  6696. ::SetEvent(dup_event_handle);
  6697. return write_fd;
  6698. }
  6699. # endif // GTEST_OS_WINDOWS
  6700. // Returns a newly created InternalRunDeathTestFlag object with fields
  6701. // initialized from the GTEST_FLAG(internal_run_death_test) flag if
  6702. // the flag is specified; otherwise returns NULL.
  6703. InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
  6704. if (GTEST_FLAG(internal_run_death_test) == "") return NULL;
  6705. // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we
  6706. // can use it here.
  6707. int line = -1;
  6708. int index = -1;
  6709. ::std::vector< ::std::string> fields;
  6710. SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields);
  6711. int write_fd = -1;
  6712. # if GTEST_OS_WINDOWS
  6713. unsigned int parent_process_id = 0;
  6714. size_t write_handle_as_size_t = 0;
  6715. size_t event_handle_as_size_t = 0;
  6716. if (fields.size() != 6
  6717. || !ParseNaturalNumber(fields[1], &line)
  6718. || !ParseNaturalNumber(fields[2], &index)
  6719. || !ParseNaturalNumber(fields[3], &parent_process_id)
  6720. || !ParseNaturalNumber(fields[4], &write_handle_as_size_t)
  6721. || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
  6722. DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
  6723. GTEST_FLAG(internal_run_death_test));
  6724. }
  6725. write_fd = GetStatusFileDescriptor(parent_process_id,
  6726. write_handle_as_size_t,
  6727. event_handle_as_size_t);
  6728. # else
  6729. if (fields.size() != 4
  6730. || !ParseNaturalNumber(fields[1], &line)
  6731. || !ParseNaturalNumber(fields[2], &index)
  6732. || !ParseNaturalNumber(fields[3], &write_fd)) {
  6733. DeathTestAbort("Bad --gtest_internal_run_death_test flag: "
  6734. + GTEST_FLAG(internal_run_death_test));
  6735. }
  6736. # endif // GTEST_OS_WINDOWS
  6737. return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);
  6738. }
  6739. } // namespace internal
  6740. #endif // GTEST_HAS_DEATH_TEST
  6741. } // namespace testing
  6742. // Copyright 2008, Google Inc.
  6743. // All rights reserved.
  6744. //
  6745. // Redistribution and use in source and binary forms, with or without
  6746. // modification, are permitted provided that the following conditions are
  6747. // met:
  6748. //
  6749. // * Redistributions of source code must retain the above copyright
  6750. // notice, this list of conditions and the following disclaimer.
  6751. // * Redistributions in binary form must reproduce the above
  6752. // copyright notice, this list of conditions and the following disclaimer
  6753. // in the documentation and/or other materials provided with the
  6754. // distribution.
  6755. // * Neither the name of Google Inc. nor the names of its
  6756. // contributors may be used to endorse or promote products derived from
  6757. // this software without specific prior written permission.
  6758. //
  6759. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  6760. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  6761. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  6762. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  6763. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  6764. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  6765. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  6766. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  6767. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  6768. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  6769. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  6770. //
  6771. // Authors: keith.ray@gmail.com (Keith Ray)
  6772. #include <stdlib.h>
  6773. #if GTEST_OS_WINDOWS_MOBILE
  6774. # include <windows.h>
  6775. #elif GTEST_OS_WINDOWS
  6776. # include <direct.h>
  6777. # include <io.h>
  6778. #elif GTEST_OS_SYMBIAN
  6779. // Symbian OpenC has PATH_MAX in sys/syslimits.h
  6780. # include <sys/syslimits.h>
  6781. #else
  6782. # include <limits.h>
  6783. # include <climits> // Some Linux distributions define PATH_MAX here.
  6784. #endif // GTEST_OS_WINDOWS_MOBILE
  6785. #if GTEST_OS_WINDOWS
  6786. # define GTEST_PATH_MAX_ _MAX_PATH
  6787. #elif defined(PATH_MAX)
  6788. # define GTEST_PATH_MAX_ PATH_MAX
  6789. #elif defined(_XOPEN_PATH_MAX)
  6790. # define GTEST_PATH_MAX_ _XOPEN_PATH_MAX
  6791. #else
  6792. # define GTEST_PATH_MAX_ _POSIX_PATH_MAX
  6793. #endif // GTEST_OS_WINDOWS
  6794. namespace testing {
  6795. namespace internal {
  6796. #if GTEST_OS_WINDOWS
  6797. // On Windows, '\\' is the standard path separator, but many tools and the
  6798. // Windows API also accept '/' as an alternate path separator. Unless otherwise
  6799. // noted, a file path can contain either kind of path separators, or a mixture
  6800. // of them.
  6801. const char kPathSeparator = '\\';
  6802. const char kAlternatePathSeparator = '/';
  6803. const char kPathSeparatorString[] = "\\";
  6804. const char kAlternatePathSeparatorString[] = "/";
  6805. # if GTEST_OS_WINDOWS_MOBILE
  6806. // Windows CE doesn't have a current directory. You should not use
  6807. // the current directory in tests on Windows CE, but this at least
  6808. // provides a reasonable fallback.
  6809. const char kCurrentDirectoryString[] = "\\";
  6810. // Windows CE doesn't define INVALID_FILE_ATTRIBUTES
  6811. const DWORD kInvalidFileAttributes = 0xffffffff;
  6812. # else
  6813. const char kCurrentDirectoryString[] = ".\\";
  6814. # endif // GTEST_OS_WINDOWS_MOBILE
  6815. #else
  6816. const char kPathSeparator = '/';
  6817. const char kPathSeparatorString[] = "/";
  6818. const char kCurrentDirectoryString[] = "./";
  6819. #endif // GTEST_OS_WINDOWS
  6820. // Returns whether the given character is a valid path separator.
  6821. static bool IsPathSeparator(char c) {
  6822. #if GTEST_HAS_ALT_PATH_SEP_
  6823. return (c == kPathSeparator) || (c == kAlternatePathSeparator);
  6824. #else
  6825. return c == kPathSeparator;
  6826. #endif
  6827. }
  6828. // Returns the current working directory, or "" if unsuccessful.
  6829. FilePath FilePath::GetCurrentDir() {
  6830. #if GTEST_OS_WINDOWS_MOBILE
  6831. // Windows CE doesn't have a current directory, so we just return
  6832. // something reasonable.
  6833. return FilePath(kCurrentDirectoryString);
  6834. #elif GTEST_OS_WINDOWS
  6835. char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
  6836. return FilePath(_getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
  6837. #else
  6838. char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
  6839. return FilePath(getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
  6840. #endif // GTEST_OS_WINDOWS_MOBILE
  6841. }
  6842. // Returns a copy of the FilePath with the case-insensitive extension removed.
  6843. // Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
  6844. // FilePath("dir/file"). If a case-insensitive extension is not
  6845. // found, returns a copy of the original FilePath.
  6846. FilePath FilePath::RemoveExtension(const char* extension) const {
  6847. const std::string dot_extension = std::string(".") + extension;
  6848. if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) {
  6849. return FilePath(pathname_.substr(
  6850. 0, pathname_.length() - dot_extension.length()));
  6851. }
  6852. return *this;
  6853. }
  6854. // Returns a pointer to the last occurence of a valid path separator in
  6855. // the FilePath. On Windows, for example, both '/' and '\' are valid path
  6856. // separators. Returns NULL if no path separator was found.
  6857. const char* FilePath::FindLastPathSeparator() const {
  6858. const char* const last_sep = strrchr(c_str(), kPathSeparator);
  6859. #if GTEST_HAS_ALT_PATH_SEP_
  6860. const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator);
  6861. // Comparing two pointers of which only one is NULL is undefined.
  6862. if (last_alt_sep != NULL &&
  6863. (last_sep == NULL || last_alt_sep > last_sep)) {
  6864. return last_alt_sep;
  6865. }
  6866. #endif
  6867. return last_sep;
  6868. }
  6869. // Returns a copy of the FilePath with the directory part removed.
  6870. // Example: FilePath("path/to/file").RemoveDirectoryName() returns
  6871. // FilePath("file"). If there is no directory part ("just_a_file"), it returns
  6872. // the FilePath unmodified. If there is no file part ("just_a_dir/") it
  6873. // returns an empty FilePath ("").
  6874. // On Windows platform, '\' is the path separator, otherwise it is '/'.
  6875. FilePath FilePath::RemoveDirectoryName() const {
  6876. const char* const last_sep = FindLastPathSeparator();
  6877. return last_sep ? FilePath(last_sep + 1) : *this;
  6878. }
  6879. // RemoveFileName returns the directory path with the filename removed.
  6880. // Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
  6881. // If the FilePath is "a_file" or "/a_file", RemoveFileName returns
  6882. // FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
  6883. // not have a file, like "just/a/dir/", it returns the FilePath unmodified.
  6884. // On Windows platform, '\' is the path separator, otherwise it is '/'.
  6885. FilePath FilePath::RemoveFileName() const {
  6886. const char* const last_sep = FindLastPathSeparator();
  6887. std::string dir;
  6888. if (last_sep) {
  6889. dir = std::string(c_str(), last_sep + 1 - c_str());
  6890. } else {
  6891. dir = kCurrentDirectoryString;
  6892. }
  6893. return FilePath(dir);
  6894. }
  6895. // Helper functions for naming files in a directory for xml output.
  6896. // Given directory = "dir", base_name = "test", number = 0,
  6897. // extension = "xml", returns "dir/test.xml". If number is greater
  6898. // than zero (e.g., 12), returns "dir/test_12.xml".
  6899. // On Windows platform, uses \ as the separator rather than /.
  6900. FilePath FilePath::MakeFileName(const FilePath& directory,
  6901. const FilePath& base_name,
  6902. int number,
  6903. const char* extension) {
  6904. std::string file;
  6905. if (number == 0) {
  6906. file = base_name.string() + "." + extension;
  6907. } else {
  6908. file = base_name.string() + "_" + StreamableToString(number)
  6909. + "." + extension;
  6910. }
  6911. return ConcatPaths(directory, FilePath(file));
  6912. }
  6913. // Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml".
  6914. // On Windows, uses \ as the separator rather than /.
  6915. FilePath FilePath::ConcatPaths(const FilePath& directory,
  6916. const FilePath& relative_path) {
  6917. if (directory.IsEmpty())
  6918. return relative_path;
  6919. const FilePath dir(directory.RemoveTrailingPathSeparator());
  6920. return FilePath(dir.string() + kPathSeparator + relative_path.string());
  6921. }
  6922. // Returns true if pathname describes something findable in the file-system,
  6923. // either a file, directory, or whatever.
  6924. bool FilePath::FileOrDirectoryExists() const {
  6925. #if GTEST_OS_WINDOWS_MOBILE
  6926. LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());
  6927. const DWORD attributes = GetFileAttributes(unicode);
  6928. delete [] unicode;
  6929. return attributes != kInvalidFileAttributes;
  6930. #else
  6931. posix::StatStruct file_stat;
  6932. return posix::Stat(pathname_.c_str(), &file_stat) == 0;
  6933. #endif // GTEST_OS_WINDOWS_MOBILE
  6934. }
  6935. // Returns true if pathname describes a directory in the file-system
  6936. // that exists.
  6937. bool FilePath::DirectoryExists() const {
  6938. bool result = false;
  6939. #if GTEST_OS_WINDOWS
  6940. // Don't strip off trailing separator if path is a root directory on
  6941. // Windows (like "C:\\").
  6942. const FilePath& path(IsRootDirectory() ? *this :
  6943. RemoveTrailingPathSeparator());
  6944. #else
  6945. const FilePath& path(*this);
  6946. #endif
  6947. #if GTEST_OS_WINDOWS_MOBILE
  6948. LPCWSTR unicode = String::AnsiToUtf16(path.c_str());
  6949. const DWORD attributes = GetFileAttributes(unicode);
  6950. delete [] unicode;
  6951. if ((attributes != kInvalidFileAttributes) &&
  6952. (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
  6953. result = true;
  6954. }
  6955. #else
  6956. posix::StatStruct file_stat;
  6957. result = posix::Stat(path.c_str(), &file_stat) == 0 &&
  6958. posix::IsDir(file_stat);
  6959. #endif // GTEST_OS_WINDOWS_MOBILE
  6960. return result;
  6961. }
  6962. // Returns true if pathname describes a root directory. (Windows has one
  6963. // root directory per disk drive.)
  6964. bool FilePath::IsRootDirectory() const {
  6965. #if GTEST_OS_WINDOWS
  6966. // TODO(wan@google.com): on Windows a network share like
  6967. // \\server\share can be a root directory, although it cannot be the
  6968. // current directory. Handle this properly.
  6969. return pathname_.length() == 3 && IsAbsolutePath();
  6970. #else
  6971. return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]);
  6972. #endif
  6973. }
  6974. // Returns true if pathname describes an absolute path.
  6975. bool FilePath::IsAbsolutePath() const {
  6976. const char* const name = pathname_.c_str();
  6977. #if GTEST_OS_WINDOWS
  6978. return pathname_.length() >= 3 &&
  6979. ((name[0] >= 'a' && name[0] <= 'z') ||
  6980. (name[0] >= 'A' && name[0] <= 'Z')) &&
  6981. name[1] == ':' &&
  6982. IsPathSeparator(name[2]);
  6983. #else
  6984. return IsPathSeparator(name[0]);
  6985. #endif
  6986. }
  6987. // Returns a pathname for a file that does not currently exist. The pathname
  6988. // will be directory/base_name.extension or
  6989. // directory/base_name_<number>.extension if directory/base_name.extension
  6990. // already exists. The number will be incremented until a pathname is found
  6991. // that does not already exist.
  6992. // Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.
  6993. // There could be a race condition if two or more processes are calling this
  6994. // function at the same time -- they could both pick the same filename.
  6995. FilePath FilePath::GenerateUniqueFileName(const FilePath& directory,
  6996. const FilePath& base_name,
  6997. const char* extension) {
  6998. FilePath full_pathname;
  6999. int number = 0;
  7000. do {
  7001. full_pathname.Set(MakeFileName(directory, base_name, number++, extension));
  7002. } while (full_pathname.FileOrDirectoryExists());
  7003. return full_pathname;
  7004. }
  7005. // Returns true if FilePath ends with a path separator, which indicates that
  7006. // it is intended to represent a directory. Returns false otherwise.
  7007. // This does NOT check that a directory (or file) actually exists.
  7008. bool FilePath::IsDirectory() const {
  7009. return !pathname_.empty() &&
  7010. IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]);
  7011. }
  7012. // Create directories so that path exists. Returns true if successful or if
  7013. // the directories already exist; returns false if unable to create directories
  7014. // for any reason.
  7015. bool FilePath::CreateDirectoriesRecursively() const {
  7016. if (!this->IsDirectory()) {
  7017. return false;
  7018. }
  7019. if (pathname_.length() == 0 || this->DirectoryExists()) {
  7020. return true;
  7021. }
  7022. const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName());
  7023. return parent.CreateDirectoriesRecursively() && this->CreateFolder();
  7024. }
  7025. // Create the directory so that path exists. Returns true if successful or
  7026. // if the directory already exists; returns false if unable to create the
  7027. // directory for any reason, including if the parent directory does not
  7028. // exist. Not named "CreateDirectory" because that's a macro on Windows.
  7029. bool FilePath::CreateFolder() const {
  7030. #if GTEST_OS_WINDOWS_MOBILE
  7031. FilePath removed_sep(this->RemoveTrailingPathSeparator());
  7032. LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());
  7033. int result = CreateDirectory(unicode, NULL) ? 0 : -1;
  7034. delete [] unicode;
  7035. #elif GTEST_OS_WINDOWS
  7036. int result = _mkdir(pathname_.c_str());
  7037. #else
  7038. int result = mkdir(pathname_.c_str(), 0777);
  7039. #endif // GTEST_OS_WINDOWS_MOBILE
  7040. if (result == -1) {
  7041. return this->DirectoryExists(); // An error is OK if the directory exists.
  7042. }
  7043. return true; // No error.
  7044. }
  7045. // If input name has a trailing separator character, remove it and return the
  7046. // name, otherwise return the name string unmodified.
  7047. // On Windows platform, uses \ as the separator, other platforms use /.
  7048. FilePath FilePath::RemoveTrailingPathSeparator() const {
  7049. return IsDirectory()
  7050. ? FilePath(pathname_.substr(0, pathname_.length() - 1))
  7051. : *this;
  7052. }
  7053. // Removes any redundant separators that might be in the pathname.
  7054. // For example, "bar///foo" becomes "bar/foo". Does not eliminate other
  7055. // redundancies that might be in a pathname involving "." or "..".
  7056. // TODO(wan@google.com): handle Windows network shares (e.g. \\server\share).
  7057. void FilePath::Normalize() {
  7058. if (pathname_.c_str() == NULL) {
  7059. pathname_ = "";
  7060. return;
  7061. }
  7062. const char* src = pathname_.c_str();
  7063. char* const dest = new char[pathname_.length() + 1];
  7064. char* dest_ptr = dest;
  7065. memset(dest_ptr, 0, pathname_.length() + 1);
  7066. while (*src != '\0') {
  7067. *dest_ptr = *src;
  7068. if (!IsPathSeparator(*src)) {
  7069. src++;
  7070. } else {
  7071. #if GTEST_HAS_ALT_PATH_SEP_
  7072. if (*dest_ptr == kAlternatePathSeparator) {
  7073. *dest_ptr = kPathSeparator;
  7074. }
  7075. #endif
  7076. while (IsPathSeparator(*src))
  7077. src++;
  7078. }
  7079. dest_ptr++;
  7080. }
  7081. *dest_ptr = '\0';
  7082. pathname_ = dest;
  7083. delete[] dest;
  7084. }
  7085. } // namespace internal
  7086. } // namespace testing
  7087. // Copyright 2008, Google Inc.
  7088. // All rights reserved.
  7089. //
  7090. // Redistribution and use in source and binary forms, with or without
  7091. // modification, are permitted provided that the following conditions are
  7092. // met:
  7093. //
  7094. // * Redistributions of source code must retain the above copyright
  7095. // notice, this list of conditions and the following disclaimer.
  7096. // * Redistributions in binary form must reproduce the above
  7097. // copyright notice, this list of conditions and the following disclaimer
  7098. // in the documentation and/or other materials provided with the
  7099. // distribution.
  7100. // * Neither the name of Google Inc. nor the names of its
  7101. // contributors may be used to endorse or promote products derived from
  7102. // this software without specific prior written permission.
  7103. //
  7104. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  7105. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  7106. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  7107. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7108. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  7109. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  7110. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  7111. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  7112. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  7113. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  7114. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  7115. //
  7116. // Author: wan@google.com (Zhanyong Wan)
  7117. #include <limits.h>
  7118. #include <stdlib.h>
  7119. #include <stdio.h>
  7120. #include <string.h>
  7121. #if GTEST_OS_WINDOWS_MOBILE
  7122. # include <windows.h> // For TerminateProcess()
  7123. #elif GTEST_OS_WINDOWS
  7124. # include <io.h>
  7125. # include <sys/stat.h>
  7126. #else
  7127. # include <unistd.h>
  7128. #endif // GTEST_OS_WINDOWS_MOBILE
  7129. #if GTEST_OS_MAC
  7130. # include <mach/mach_init.h>
  7131. # include <mach/task.h>
  7132. # include <mach/vm_map.h>
  7133. #endif // GTEST_OS_MAC
  7134. #if GTEST_OS_QNX
  7135. # include <devctl.h>
  7136. # include <sys/procfs.h>
  7137. #endif // GTEST_OS_QNX
  7138. // Indicates that this translation unit is part of Google Test's
  7139. // implementation. It must come before gtest-internal-inl.h is
  7140. // included, or there will be a compiler error. This trick is to
  7141. // prevent a user from accidentally including gtest-internal-inl.h in
  7142. // his code.
  7143. #define GTEST_IMPLEMENTATION_ 1
  7144. #undef GTEST_IMPLEMENTATION_
  7145. namespace testing {
  7146. namespace internal {
  7147. #if defined(_MSC_VER) || defined(__BORLANDC__)
  7148. // MSVC and C++Builder do not provide a definition of STDERR_FILENO.
  7149. const int kStdOutFileno = 1;
  7150. const int kStdErrFileno = 2;
  7151. #else
  7152. const int kStdOutFileno = STDOUT_FILENO;
  7153. const int kStdErrFileno = STDERR_FILENO;
  7154. #endif // _MSC_VER
  7155. #if GTEST_OS_MAC
  7156. // Returns the number of threads running in the process, or 0 to indicate that
  7157. // we cannot detect it.
  7158. size_t GetThreadCount() {
  7159. const task_t task = mach_task_self();
  7160. mach_msg_type_number_t thread_count;
  7161. thread_act_array_t thread_list;
  7162. const kern_return_t status = task_threads(task, &thread_list, &thread_count);
  7163. if (status == KERN_SUCCESS) {
  7164. // task_threads allocates resources in thread_list and we need to free them
  7165. // to avoid leaks.
  7166. vm_deallocate(task,
  7167. reinterpret_cast<vm_address_t>(thread_list),
  7168. sizeof(thread_t) * thread_count);
  7169. return static_cast<size_t>(thread_count);
  7170. } else {
  7171. return 0;
  7172. }
  7173. }
  7174. #elif GTEST_OS_QNX
  7175. // Returns the number of threads running in the process, or 0 to indicate that
  7176. // we cannot detect it.
  7177. size_t GetThreadCount() {
  7178. const int fd = open("/proc/self/as", O_RDONLY);
  7179. if (fd < 0) {
  7180. return 0;
  7181. }
  7182. procfs_info process_info;
  7183. const int status =
  7184. devctl(fd, DCMD_PROC_INFO, &process_info, sizeof(process_info), NULL);
  7185. close(fd);
  7186. if (status == EOK) {
  7187. return static_cast<size_t>(process_info.num_threads);
  7188. } else {
  7189. return 0;
  7190. }
  7191. }
  7192. #else
  7193. size_t GetThreadCount() {
  7194. // There's no portable way to detect the number of threads, so we just
  7195. // return 0 to indicate that we cannot detect it.
  7196. return 0;
  7197. }
  7198. #endif // GTEST_OS_MAC
  7199. #if GTEST_USES_POSIX_RE
  7200. // Implements RE. Currently only needed for death tests.
  7201. RE::~RE() {
  7202. if (is_valid_) {
  7203. // regfree'ing an invalid regex might crash because the content
  7204. // of the regex is undefined. Since the regex's are essentially
  7205. // the same, one cannot be valid (or invalid) without the other
  7206. // being so too.
  7207. regfree(&partial_regex_);
  7208. regfree(&full_regex_);
  7209. }
  7210. free(const_cast<char*>(pattern_));
  7211. }
  7212. // Returns true iff regular expression re matches the entire str.
  7213. bool RE::FullMatch(const char* str, const RE& re) {
  7214. if (!re.is_valid_) return false;
  7215. regmatch_t match;
  7216. return regexec(&re.full_regex_, str, 1, &match, 0) == 0;
  7217. }
  7218. // Returns true iff regular expression re matches a substring of str
  7219. // (including str itself).
  7220. bool RE::PartialMatch(const char* str, const RE& re) {
  7221. if (!re.is_valid_) return false;
  7222. regmatch_t match;
  7223. return regexec(&re.partial_regex_, str, 1, &match, 0) == 0;
  7224. }
  7225. // Initializes an RE from its string representation.
  7226. void RE::Init(const char* regex) {
  7227. pattern_ = posix::StrDup(regex);
  7228. // Reserves enough bytes to hold the regular expression used for a
  7229. // full match.
  7230. const size_t full_regex_len = strlen(regex) + 10;
  7231. char* const full_pattern = new char[full_regex_len];
  7232. snprintf(full_pattern, full_regex_len, "^(%s)$", regex);
  7233. is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0;
  7234. // We want to call regcomp(&partial_regex_, ...) even if the
  7235. // previous expression returns false. Otherwise partial_regex_ may
  7236. // not be properly initialized can may cause trouble when it's
  7237. // freed.
  7238. //
  7239. // Some implementation of POSIX regex (e.g. on at least some
  7240. // versions of Cygwin) doesn't accept the empty string as a valid
  7241. // regex. We change it to an equivalent form "()" to be safe.
  7242. if (is_valid_) {
  7243. const char* const partial_regex = (*regex == '\0') ? "()" : regex;
  7244. is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0;
  7245. }
  7246. EXPECT_TRUE(is_valid_)
  7247. << "Regular expression \"" << regex
  7248. << "\" is not a valid POSIX Extended regular expression.";
  7249. delete[] full_pattern;
  7250. }
  7251. #elif GTEST_USES_SIMPLE_RE
  7252. // Returns true iff ch appears anywhere in str (excluding the
  7253. // terminating '\0' character).
  7254. bool IsInSet(char ch, const char* str) {
  7255. return ch != '\0' && strchr(str, ch) != NULL;
  7256. }
  7257. // Returns true iff ch belongs to the given classification. Unlike
  7258. // similar functions in <ctype.h>, these aren't affected by the
  7259. // current locale.
  7260. bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; }
  7261. bool IsAsciiPunct(char ch) {
  7262. return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
  7263. }
  7264. bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); }
  7265. bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); }
  7266. bool IsAsciiWordChar(char ch) {
  7267. return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') ||
  7268. ('0' <= ch && ch <= '9') || ch == '_';
  7269. }
  7270. // Returns true iff "\\c" is a supported escape sequence.
  7271. bool IsValidEscape(char c) {
  7272. return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW"));
  7273. }
  7274. // Returns true iff the given atom (specified by escaped and pattern)
  7275. // matches ch. The result is undefined if the atom is invalid.
  7276. bool AtomMatchesChar(bool escaped, char pattern_char, char ch) {
  7277. if (escaped) { // "\\p" where p is pattern_char.
  7278. switch (pattern_char) {
  7279. case 'd': return IsAsciiDigit(ch);
  7280. case 'D': return !IsAsciiDigit(ch);
  7281. case 'f': return ch == '\f';
  7282. case 'n': return ch == '\n';
  7283. case 'r': return ch == '\r';
  7284. case 's': return IsAsciiWhiteSpace(ch);
  7285. case 'S': return !IsAsciiWhiteSpace(ch);
  7286. case 't': return ch == '\t';
  7287. case 'v': return ch == '\v';
  7288. case 'w': return IsAsciiWordChar(ch);
  7289. case 'W': return !IsAsciiWordChar(ch);
  7290. }
  7291. return IsAsciiPunct(pattern_char) && pattern_char == ch;
  7292. }
  7293. return (pattern_char == '.' && ch != '\n') || pattern_char == ch;
  7294. }
  7295. // Helper function used by ValidateRegex() to format error messages.
  7296. std::string FormatRegexSyntaxError(const char* regex, int index) {
  7297. return (Message() << "Syntax error at index " << index
  7298. << " in simple regular expression \"" << regex << "\": ").GetString();
  7299. }
  7300. // Generates non-fatal failures and returns false if regex is invalid;
  7301. // otherwise returns true.
  7302. bool ValidateRegex(const char* regex) {
  7303. if (regex == NULL) {
  7304. // TODO(wan@google.com): fix the source file location in the
  7305. // assertion failures to match where the regex is used in user
  7306. // code.
  7307. ADD_FAILURE() << "NULL is not a valid simple regular expression.";
  7308. return false;
  7309. }
  7310. bool is_valid = true;
  7311. // True iff ?, *, or + can follow the previous atom.
  7312. bool prev_repeatable = false;
  7313. for (int i = 0; regex[i]; i++) {
  7314. if (regex[i] == '\\') { // An escape sequence
  7315. i++;
  7316. if (regex[i] == '\0') {
  7317. ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
  7318. << "'\\' cannot appear at the end.";
  7319. return false;
  7320. }
  7321. if (!IsValidEscape(regex[i])) {
  7322. ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
  7323. << "invalid escape sequence \"\\" << regex[i] << "\".";
  7324. is_valid = false;
  7325. }
  7326. prev_repeatable = true;
  7327. } else { // Not an escape sequence.
  7328. const char ch = regex[i];
  7329. if (ch == '^' && i > 0) {
  7330. ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
  7331. << "'^' can only appear at the beginning.";
  7332. is_valid = false;
  7333. } else if (ch == '$' && regex[i + 1] != '\0') {
  7334. ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
  7335. << "'$' can only appear at the end.";
  7336. is_valid = false;
  7337. } else if (IsInSet(ch, "()[]{}|")) {
  7338. ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
  7339. << "'" << ch << "' is unsupported.";
  7340. is_valid = false;
  7341. } else if (IsRepeat(ch) && !prev_repeatable) {
  7342. ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
  7343. << "'" << ch << "' can only follow a repeatable token.";
  7344. is_valid = false;
  7345. }
  7346. prev_repeatable = !IsInSet(ch, "^$?*+");
  7347. }
  7348. }
  7349. return is_valid;
  7350. }
  7351. // Matches a repeated regex atom followed by a valid simple regular
  7352. // expression. The regex atom is defined as c if escaped is false,
  7353. // or \c otherwise. repeat is the repetition meta character (?, *,
  7354. // or +). The behavior is undefined if str contains too many
  7355. // characters to be indexable by size_t, in which case the test will
  7356. // probably time out anyway. We are fine with this limitation as
  7357. // std::string has it too.
  7358. bool MatchRepetitionAndRegexAtHead(
  7359. bool escaped, char c, char repeat, const char* regex,
  7360. const char* str) {
  7361. const size_t min_count = (repeat == '+') ? 1 : 0;
  7362. const size_t max_count = (repeat == '?') ? 1 :
  7363. static_cast<size_t>(-1) - 1;
  7364. // We cannot call numeric_limits::max() as it conflicts with the
  7365. // max() macro on Windows.
  7366. for (size_t i = 0; i <= max_count; ++i) {
  7367. // We know that the atom matches each of the first i characters in str.
  7368. if (i >= min_count && MatchRegexAtHead(regex, str + i)) {
  7369. // We have enough matches at the head, and the tail matches too.
  7370. // Since we only care about *whether* the pattern matches str
  7371. // (as opposed to *how* it matches), there is no need to find a
  7372. // greedy match.
  7373. return true;
  7374. }
  7375. if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i]))
  7376. return false;
  7377. }
  7378. return false;
  7379. }
  7380. // Returns true iff regex matches a prefix of str. regex must be a
  7381. // valid simple regular expression and not start with "^", or the
  7382. // result is undefined.
  7383. bool MatchRegexAtHead(const char* regex, const char* str) {
  7384. if (*regex == '\0') // An empty regex matches a prefix of anything.
  7385. return true;
  7386. // "$" only matches the end of a string. Note that regex being
  7387. // valid guarantees that there's nothing after "$" in it.
  7388. if (*regex == '$')
  7389. return *str == '\0';
  7390. // Is the first thing in regex an escape sequence?
  7391. const bool escaped = *regex == '\\';
  7392. if (escaped)
  7393. ++regex;
  7394. if (IsRepeat(regex[1])) {
  7395. // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so
  7396. // here's an indirect recursion. It terminates as the regex gets
  7397. // shorter in each recursion.
  7398. return MatchRepetitionAndRegexAtHead(
  7399. escaped, regex[0], regex[1], regex + 2, str);
  7400. } else {
  7401. // regex isn't empty, isn't "$", and doesn't start with a
  7402. // repetition. We match the first atom of regex with the first
  7403. // character of str and recurse.
  7404. return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) &&
  7405. MatchRegexAtHead(regex + 1, str + 1);
  7406. }
  7407. }
  7408. // Returns true iff regex matches any substring of str. regex must be
  7409. // a valid simple regular expression, or the result is undefined.
  7410. //
  7411. // The algorithm is recursive, but the recursion depth doesn't exceed
  7412. // the regex length, so we won't need to worry about running out of
  7413. // stack space normally. In rare cases the time complexity can be
  7414. // exponential with respect to the regex length + the string length,
  7415. // but usually it's must faster (often close to linear).
  7416. bool MatchRegexAnywhere(const char* regex, const char* str) {
  7417. if (regex == NULL || str == NULL)
  7418. return false;
  7419. if (*regex == '^')
  7420. return MatchRegexAtHead(regex + 1, str);
  7421. // A successful match can be anywhere in str.
  7422. do {
  7423. if (MatchRegexAtHead(regex, str))
  7424. return true;
  7425. } while (*str++ != '\0');
  7426. return false;
  7427. }
  7428. // Implements the RE class.
  7429. RE::~RE() {
  7430. free(const_cast<char*>(pattern_));
  7431. free(const_cast<char*>(full_pattern_));
  7432. }
  7433. // Returns true iff regular expression re matches the entire str.
  7434. bool RE::FullMatch(const char* str, const RE& re) {
  7435. return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);
  7436. }
  7437. // Returns true iff regular expression re matches a substring of str
  7438. // (including str itself).
  7439. bool RE::PartialMatch(const char* str, const RE& re) {
  7440. return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);
  7441. }
  7442. // Initializes an RE from its string representation.
  7443. void RE::Init(const char* regex) {
  7444. pattern_ = full_pattern_ = NULL;
  7445. if (regex != NULL) {
  7446. pattern_ = posix::StrDup(regex);
  7447. }
  7448. is_valid_ = ValidateRegex(regex);
  7449. if (!is_valid_) {
  7450. // No need to calculate the full pattern when the regex is invalid.
  7451. return;
  7452. }
  7453. const size_t len = strlen(regex);
  7454. // Reserves enough bytes to hold the regular expression used for a
  7455. // full match: we need space to prepend a '^', append a '$', and
  7456. // terminate the string with '\0'.
  7457. char* buffer = static_cast<char*>(malloc(len + 3));
  7458. full_pattern_ = buffer;
  7459. if (*regex != '^')
  7460. *buffer++ = '^'; // Makes sure full_pattern_ starts with '^'.
  7461. // We don't use snprintf or strncpy, as they trigger a warning when
  7462. // compiled with VC++ 8.0.
  7463. memcpy(buffer, regex, len);
  7464. buffer += len;
  7465. if (len == 0 || regex[len - 1] != '$')
  7466. *buffer++ = '$'; // Makes sure full_pattern_ ends with '$'.
  7467. *buffer = '\0';
  7468. }
  7469. #endif // GTEST_USES_POSIX_RE
  7470. const char kUnknownFile[] = "unknown file";
  7471. // Formats a source file path and a line number as they would appear
  7472. // in an error message from the compiler used to compile this code.
  7473. GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) {
  7474. const std::string file_name(file == NULL ? kUnknownFile : file);
  7475. if (line < 0) {
  7476. return file_name + ":";
  7477. }
  7478. #ifdef _MSC_VER
  7479. return file_name + "(" + StreamableToString(line) + "):";
  7480. #else
  7481. return file_name + ":" + StreamableToString(line) + ":";
  7482. #endif // _MSC_VER
  7483. }
  7484. // Formats a file location for compiler-independent XML output.
  7485. // Although this function is not platform dependent, we put it next to
  7486. // FormatFileLocation in order to contrast the two functions.
  7487. // Note that FormatCompilerIndependentFileLocation() does NOT append colon
  7488. // to the file location it produces, unlike FormatFileLocation().
  7489. GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(
  7490. const char* file, int line) {
  7491. const std::string file_name(file == NULL ? kUnknownFile : file);
  7492. if (line < 0)
  7493. return file_name;
  7494. else
  7495. return file_name + ":" + StreamableToString(line);
  7496. }
  7497. GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line)
  7498. : severity_(severity) {
  7499. const char* const marker =
  7500. severity == GTEST_INFO ? "[ INFO ]" :
  7501. severity == GTEST_WARNING ? "[WARNING]" :
  7502. severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]";
  7503. GetStream() << ::std::endl << marker << " "
  7504. << FormatFileLocation(file, line).c_str() << ": ";
  7505. }
  7506. // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
  7507. GTestLog::~GTestLog() {
  7508. GetStream() << ::std::endl;
  7509. if (severity_ == GTEST_FATAL) {
  7510. fflush(stderr);
  7511. posix::Abort();
  7512. }
  7513. }
  7514. // Disable Microsoft deprecation warnings for POSIX functions called from
  7515. // this class (creat, dup, dup2, and close)
  7516. #ifdef _MSC_VER
  7517. # pragma warning(push)
  7518. # pragma warning(disable: 4996)
  7519. #endif // _MSC_VER
  7520. #if GTEST_HAS_STREAM_REDIRECTION
  7521. // Object that captures an output stream (stdout/stderr).
  7522. class CapturedStream {
  7523. public:
  7524. // The ctor redirects the stream to a temporary file.
  7525. explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {
  7526. # if GTEST_OS_WINDOWS
  7527. char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT
  7528. char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT
  7529. ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path);
  7530. const UINT success = ::GetTempFileNameA(temp_dir_path,
  7531. "gtest_redir",
  7532. 0, // Generate unique file name.
  7533. temp_file_path);
  7534. GTEST_CHECK_(success != 0)
  7535. << "Unable to create a temporary file in " << temp_dir_path;
  7536. const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
  7537. GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file "
  7538. << temp_file_path;
  7539. filename_ = temp_file_path;
  7540. # else
  7541. // There's no guarantee that a test has write access to the current
  7542. // directory, so we create the temporary file in the /tmp directory
  7543. // instead. We use /tmp on most systems, and /sdcard on Android.
  7544. // That's because Android doesn't have /tmp.
  7545. # if GTEST_OS_LINUX_ANDROID
  7546. // Note: Android applications are expected to call the framework's
  7547. // Context.getExternalStorageDirectory() method through JNI to get
  7548. // the location of the world-writable SD Card directory. However,
  7549. // this requires a Context handle, which cannot be retrieved
  7550. // globally from native code. Doing so also precludes running the
  7551. // code as part of a regular standalone executable, which doesn't
  7552. // run in a Dalvik process (e.g. when running it through 'adb shell').
  7553. //
  7554. // The location /sdcard is directly accessible from native code
  7555. // and is the only location (unofficially) supported by the Android
  7556. // team. It's generally a symlink to the real SD Card mount point
  7557. // which can be /mnt/sdcard, /mnt/sdcard0, /system/media/sdcard, or
  7558. // other OEM-customized locations. Never rely on these, and always
  7559. // use /sdcard.
  7560. char name_template[] = "/sdcard/gtest_captured_stream.XXXXXX";
  7561. # else
  7562. char name_template[] = "/tmp/captured_stream.XXXXXX";
  7563. # endif // GTEST_OS_LINUX_ANDROID
  7564. const int captured_fd = mkstemp(name_template);
  7565. filename_ = name_template;
  7566. # endif // GTEST_OS_WINDOWS
  7567. fflush(NULL);
  7568. dup2(captured_fd, fd_);
  7569. close(captured_fd);
  7570. }
  7571. ~CapturedStream() {
  7572. remove(filename_.c_str());
  7573. }
  7574. std::string GetCapturedString() {
  7575. if (uncaptured_fd_ != -1) {
  7576. // Restores the original stream.
  7577. fflush(NULL);
  7578. dup2(uncaptured_fd_, fd_);
  7579. close(uncaptured_fd_);
  7580. uncaptured_fd_ = -1;
  7581. }
  7582. FILE* const file = posix::FOpen(filename_.c_str(), "r");
  7583. const std::string content = ReadEntireFile(file);
  7584. posix::FClose(file);
  7585. return content;
  7586. }
  7587. private:
  7588. // Reads the entire content of a file as an std::string.
  7589. static std::string ReadEntireFile(FILE* file);
  7590. // Returns the size (in bytes) of a file.
  7591. static size_t GetFileSize(FILE* file);
  7592. const int fd_; // A stream to capture.
  7593. int uncaptured_fd_;
  7594. // Name of the temporary file holding the stderr output.
  7595. ::std::string filename_;
  7596. GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream);
  7597. };
  7598. // Returns the size (in bytes) of a file.
  7599. size_t CapturedStream::GetFileSize(FILE* file) {
  7600. fseek(file, 0, SEEK_END);
  7601. return static_cast<size_t>(ftell(file));
  7602. }
  7603. // Reads the entire content of a file as a string.
  7604. std::string CapturedStream::ReadEntireFile(FILE* file) {
  7605. const size_t file_size = GetFileSize(file);
  7606. char* const buffer = new char[file_size];
  7607. size_t bytes_last_read = 0; // # of bytes read in the last fread()
  7608. size_t bytes_read = 0; // # of bytes read so far
  7609. fseek(file, 0, SEEK_SET);
  7610. // Keeps reading the file until we cannot read further or the
  7611. // pre-determined file size is reached.
  7612. do {
  7613. bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
  7614. bytes_read += bytes_last_read;
  7615. } while (bytes_last_read > 0 && bytes_read < file_size);
  7616. const std::string content(buffer, bytes_read);
  7617. delete[] buffer;
  7618. return content;
  7619. }
  7620. # ifdef _MSC_VER
  7621. # pragma warning(pop)
  7622. # endif // _MSC_VER
  7623. static CapturedStream* g_captured_stderr = NULL;
  7624. static CapturedStream* g_captured_stdout = NULL;
  7625. // Starts capturing an output stream (stdout/stderr).
  7626. void CaptureStream(int fd, const char* stream_name, CapturedStream** stream) {
  7627. if (*stream != NULL) {
  7628. GTEST_LOG_(FATAL) << "Only one " << stream_name
  7629. << " capturer can exist at a time.";
  7630. }
  7631. *stream = new CapturedStream(fd);
  7632. }
  7633. // Stops capturing the output stream and returns the captured string.
  7634. std::string GetCapturedStream(CapturedStream** captured_stream) {
  7635. const std::string content = (*captured_stream)->GetCapturedString();
  7636. delete *captured_stream;
  7637. *captured_stream = NULL;
  7638. return content;
  7639. }
  7640. // Starts capturing stdout.
  7641. void CaptureStdout() {
  7642. CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout);
  7643. }
  7644. // Starts capturing stderr.
  7645. void CaptureStderr() {
  7646. CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr);
  7647. }
  7648. // Stops capturing stdout and returns the captured string.
  7649. std::string GetCapturedStdout() {
  7650. return GetCapturedStream(&g_captured_stdout);
  7651. }
  7652. // Stops capturing stderr and returns the captured string.
  7653. std::string GetCapturedStderr() {
  7654. return GetCapturedStream(&g_captured_stderr);
  7655. }
  7656. #endif // GTEST_HAS_STREAM_REDIRECTION
  7657. #if GTEST_HAS_DEATH_TEST
  7658. // A copy of all command line arguments. Set by InitGoogleTest().
  7659. ::std::vector<testing::internal::string> g_argvs;
  7660. static const ::std::vector<testing::internal::string>* g_injected_test_argvs =
  7661. NULL; // Owned.
  7662. void SetInjectableArgvs(const ::std::vector<testing::internal::string>* argvs) {
  7663. if (g_injected_test_argvs != argvs)
  7664. delete g_injected_test_argvs;
  7665. g_injected_test_argvs = argvs;
  7666. }
  7667. const ::std::vector<testing::internal::string>& GetInjectableArgvs() {
  7668. if (g_injected_test_argvs != NULL) {
  7669. return *g_injected_test_argvs;
  7670. }
  7671. return g_argvs;
  7672. }
  7673. #endif // GTEST_HAS_DEATH_TEST
  7674. #if GTEST_OS_WINDOWS_MOBILE
  7675. namespace posix {
  7676. void Abort() {
  7677. DebugBreak();
  7678. TerminateProcess(GetCurrentProcess(), 1);
  7679. }
  7680. } // namespace posix
  7681. #endif // GTEST_OS_WINDOWS_MOBILE
  7682. // Returns the name of the environment variable corresponding to the
  7683. // given flag. For example, FlagToEnvVar("foo") will return
  7684. // "GTEST_FOO" in the open-source version.
  7685. static std::string FlagToEnvVar(const char* flag) {
  7686. const std::string full_flag =
  7687. (Message() << GTEST_FLAG_PREFIX_ << flag).GetString();
  7688. Message env_var;
  7689. for (size_t i = 0; i != full_flag.length(); i++) {
  7690. env_var << ToUpper(full_flag.c_str()[i]);
  7691. }
  7692. return env_var.GetString();
  7693. }
  7694. // Parses 'str' for a 32-bit signed integer. If successful, writes
  7695. // the result to *value and returns true; otherwise leaves *value
  7696. // unchanged and returns false.
  7697. bool ParseInt32(const Message& src_text, const char* str, Int32* value) {
  7698. // Parses the environment variable as a decimal integer.
  7699. char* end = NULL;
  7700. const long long_value = strtol(str, &end, 10); // NOLINT
  7701. // Has strtol() consumed all characters in the string?
  7702. if (*end != '\0') {
  7703. // No - an invalid character was encountered.
  7704. Message msg;
  7705. msg << "WARNING: " << src_text
  7706. << " is expected to be a 32-bit integer, but actually"
  7707. << " has value \"" << str << "\".\n";
  7708. printf("%s", msg.GetString().c_str());
  7709. fflush(stdout);
  7710. return false;
  7711. }
  7712. // Is the parsed value in the range of an Int32?
  7713. const Int32 result = static_cast<Int32>(long_value);
  7714. if (long_value == LONG_MAX || long_value == LONG_MIN ||
  7715. // The parsed value overflows as a long. (strtol() returns
  7716. // LONG_MAX or LONG_MIN when the input overflows.)
  7717. result != long_value
  7718. // The parsed value overflows as an Int32.
  7719. ) {
  7720. Message msg;
  7721. msg << "WARNING: " << src_text
  7722. << " is expected to be a 32-bit integer, but actually"
  7723. << " has value " << str << ", which overflows.\n";
  7724. printf("%s", msg.GetString().c_str());
  7725. fflush(stdout);
  7726. return false;
  7727. }
  7728. *value = result;
  7729. return true;
  7730. }
  7731. // Reads and returns the Boolean environment variable corresponding to
  7732. // the given flag; if it's not set, returns default_value.
  7733. //
  7734. // The value is considered true iff it's not "0".
  7735. bool BoolFromGTestEnv(const char* flag, bool default_value) {
  7736. const std::string env_var = FlagToEnvVar(flag);
  7737. const char* const string_value = posix::GetEnv(env_var.c_str());
  7738. return string_value == NULL ?
  7739. default_value : strcmp(string_value, "0") != 0;
  7740. }
  7741. // Reads and returns a 32-bit integer stored in the environment
  7742. // variable corresponding to the given flag; if it isn't set or
  7743. // doesn't represent a valid 32-bit integer, returns default_value.
  7744. Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) {
  7745. const std::string env_var = FlagToEnvVar(flag);
  7746. const char* const string_value = posix::GetEnv(env_var.c_str());
  7747. if (string_value == NULL) {
  7748. // The environment variable is not set.
  7749. return default_value;
  7750. }
  7751. Int32 result = default_value;
  7752. if (!ParseInt32(Message() << "Environment variable " << env_var,
  7753. string_value, &result)) {
  7754. printf("The default value %s is used.\n",
  7755. (Message() << default_value).GetString().c_str());
  7756. fflush(stdout);
  7757. return default_value;
  7758. }
  7759. return result;
  7760. }
  7761. // Reads and returns the string environment variable corresponding to
  7762. // the given flag; if it's not set, returns default_value.
  7763. const char* StringFromGTestEnv(const char* flag, const char* default_value) {
  7764. const std::string env_var = FlagToEnvVar(flag);
  7765. const char* const value = posix::GetEnv(env_var.c_str());
  7766. return value == NULL ? default_value : value;
  7767. }
  7768. } // namespace internal
  7769. } // namespace testing
  7770. // Copyright 2007, Google Inc.
  7771. // All rights reserved.
  7772. //
  7773. // Redistribution and use in source and binary forms, with or without
  7774. // modification, are permitted provided that the following conditions are
  7775. // met:
  7776. //
  7777. // * Redistributions of source code must retain the above copyright
  7778. // notice, this list of conditions and the following disclaimer.
  7779. // * Redistributions in binary form must reproduce the above
  7780. // copyright notice, this list of conditions and the following disclaimer
  7781. // in the documentation and/or other materials provided with the
  7782. // distribution.
  7783. // * Neither the name of Google Inc. nor the names of its
  7784. // contributors may be used to endorse or promote products derived from
  7785. // this software without specific prior written permission.
  7786. //
  7787. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  7788. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  7789. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  7790. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7791. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  7792. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  7793. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  7794. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  7795. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  7796. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  7797. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  7798. //
  7799. // Author: wan@google.com (Zhanyong Wan)
  7800. // Google Test - The Google C++ Testing Framework
  7801. //
  7802. // This file implements a universal value printer that can print a
  7803. // value of any type T:
  7804. //
  7805. // void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);
  7806. //
  7807. // It uses the << operator when possible, and prints the bytes in the
  7808. // object otherwise. A user can override its behavior for a class
  7809. // type Foo by defining either operator<<(::std::ostream&, const Foo&)
  7810. // or void PrintTo(const Foo&, ::std::ostream*) in the namespace that
  7811. // defines Foo.
  7812. #include <ctype.h>
  7813. #include <stdio.h>
  7814. #include <ostream> // NOLINT
  7815. #include <string>
  7816. namespace testing {
  7817. namespace {
  7818. using ::std::ostream;
  7819. // Prints a segment of bytes in the given object.
  7820. void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start,
  7821. size_t count, ostream* os) {
  7822. char text[5] = "";
  7823. for (size_t i = 0; i != count; i++) {
  7824. const size_t j = start + i;
  7825. if (i != 0) {
  7826. // Organizes the bytes into groups of 2 for easy parsing by
  7827. // human.
  7828. if ((j % 2) == 0)
  7829. *os << ' ';
  7830. else
  7831. *os << '-';
  7832. }
  7833. GTEST_SNPRINTF_(text, sizeof(text), "%02X", obj_bytes[j]);
  7834. *os << text;
  7835. }
  7836. }
  7837. // Prints the bytes in the given value to the given ostream.
  7838. void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count,
  7839. ostream* os) {
  7840. // Tells the user how big the object is.
  7841. *os << count << "-byte object <";
  7842. const size_t kThreshold = 132;
  7843. const size_t kChunkSize = 64;
  7844. // If the object size is bigger than kThreshold, we'll have to omit
  7845. // some details by printing only the first and the last kChunkSize
  7846. // bytes.
  7847. // TODO(wan): let the user control the threshold using a flag.
  7848. if (count < kThreshold) {
  7849. PrintByteSegmentInObjectTo(obj_bytes, 0, count, os);
  7850. } else {
  7851. PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os);
  7852. *os << " ... ";
  7853. // Rounds up to 2-byte boundary.
  7854. const size_t resume_pos = (count - kChunkSize + 1)/2*2;
  7855. PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os);
  7856. }
  7857. *os << ">";
  7858. }
  7859. } // namespace
  7860. namespace internal2 {
  7861. // Delegates to PrintBytesInObjectToImpl() to print the bytes in the
  7862. // given object. The delegation simplifies the implementation, which
  7863. // uses the << operator and thus is easier done outside of the
  7864. // ::testing::internal namespace, which contains a << operator that
  7865. // sometimes conflicts with the one in STL.
  7866. void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count,
  7867. ostream* os) {
  7868. PrintBytesInObjectToImpl(obj_bytes, count, os);
  7869. }
  7870. } // namespace internal2
  7871. namespace internal {
  7872. // Depending on the value of a char (or wchar_t), we print it in one
  7873. // of three formats:
  7874. // - as is if it's a printable ASCII (e.g. 'a', '2', ' '),
  7875. // - as a hexidecimal escape sequence (e.g. '\x7F'), or
  7876. // - as a special escape sequence (e.g. '\r', '\n').
  7877. enum CharFormat {
  7878. kAsIs,
  7879. kHexEscape,
  7880. kSpecialEscape
  7881. };
  7882. // Returns true if c is a printable ASCII character. We test the
  7883. // value of c directly instead of calling isprint(), which is buggy on
  7884. // Windows Mobile.
  7885. inline bool IsPrintableAscii(wchar_t c) {
  7886. return 0x20 <= c && c <= 0x7E;
  7887. }
  7888. // Prints a wide or narrow char c as a character literal without the
  7889. // quotes, escaping it when necessary; returns how c was formatted.
  7890. // The template argument UnsignedChar is the unsigned version of Char,
  7891. // which is the type of c.
  7892. template <typename UnsignedChar, typename Char>
  7893. static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {
  7894. switch (static_cast<wchar_t>(c)) {
  7895. case L'\0':
  7896. *os << "\\0";
  7897. break;
  7898. case L'\'':
  7899. *os << "\\'";
  7900. break;
  7901. case L'\\':
  7902. *os << "\\\\";
  7903. break;
  7904. case L'\a':
  7905. *os << "\\a";
  7906. break;
  7907. case L'\b':
  7908. *os << "\\b";
  7909. break;
  7910. case L'\f':
  7911. *os << "\\f";
  7912. break;
  7913. case L'\n':
  7914. *os << "\\n";
  7915. break;
  7916. case L'\r':
  7917. *os << "\\r";
  7918. break;
  7919. case L'\t':
  7920. *os << "\\t";
  7921. break;
  7922. case L'\v':
  7923. *os << "\\v";
  7924. break;
  7925. default:
  7926. if (IsPrintableAscii(c)) {
  7927. *os << static_cast<char>(c);
  7928. return kAsIs;
  7929. } else {
  7930. *os << "\\x" + String::FormatHexInt(static_cast<UnsignedChar>(c));
  7931. return kHexEscape;
  7932. }
  7933. }
  7934. return kSpecialEscape;
  7935. }
  7936. // Prints a wchar_t c as if it's part of a string literal, escaping it when
  7937. // necessary; returns how c was formatted.
  7938. static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) {
  7939. switch (c) {
  7940. case L'\'':
  7941. *os << "'";
  7942. return kAsIs;
  7943. case L'"':
  7944. *os << "\\\"";
  7945. return kSpecialEscape;
  7946. default:
  7947. return PrintAsCharLiteralTo<wchar_t>(c, os);
  7948. }
  7949. }
  7950. // Prints a char c as if it's part of a string literal, escaping it when
  7951. // necessary; returns how c was formatted.
  7952. static CharFormat PrintAsStringLiteralTo(char c, ostream* os) {
  7953. return PrintAsStringLiteralTo(
  7954. static_cast<wchar_t>(static_cast<unsigned char>(c)), os);
  7955. }
  7956. // Prints a wide or narrow character c and its code. '\0' is printed
  7957. // as "'\\0'", other unprintable characters are also properly escaped
  7958. // using the standard C++ escape sequence. The template argument
  7959. // UnsignedChar is the unsigned version of Char, which is the type of c.
  7960. template <typename UnsignedChar, typename Char>
  7961. void PrintCharAndCodeTo(Char c, ostream* os) {
  7962. // First, print c as a literal in the most readable form we can find.
  7963. *os << ((sizeof(c) > 1) ? "L'" : "'");
  7964. const CharFormat format = PrintAsCharLiteralTo<UnsignedChar>(c, os);
  7965. *os << "'";
  7966. // To aid user debugging, we also print c's code in decimal, unless
  7967. // it's 0 (in which case c was printed as '\\0', making the code
  7968. // obvious).
  7969. if (c == 0)
  7970. return;
  7971. *os << " (" << static_cast<int>(c);
  7972. // For more convenience, we print c's code again in hexidecimal,
  7973. // unless c was already printed in the form '\x##' or the code is in
  7974. // [1, 9].
  7975. if (format == kHexEscape || (1 <= c && c <= 9)) {
  7976. // Do nothing.
  7977. } else {
  7978. *os << ", 0x" << String::FormatHexInt(static_cast<UnsignedChar>(c));
  7979. }
  7980. *os << ")";
  7981. }
  7982. void PrintTo(unsigned char c, ::std::ostream* os) {
  7983. PrintCharAndCodeTo<unsigned char>(c, os);
  7984. }
  7985. void PrintTo(signed char c, ::std::ostream* os) {
  7986. PrintCharAndCodeTo<unsigned char>(c, os);
  7987. }
  7988. // Prints a wchar_t as a symbol if it is printable or as its internal
  7989. // code otherwise and also as its code. L'\0' is printed as "L'\\0'".
  7990. void PrintTo(wchar_t wc, ostream* os) {
  7991. PrintCharAndCodeTo<wchar_t>(wc, os);
  7992. }
  7993. // Prints the given array of characters to the ostream. CharType must be either
  7994. // char or wchar_t.
  7995. // The array starts at begin, the length is len, it may include '\0' characters
  7996. // and may not be NUL-terminated.
  7997. template <typename CharType>
  7998. static void PrintCharsAsStringTo(
  7999. const CharType* begin, size_t len, ostream* os) {
  8000. const char* const kQuoteBegin = sizeof(CharType) == 1 ? "\"" : "L\"";
  8001. *os << kQuoteBegin;
  8002. bool is_previous_hex = false;
  8003. for (size_t index = 0; index < len; ++index) {
  8004. const CharType cur = begin[index];
  8005. if (is_previous_hex && IsXDigit(cur)) {
  8006. // Previous character is of '\x..' form and this character can be
  8007. // interpreted as another hexadecimal digit in its number. Break string to
  8008. // disambiguate.
  8009. *os << "\" " << kQuoteBegin;
  8010. }
  8011. is_previous_hex = PrintAsStringLiteralTo(cur, os) == kHexEscape;
  8012. }
  8013. *os << "\"";
  8014. }
  8015. // Prints a (const) char/wchar_t array of 'len' elements, starting at address
  8016. // 'begin'. CharType must be either char or wchar_t.
  8017. template <typename CharType>
  8018. static void UniversalPrintCharArray(
  8019. const CharType* begin, size_t len, ostream* os) {
  8020. // The code
  8021. // const char kFoo[] = "foo";
  8022. // generates an array of 4, not 3, elements, with the last one being '\0'.
  8023. //
  8024. // Therefore when printing a char array, we don't print the last element if
  8025. // it's '\0', such that the output matches the string literal as it's
  8026. // written in the source code.
  8027. if (len > 0 && begin[len - 1] == '\0') {
  8028. PrintCharsAsStringTo(begin, len - 1, os);
  8029. return;
  8030. }
  8031. // If, however, the last element in the array is not '\0', e.g.
  8032. // const char kFoo[] = { 'f', 'o', 'o' };
  8033. // we must print the entire array. We also print a message to indicate
  8034. // that the array is not NUL-terminated.
  8035. PrintCharsAsStringTo(begin, len, os);
  8036. *os << " (no terminating NUL)";
  8037. }
  8038. // Prints a (const) char array of 'len' elements, starting at address 'begin'.
  8039. void UniversalPrintArray(const char* begin, size_t len, ostream* os) {
  8040. UniversalPrintCharArray(begin, len, os);
  8041. }
  8042. // Prints a (const) wchar_t array of 'len' elements, starting at address
  8043. // 'begin'.
  8044. void UniversalPrintArray(const wchar_t* begin, size_t len, ostream* os) {
  8045. UniversalPrintCharArray(begin, len, os);
  8046. }
  8047. // Prints the given C string to the ostream.
  8048. void PrintTo(const char* s, ostream* os) {
  8049. if (s == NULL) {
  8050. *os << "NULL";
  8051. } else {
  8052. *os << ImplicitCast_<const void*>(s) << " pointing to ";
  8053. PrintCharsAsStringTo(s, strlen(s), os);
  8054. }
  8055. }
  8056. // MSVC compiler can be configured to define whar_t as a typedef
  8057. // of unsigned short. Defining an overload for const wchar_t* in that case
  8058. // would cause pointers to unsigned shorts be printed as wide strings,
  8059. // possibly accessing more memory than intended and causing invalid
  8060. // memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when
  8061. // wchar_t is implemented as a native type.
  8062. #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
  8063. // Prints the given wide C string to the ostream.
  8064. void PrintTo(const wchar_t* s, ostream* os) {
  8065. if (s == NULL) {
  8066. *os << "NULL";
  8067. } else {
  8068. *os << ImplicitCast_<const void*>(s) << " pointing to ";
  8069. PrintCharsAsStringTo(s, wcslen(s), os);
  8070. }
  8071. }
  8072. #endif // wchar_t is native
  8073. // Prints a ::string object.
  8074. #if GTEST_HAS_GLOBAL_STRING
  8075. void PrintStringTo(const ::string& s, ostream* os) {
  8076. PrintCharsAsStringTo(s.data(), s.size(), os);
  8077. }
  8078. #endif // GTEST_HAS_GLOBAL_STRING
  8079. void PrintStringTo(const ::std::string& s, ostream* os) {
  8080. PrintCharsAsStringTo(s.data(), s.size(), os);
  8081. }
  8082. // Prints a ::wstring object.
  8083. #if GTEST_HAS_GLOBAL_WSTRING
  8084. void PrintWideStringTo(const ::wstring& s, ostream* os) {
  8085. PrintCharsAsStringTo(s.data(), s.size(), os);
  8086. }
  8087. #endif // GTEST_HAS_GLOBAL_WSTRING
  8088. #if GTEST_HAS_STD_WSTRING
  8089. void PrintWideStringTo(const ::std::wstring& s, ostream* os) {
  8090. PrintCharsAsStringTo(s.data(), s.size(), os);
  8091. }
  8092. #endif // GTEST_HAS_STD_WSTRING
  8093. } // namespace internal
  8094. } // namespace testing
  8095. // Copyright 2008, Google Inc.
  8096. // All rights reserved.
  8097. //
  8098. // Redistribution and use in source and binary forms, with or without
  8099. // modification, are permitted provided that the following conditions are
  8100. // met:
  8101. //
  8102. // * Redistributions of source code must retain the above copyright
  8103. // notice, this list of conditions and the following disclaimer.
  8104. // * Redistributions in binary form must reproduce the above
  8105. // copyright notice, this list of conditions and the following disclaimer
  8106. // in the documentation and/or other materials provided with the
  8107. // distribution.
  8108. // * Neither the name of Google Inc. nor the names of its
  8109. // contributors may be used to endorse or promote products derived from
  8110. // this software without specific prior written permission.
  8111. //
  8112. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  8113. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  8114. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  8115. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  8116. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  8117. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  8118. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  8119. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  8120. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  8121. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  8122. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  8123. //
  8124. // Author: mheule@google.com (Markus Heule)
  8125. //
  8126. // The Google C++ Testing Framework (Google Test)
  8127. // Indicates that this translation unit is part of Google Test's
  8128. // implementation. It must come before gtest-internal-inl.h is
  8129. // included, or there will be a compiler error. This trick is to
  8130. // prevent a user from accidentally including gtest-internal-inl.h in
  8131. // his code.
  8132. #define GTEST_IMPLEMENTATION_ 1
  8133. #undef GTEST_IMPLEMENTATION_
  8134. namespace testing {
  8135. using internal::GetUnitTestImpl;
  8136. // Gets the summary of the failure message by omitting the stack trace
  8137. // in it.
  8138. std::string TestPartResult::ExtractSummary(const char* message) {
  8139. const char* const stack_trace = strstr(message, internal::kStackTraceMarker);
  8140. return stack_trace == NULL ? message :
  8141. std::string(message, stack_trace);
  8142. }
  8143. // Prints a TestPartResult object.
  8144. std::ostream& operator<<(std::ostream& os, const TestPartResult& result) {
  8145. return os
  8146. << result.file_name() << ":" << result.line_number() << ": "
  8147. << (result.type() == TestPartResult::kSuccess ? "Success" :
  8148. result.type() == TestPartResult::kFatalFailure ? "Fatal failure" :
  8149. "Non-fatal failure") << ":\n"
  8150. << result.message() << std::endl;
  8151. }
  8152. // Appends a TestPartResult to the array.
  8153. void TestPartResultArray::Append(const TestPartResult& result) {
  8154. array_.push_back(result);
  8155. }
  8156. // Returns the TestPartResult at the given index (0-based).
  8157. const TestPartResult& TestPartResultArray::GetTestPartResult(int index) const {
  8158. if (index < 0 || index >= size()) {
  8159. printf("\nInvalid index (%d) into TestPartResultArray.\n", index);
  8160. internal::posix::Abort();
  8161. }
  8162. return array_[index];
  8163. }
  8164. // Returns the number of TestPartResult objects in the array.
  8165. int TestPartResultArray::size() const {
  8166. return static_cast<int>(array_.size());
  8167. }
  8168. namespace internal {
  8169. HasNewFatalFailureHelper::HasNewFatalFailureHelper()
  8170. : has_new_fatal_failure_(false),
  8171. original_reporter_(GetUnitTestImpl()->
  8172. GetTestPartResultReporterForCurrentThread()) {
  8173. GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this);
  8174. }
  8175. HasNewFatalFailureHelper::~HasNewFatalFailureHelper() {
  8176. GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(
  8177. original_reporter_);
  8178. }
  8179. void HasNewFatalFailureHelper::ReportTestPartResult(
  8180. const TestPartResult& result) {
  8181. if (result.fatally_failed())
  8182. has_new_fatal_failure_ = true;
  8183. original_reporter_->ReportTestPartResult(result);
  8184. }
  8185. } // namespace internal
  8186. } // namespace testing
  8187. // Copyright 2008 Google Inc.
  8188. // All Rights Reserved.
  8189. //
  8190. // Redistribution and use in source and binary forms, with or without
  8191. // modification, are permitted provided that the following conditions are
  8192. // met:
  8193. //
  8194. // * Redistributions of source code must retain the above copyright
  8195. // notice, this list of conditions and the following disclaimer.
  8196. // * Redistributions in binary form must reproduce the above
  8197. // copyright notice, this list of conditions and the following disclaimer
  8198. // in the documentation and/or other materials provided with the
  8199. // distribution.
  8200. // * Neither the name of Google Inc. nor the names of its
  8201. // contributors may be used to endorse or promote products derived from
  8202. // this software without specific prior written permission.
  8203. //
  8204. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  8205. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  8206. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  8207. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  8208. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  8209. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  8210. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  8211. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  8212. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  8213. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  8214. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  8215. //
  8216. // Author: wan@google.com (Zhanyong Wan)
  8217. namespace testing {
  8218. namespace internal {
  8219. #if GTEST_HAS_TYPED_TEST_P
  8220. // Skips to the first non-space char in str. Returns an empty string if str
  8221. // contains only whitespace characters.
  8222. static const char* SkipSpaces(const char* str) {
  8223. while (IsSpace(*str))
  8224. str++;
  8225. return str;
  8226. }
  8227. // Verifies that registered_tests match the test names in
  8228. // defined_test_names_; returns registered_tests if successful, or
  8229. // aborts the program otherwise.
  8230. const char* TypedTestCasePState::VerifyRegisteredTestNames(
  8231. const char* file, int line, const char* registered_tests) {
  8232. typedef ::std::set<const char*>::const_iterator DefinedTestIter;
  8233. registered_ = true;
  8234. // Skip initial whitespace in registered_tests since some
  8235. // preprocessors prefix stringizied literals with whitespace.
  8236. registered_tests = SkipSpaces(registered_tests);
  8237. Message errors;
  8238. ::std::set<std::string> tests;
  8239. for (const char* names = registered_tests; names != NULL;
  8240. names = SkipComma(names)) {
  8241. const std::string name = GetPrefixUntilComma(names);
  8242. if (tests.count(name) != 0) {
  8243. errors << "Test " << name << " is listed more than once.\n";
  8244. continue;
  8245. }
  8246. bool found = false;
  8247. for (DefinedTestIter it = defined_test_names_.begin();
  8248. it != defined_test_names_.end();
  8249. ++it) {
  8250. if (name == *it) {
  8251. found = true;
  8252. break;
  8253. }
  8254. }
  8255. if (found) {
  8256. tests.insert(name);
  8257. } else {
  8258. errors << "No test named " << name
  8259. << " can be found in this test case.\n";
  8260. }
  8261. }
  8262. for (DefinedTestIter it = defined_test_names_.begin();
  8263. it != defined_test_names_.end();
  8264. ++it) {
  8265. if (tests.count(*it) == 0) {
  8266. errors << "You forgot to list test " << *it << ".\n";
  8267. }
  8268. }
  8269. const std::string& errors_str = errors.GetString();
  8270. if (errors_str != "") {
  8271. fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
  8272. errors_str.c_str());
  8273. fflush(stderr);
  8274. posix::Abort();
  8275. }
  8276. return registered_tests;
  8277. }
  8278. #endif // GTEST_HAS_TYPED_TEST_P
  8279. } // namespace internal
  8280. } // namespace testing