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.

1226 lines
46 KiB

  1. // Copyright 2005, Google Inc.
  2. // All rights reserved.
  3. //
  4. // Redistribution and use in source and binary forms, with or without
  5. // modification, are permitted provided that the following conditions are
  6. // met:
  7. //
  8. // * Redistributions of source code must retain the above copyright
  9. // notice, this list of conditions and the following disclaimer.
  10. // * Redistributions in binary form must reproduce the above
  11. // copyright notice, this list of conditions and the following disclaimer
  12. // in the documentation and/or other materials provided with the
  13. // distribution.
  14. // * Neither the name of Google Inc. nor the names of its
  15. // contributors may be used to endorse or promote products derived from
  16. // this software without specific prior written permission.
  17. //
  18. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  22. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  23. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  24. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  25. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  26. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  28. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. //
  30. // Authors: wan@google.com (Zhanyong Wan), eefacm@gmail.com (Sean Mcafee)
  31. //
  32. // The Google C++ Testing Framework (Google Test)
  33. //
  34. // This header file declares functions and macros used internally by
  35. // Google Test. They are subject to change without notice.
  36. #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
  37. #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
  38. #include "gtest/internal/gtest-port.h"
  39. #if GTEST_OS_LINUX
  40. # include <stdlib.h>
  41. # include <sys/types.h>
  42. # include <sys/wait.h>
  43. # include <unistd.h>
  44. #endif // GTEST_OS_LINUX
  45. #include <ctype.h>
  46. #include <string.h>
  47. #include <iomanip>
  48. #include <limits>
  49. #include <set>
  50. #include "gtest/internal/gtest-string.h"
  51. #include "gtest/internal/gtest-filepath.h"
  52. #include "gtest/internal/gtest-type-util.h"
  53. // Due to C++ preprocessor weirdness, we need double indirection to
  54. // concatenate two tokens when one of them is __LINE__. Writing
  55. //
  56. // foo ## __LINE__
  57. //
  58. // will result in the token foo__LINE__, instead of foo followed by
  59. // the current line number. For more details, see
  60. // http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.6
  61. #define GTEST_CONCAT_TOKEN_(foo, bar) GTEST_CONCAT_TOKEN_IMPL_(foo, bar)
  62. #define GTEST_CONCAT_TOKEN_IMPL_(foo, bar) foo ## bar
  63. // Google Test defines the testing::Message class to allow construction of
  64. // test messages via the << operator. The idea is that anything
  65. // streamable to std::ostream can be streamed to a testing::Message.
  66. // This allows a user to use his own types in Google Test assertions by
  67. // overloading the << operator.
  68. //
  69. // util/gtl/stl_logging-inl.h overloads << for STL containers. These
  70. // overloads cannot be defined in the std namespace, as that will be
  71. // undefined behavior. Therefore, they are defined in the global
  72. // namespace instead.
  73. //
  74. // C++'s symbol lookup rule (i.e. Koenig lookup) says that these
  75. // overloads are visible in either the std namespace or the global
  76. // namespace, but not other namespaces, including the testing
  77. // namespace which Google Test's Message class is in.
  78. //
  79. // To allow STL containers (and other types that has a << operator
  80. // defined in the global namespace) to be used in Google Test assertions,
  81. // testing::Message must access the custom << operator from the global
  82. // namespace. Hence this helper function.
  83. //
  84. // Note: Jeffrey Yasskin suggested an alternative fix by "using
  85. // ::operator<<;" in the definition of Message's operator<<. That fix
  86. // doesn't require a helper function, but unfortunately doesn't
  87. // compile with MSVC.
  88. template <typename T>
  89. inline void GTestStreamToHelper(std::ostream* os, const T& val) {
  90. *os << val;
  91. }
  92. class ProtocolMessage;
  93. namespace proto2 { class Message; }
  94. namespace testing {
  95. // Forward declarations.
  96. class AssertionResult; // Result of an assertion.
  97. class Message; // Represents a failure message.
  98. class Test; // Represents a test.
  99. class TestInfo; // Information about a test.
  100. class TestPartResult; // Result of a test part.
  101. class UnitTest; // A collection of test cases.
  102. template <typename T>
  103. ::std::string PrintToString(const T& value);
  104. namespace internal {
  105. struct TraceInfo; // Information about a trace point.
  106. class ScopedTrace; // Implements scoped trace.
  107. class TestInfoImpl; // Opaque implementation of TestInfo
  108. class UnitTestImpl; // Opaque implementation of UnitTest
  109. // How many times InitGoogleTest() has been called.
  110. extern int g_init_gtest_count;
  111. // The text used in failure messages to indicate the start of the
  112. // stack trace.
  113. GTEST_API_ extern const char kStackTraceMarker[];
  114. // A secret type that Google Test users don't know about. It has no
  115. // definition on purpose. Therefore it's impossible to create a
  116. // Secret object, which is what we want.
  117. class Secret;
  118. // Two overloaded helpers for checking at compile time whether an
  119. // expression is a null pointer literal (i.e. NULL or any 0-valued
  120. // compile-time integral constant). Their return values have
  121. // different sizes, so we can use sizeof() to test which version is
  122. // picked by the compiler. These helpers have no implementations, as
  123. // we only need their signatures.
  124. //
  125. // Given IsNullLiteralHelper(x), the compiler will pick the first
  126. // version if x can be implicitly converted to Secret*, and pick the
  127. // second version otherwise. Since Secret is a secret and incomplete
  128. // type, the only expression a user can write that has type Secret* is
  129. // a null pointer literal. Therefore, we know that x is a null
  130. // pointer literal if and only if the first version is picked by the
  131. // compiler.
  132. char IsNullLiteralHelper(Secret* p);
  133. char (&IsNullLiteralHelper(...))[2]; // NOLINT
  134. // A compile-time bool constant that is true if and only if x is a
  135. // null pointer literal (i.e. NULL or any 0-valued compile-time
  136. // integral constant).
  137. #ifdef GTEST_ELLIPSIS_NEEDS_POD_
  138. // We lose support for NULL detection where the compiler doesn't like
  139. // passing non-POD classes through ellipsis (...).
  140. # define GTEST_IS_NULL_LITERAL_(x) false
  141. #else
  142. # define GTEST_IS_NULL_LITERAL_(x) \
  143. (sizeof(::testing::internal::IsNullLiteralHelper(x)) == 1)
  144. #endif // GTEST_ELLIPSIS_NEEDS_POD_
  145. // Appends the user-supplied message to the Google-Test-generated message.
  146. GTEST_API_ String AppendUserMessage(const String& gtest_msg,
  147. const Message& user_msg);
  148. // A helper class for creating scoped traces in user programs.
  149. class GTEST_API_ ScopedTrace {
  150. public:
  151. // The c'tor pushes the given source file location and message onto
  152. // a trace stack maintained by Google Test.
  153. ScopedTrace(const char* file, int line, const Message& message);
  154. // The d'tor pops the info pushed by the c'tor.
  155. //
  156. // Note that the d'tor is not virtual in order to be efficient.
  157. // Don't inherit from ScopedTrace!
  158. ~ScopedTrace();
  159. private:
  160. GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedTrace);
  161. } GTEST_ATTRIBUTE_UNUSED_; // A ScopedTrace object does its job in its
  162. // c'tor and d'tor. Therefore it doesn't
  163. // need to be used otherwise.
  164. // Converts a streamable value to a String. A NULL pointer is
  165. // converted to "(null)". When the input value is a ::string,
  166. // ::std::string, ::wstring, or ::std::wstring object, each NUL
  167. // character in it is replaced with "\\0".
  168. // Declared here but defined in gtest.h, so that it has access
  169. // to the definition of the Message class, required by the ARM
  170. // compiler.
  171. template <typename T>
  172. String StreamableToString(const T& streamable);
  173. // The Symbian compiler has a bug that prevents it from selecting the
  174. // correct overload of FormatForComparisonFailureMessage (see below)
  175. // unless we pass the first argument by reference. If we do that,
  176. // however, Visual Age C++ 10.1 generates a compiler error. Therefore
  177. // we only apply the work-around for Symbian.
  178. #if defined(__SYMBIAN32__)
  179. # define GTEST_CREF_WORKAROUND_ const&
  180. #else
  181. # define GTEST_CREF_WORKAROUND_
  182. #endif
  183. // When this operand is a const char* or char*, if the other operand
  184. // is a ::std::string or ::string, we print this operand as a C string
  185. // rather than a pointer (we do the same for wide strings); otherwise
  186. // we print it as a pointer to be safe.
  187. // This internal macro is used to avoid duplicated code.
  188. #define GTEST_FORMAT_IMPL_(operand2_type, operand1_printer)\
  189. inline String FormatForComparisonFailureMessage(\
  190. operand2_type::value_type* GTEST_CREF_WORKAROUND_ str, \
  191. const operand2_type& /*operand2*/) {\
  192. return operand1_printer(str);\
  193. }\
  194. inline String FormatForComparisonFailureMessage(\
  195. const operand2_type::value_type* GTEST_CREF_WORKAROUND_ str, \
  196. const operand2_type& /*operand2*/) {\
  197. return operand1_printer(str);\
  198. }
  199. GTEST_FORMAT_IMPL_(::std::string, String::ShowCStringQuoted)
  200. #if GTEST_HAS_STD_WSTRING
  201. GTEST_FORMAT_IMPL_(::std::wstring, String::ShowWideCStringQuoted)
  202. #endif // GTEST_HAS_STD_WSTRING
  203. #if GTEST_HAS_GLOBAL_STRING
  204. GTEST_FORMAT_IMPL_(::string, String::ShowCStringQuoted)
  205. #endif // GTEST_HAS_GLOBAL_STRING
  206. #if GTEST_HAS_GLOBAL_WSTRING
  207. GTEST_FORMAT_IMPL_(::wstring, String::ShowWideCStringQuoted)
  208. #endif // GTEST_HAS_GLOBAL_WSTRING
  209. #undef GTEST_FORMAT_IMPL_
  210. // The next four overloads handle the case where the operand being
  211. // printed is a char/wchar_t pointer and the other operand is not a
  212. // string/wstring object. In such cases, we just print the operand as
  213. // a pointer to be safe.
  214. #define GTEST_FORMAT_CHAR_PTR_IMPL_(CharType) \
  215. template <typename T> \
  216. String FormatForComparisonFailureMessage(CharType* GTEST_CREF_WORKAROUND_ p, \
  217. const T&) { \
  218. return PrintToString(static_cast<const void*>(p)); \
  219. }
  220. GTEST_FORMAT_CHAR_PTR_IMPL_(char)
  221. GTEST_FORMAT_CHAR_PTR_IMPL_(const char)
  222. GTEST_FORMAT_CHAR_PTR_IMPL_(wchar_t)
  223. GTEST_FORMAT_CHAR_PTR_IMPL_(const wchar_t)
  224. #undef GTEST_FORMAT_CHAR_PTR_IMPL_
  225. // Constructs and returns the message for an equality assertion
  226. // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
  227. //
  228. // The first four parameters are the expressions used in the assertion
  229. // and their values, as strings. For example, for ASSERT_EQ(foo, bar)
  230. // where foo is 5 and bar is 6, we have:
  231. //
  232. // expected_expression: "foo"
  233. // actual_expression: "bar"
  234. // expected_value: "5"
  235. // actual_value: "6"
  236. //
  237. // The ignoring_case parameter is true iff the assertion is a
  238. // *_STRCASEEQ*. When it's true, the string " (ignoring case)" will
  239. // be inserted into the message.
  240. GTEST_API_ AssertionResult EqFailure(const char* expected_expression,
  241. const char* actual_expression,
  242. const String& expected_value,
  243. const String& actual_value,
  244. bool ignoring_case);
  245. // Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
  246. GTEST_API_ String GetBoolAssertionFailureMessage(
  247. const AssertionResult& assertion_result,
  248. const char* expression_text,
  249. const char* actual_predicate_value,
  250. const char* expected_predicate_value);
  251. // This template class represents an IEEE floating-point number
  252. // (either single-precision or double-precision, depending on the
  253. // template parameters).
  254. //
  255. // The purpose of this class is to do more sophisticated number
  256. // comparison. (Due to round-off error, etc, it's very unlikely that
  257. // two floating-points will be equal exactly. Hence a naive
  258. // comparison by the == operation often doesn't work.)
  259. //
  260. // Format of IEEE floating-point:
  261. //
  262. // The most-significant bit being the leftmost, an IEEE
  263. // floating-point looks like
  264. //
  265. // sign_bit exponent_bits fraction_bits
  266. //
  267. // Here, sign_bit is a single bit that designates the sign of the
  268. // number.
  269. //
  270. // For float, there are 8 exponent bits and 23 fraction bits.
  271. //
  272. // For double, there are 11 exponent bits and 52 fraction bits.
  273. //
  274. // More details can be found at
  275. // http://en.wikipedia.org/wiki/IEEE_floating-point_standard.
  276. //
  277. // Template parameter:
  278. //
  279. // RawType: the raw floating-point type (either float or double)
  280. template <typename RawType>
  281. class FloatingPoint {
  282. public:
  283. // Defines the unsigned integer type that has the same size as the
  284. // floating point number.
  285. typedef typename TypeWithSize<sizeof(RawType)>::UInt Bits;
  286. // Constants.
  287. // # of bits in a number.
  288. static const size_t kBitCount = 8*sizeof(RawType);
  289. // # of fraction bits in a number.
  290. static const size_t kFractionBitCount =
  291. std::numeric_limits<RawType>::digits - 1;
  292. // # of exponent bits in a number.
  293. static const size_t kExponentBitCount = kBitCount - 1 - kFractionBitCount;
  294. // The mask for the sign bit.
  295. static const Bits kSignBitMask = static_cast<Bits>(1) << (kBitCount - 1);
  296. // The mask for the fraction bits.
  297. static const Bits kFractionBitMask =
  298. ~static_cast<Bits>(0) >> (kExponentBitCount + 1);
  299. // The mask for the exponent bits.
  300. static const Bits kExponentBitMask = ~(kSignBitMask | kFractionBitMask);
  301. // How many ULP's (Units in the Last Place) we want to tolerate when
  302. // comparing two numbers. The larger the value, the more error we
  303. // allow. A 0 value means that two numbers must be exactly the same
  304. // to be considered equal.
  305. //
  306. // The maximum error of a single floating-point operation is 0.5
  307. // units in the last place. On Intel CPU's, all floating-point
  308. // calculations are done with 80-bit precision, while double has 64
  309. // bits. Therefore, 4 should be enough for ordinary use.
  310. //
  311. // See the following article for more details on ULP:
  312. // http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm.
  313. static const size_t kMaxUlps = 4;
  314. // Constructs a FloatingPoint from a raw floating-point number.
  315. //
  316. // On an Intel CPU, passing a non-normalized NAN (Not a Number)
  317. // around may change its bits, although the new value is guaranteed
  318. // to be also a NAN. Therefore, don't expect this constructor to
  319. // preserve the bits in x when x is a NAN.
  320. explicit FloatingPoint(const RawType& x) { u_.value_ = x; }
  321. // Static methods
  322. // Reinterprets a bit pattern as a floating-point number.
  323. //
  324. // This function is needed to test the AlmostEquals() method.
  325. static RawType ReinterpretBits(const Bits bits) {
  326. FloatingPoint fp(0);
  327. fp.u_.bits_ = bits;
  328. return fp.u_.value_;
  329. }
  330. // Returns the floating-point number that represent positive infinity.
  331. static RawType Infinity() {
  332. return ReinterpretBits(kExponentBitMask);
  333. }
  334. // Non-static methods
  335. // Returns the bits that represents this number.
  336. const Bits &bits() const { return u_.bits_; }
  337. // Returns the exponent bits of this number.
  338. Bits exponent_bits() const { return kExponentBitMask & u_.bits_; }
  339. // Returns the fraction bits of this number.
  340. Bits fraction_bits() const { return kFractionBitMask & u_.bits_; }
  341. // Returns the sign bit of this number.
  342. Bits sign_bit() const { return kSignBitMask & u_.bits_; }
  343. // Returns true iff this is NAN (not a number).
  344. bool is_nan() const {
  345. // It's a NAN if the exponent bits are all ones and the fraction
  346. // bits are not entirely zeros.
  347. return (exponent_bits() == kExponentBitMask) && (fraction_bits() != 0);
  348. }
  349. // Returns true iff this number is at most kMaxUlps ULP's away from
  350. // rhs. In particular, this function:
  351. //
  352. // - returns false if either number is (or both are) NAN.
  353. // - treats really large numbers as almost equal to infinity.
  354. // - thinks +0.0 and -0.0 are 0 DLP's apart.
  355. bool AlmostEquals(const FloatingPoint& rhs) const {
  356. // The IEEE standard says that any comparison operation involving
  357. // a NAN must return false.
  358. if (is_nan() || rhs.is_nan()) return false;
  359. return DistanceBetweenSignAndMagnitudeNumbers(u_.bits_, rhs.u_.bits_)
  360. <= kMaxUlps;
  361. }
  362. private:
  363. // The data type used to store the actual floating-point number.
  364. union FloatingPointUnion {
  365. RawType value_; // The raw floating-point number.
  366. Bits bits_; // The bits that represent the number.
  367. };
  368. // Converts an integer from the sign-and-magnitude representation to
  369. // the biased representation. More precisely, let N be 2 to the
  370. // power of (kBitCount - 1), an integer x is represented by the
  371. // unsigned number x + N.
  372. //
  373. // For instance,
  374. //
  375. // -N + 1 (the most negative number representable using
  376. // sign-and-magnitude) is represented by 1;
  377. // 0 is represented by N; and
  378. // N - 1 (the biggest number representable using
  379. // sign-and-magnitude) is represented by 2N - 1.
  380. //
  381. // Read http://en.wikipedia.org/wiki/Signed_number_representations
  382. // for more details on signed number representations.
  383. static Bits SignAndMagnitudeToBiased(const Bits &sam) {
  384. if (kSignBitMask & sam) {
  385. // sam represents a negative number.
  386. return ~sam + 1;
  387. } else {
  388. // sam represents a positive number.
  389. return kSignBitMask | sam;
  390. }
  391. }
  392. // Given two numbers in the sign-and-magnitude representation,
  393. // returns the distance between them as an unsigned number.
  394. static Bits DistanceBetweenSignAndMagnitudeNumbers(const Bits &sam1,
  395. const Bits &sam2) {
  396. const Bits biased1 = SignAndMagnitudeToBiased(sam1);
  397. const Bits biased2 = SignAndMagnitudeToBiased(sam2);
  398. return (biased1 >= biased2) ? (biased1 - biased2) : (biased2 - biased1);
  399. }
  400. FloatingPointUnion u_;
  401. };
  402. // Typedefs the instances of the FloatingPoint template class that we
  403. // care to use.
  404. typedef FloatingPoint<float> Float;
  405. typedef FloatingPoint<double> Double;
  406. // In order to catch the mistake of putting tests that use different
  407. // test fixture classes in the same test case, we need to assign
  408. // unique IDs to fixture classes and compare them. The TypeId type is
  409. // used to hold such IDs. The user should treat TypeId as an opaque
  410. // type: the only operation allowed on TypeId values is to compare
  411. // them for equality using the == operator.
  412. typedef const void* TypeId;
  413. template <typename T>
  414. class TypeIdHelper {
  415. public:
  416. // dummy_ must not have a const type. Otherwise an overly eager
  417. // compiler (e.g. MSVC 7.1 & 8.0) may try to merge
  418. // TypeIdHelper<T>::dummy_ for different Ts as an "optimization".
  419. static bool dummy_;
  420. };
  421. template <typename T>
  422. bool TypeIdHelper<T>::dummy_ = false;
  423. // GetTypeId<T>() returns the ID of type T. Different values will be
  424. // returned for different types. Calling the function twice with the
  425. // same type argument is guaranteed to return the same ID.
  426. template <typename T>
  427. TypeId GetTypeId() {
  428. // The compiler is required to allocate a different
  429. // TypeIdHelper<T>::dummy_ variable for each T used to instantiate
  430. // the template. Therefore, the address of dummy_ is guaranteed to
  431. // be unique.
  432. return &(TypeIdHelper<T>::dummy_);
  433. }
  434. // Returns the type ID of ::testing::Test. Always call this instead
  435. // of GetTypeId< ::testing::Test>() to get the type ID of
  436. // ::testing::Test, as the latter may give the wrong result due to a
  437. // suspected linker bug when compiling Google Test as a Mac OS X
  438. // framework.
  439. GTEST_API_ TypeId GetTestTypeId();
  440. // Defines the abstract factory interface that creates instances
  441. // of a Test object.
  442. class TestFactoryBase {
  443. public:
  444. virtual ~TestFactoryBase() {}
  445. // Creates a test instance to run. The instance is both created and destroyed
  446. // within TestInfoImpl::Run()
  447. virtual Test* CreateTest() = 0;
  448. protected:
  449. TestFactoryBase() {}
  450. private:
  451. GTEST_DISALLOW_COPY_AND_ASSIGN_(TestFactoryBase);
  452. };
  453. // This class provides implementation of TeastFactoryBase interface.
  454. // It is used in TEST and TEST_F macros.
  455. template <class TestClass>
  456. class TestFactoryImpl : public TestFactoryBase {
  457. public:
  458. virtual Test* CreateTest() { return new TestClass; }
  459. };
  460. #if GTEST_OS_WINDOWS
  461. // Predicate-formatters for implementing the HRESULT checking macros
  462. // {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED}
  463. // We pass a long instead of HRESULT to avoid causing an
  464. // include dependency for the HRESULT type.
  465. GTEST_API_ AssertionResult IsHRESULTSuccess(const char* expr,
  466. long hr); // NOLINT
  467. GTEST_API_ AssertionResult IsHRESULTFailure(const char* expr,
  468. long hr); // NOLINT
  469. #endif // GTEST_OS_WINDOWS
  470. // Types of SetUpTestCase() and TearDownTestCase() functions.
  471. typedef void (*SetUpTestCaseFunc)();
  472. typedef void (*TearDownTestCaseFunc)();
  473. // Creates a new TestInfo object and registers it with Google Test;
  474. // returns the created object.
  475. //
  476. // Arguments:
  477. //
  478. // test_case_name: name of the test case
  479. // name: name of the test
  480. // type_param the name of the test's type parameter, or NULL if
  481. // this is not a typed or a type-parameterized test.
  482. // value_param text representation of the test's value parameter,
  483. // or NULL if this is not a type-parameterized test.
  484. // fixture_class_id: ID of the test fixture class
  485. // set_up_tc: pointer to the function that sets up the test case
  486. // tear_down_tc: pointer to the function that tears down the test case
  487. // factory: pointer to the factory that creates a test object.
  488. // The newly created TestInfo instance will assume
  489. // ownership of the factory object.
  490. GTEST_API_ TestInfo* MakeAndRegisterTestInfo(
  491. const char* test_case_name, const char* name,
  492. const char* type_param,
  493. const char* value_param,
  494. TypeId fixture_class_id,
  495. SetUpTestCaseFunc set_up_tc,
  496. TearDownTestCaseFunc tear_down_tc,
  497. TestFactoryBase* factory);
  498. // If *pstr starts with the given prefix, modifies *pstr to be right
  499. // past the prefix and returns true; otherwise leaves *pstr unchanged
  500. // and returns false. None of pstr, *pstr, and prefix can be NULL.
  501. GTEST_API_ bool SkipPrefix(const char* prefix, const char** pstr);
  502. #if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P
  503. // State of the definition of a type-parameterized test case.
  504. class GTEST_API_ TypedTestCasePState {
  505. public:
  506. TypedTestCasePState() : registered_(false) {}
  507. // Adds the given test name to defined_test_names_ and return true
  508. // if the test case hasn't been registered; otherwise aborts the
  509. // program.
  510. bool AddTestName(const char* file, int line, const char* case_name,
  511. const char* test_name) {
  512. if (registered_) {
  513. fprintf(stderr, "%s Test %s must be defined before "
  514. "REGISTER_TYPED_TEST_CASE_P(%s, ...).\n",
  515. FormatFileLocation(file, line).c_str(), test_name, case_name);
  516. fflush(stderr);
  517. posix::Abort();
  518. }
  519. defined_test_names_.insert(test_name);
  520. return true;
  521. }
  522. // Verifies that registered_tests match the test names in
  523. // defined_test_names_; returns registered_tests if successful, or
  524. // aborts the program otherwise.
  525. const char* VerifyRegisteredTestNames(
  526. const char* file, int line, const char* registered_tests);
  527. private:
  528. bool registered_;
  529. ::std::set<const char*> defined_test_names_;
  530. };
  531. // Skips to the first non-space char after the first comma in 'str';
  532. // returns NULL if no comma is found in 'str'.
  533. inline const char* SkipComma(const char* str) {
  534. const char* comma = strchr(str, ',');
  535. if (comma == NULL) {
  536. return NULL;
  537. }
  538. while (IsSpace(*(++comma))) {}
  539. return comma;
  540. }
  541. // Returns the prefix of 'str' before the first comma in it; returns
  542. // the entire string if it contains no comma.
  543. inline String GetPrefixUntilComma(const char* str) {
  544. const char* comma = strchr(str, ',');
  545. return comma == NULL ? String(str) : String(str, comma - str);
  546. }
  547. // TypeParameterizedTest<Fixture, TestSel, Types>::Register()
  548. // registers a list of type-parameterized tests with Google Test. The
  549. // return value is insignificant - we just need to return something
  550. // such that we can call this function in a namespace scope.
  551. //
  552. // Implementation note: The GTEST_TEMPLATE_ macro declares a template
  553. // template parameter. It's defined in gtest-type-util.h.
  554. template <GTEST_TEMPLATE_ Fixture, class TestSel, typename Types>
  555. class TypeParameterizedTest {
  556. public:
  557. // 'index' is the index of the test in the type list 'Types'
  558. // specified in INSTANTIATE_TYPED_TEST_CASE_P(Prefix, TestCase,
  559. // Types). Valid values for 'index' are [0, N - 1] where N is the
  560. // length of Types.
  561. static bool Register(const char* prefix, const char* case_name,
  562. const char* test_names, int index) {
  563. typedef typename Types::Head Type;
  564. typedef Fixture<Type> FixtureClass;
  565. typedef typename GTEST_BIND_(TestSel, Type) TestClass;
  566. // First, registers the first type-parameterized test in the type
  567. // list.
  568. MakeAndRegisterTestInfo(
  569. String::Format("%s%s%s/%d", prefix, prefix[0] == '\0' ? "" : "/",
  570. case_name, index).c_str(),
  571. GetPrefixUntilComma(test_names).c_str(),
  572. GetTypeName<Type>().c_str(),
  573. NULL, // No value parameter.
  574. GetTypeId<FixtureClass>(),
  575. TestClass::SetUpTestCase,
  576. TestClass::TearDownTestCase,
  577. new TestFactoryImpl<TestClass>);
  578. // Next, recurses (at compile time) with the tail of the type list.
  579. return TypeParameterizedTest<Fixture, TestSel, typename Types::Tail>
  580. ::Register(prefix, case_name, test_names, index + 1);
  581. }
  582. };
  583. // The base case for the compile time recursion.
  584. template <GTEST_TEMPLATE_ Fixture, class TestSel>
  585. class TypeParameterizedTest<Fixture, TestSel, Types0> {
  586. public:
  587. static bool Register(const char* /*prefix*/, const char* /*case_name*/,
  588. const char* /*test_names*/, int /*index*/) {
  589. return true;
  590. }
  591. };
  592. // TypeParameterizedTestCase<Fixture, Tests, Types>::Register()
  593. // registers *all combinations* of 'Tests' and 'Types' with Google
  594. // Test. The return value is insignificant - we just need to return
  595. // something such that we can call this function in a namespace scope.
  596. template <GTEST_TEMPLATE_ Fixture, typename Tests, typename Types>
  597. class TypeParameterizedTestCase {
  598. public:
  599. static bool Register(const char* prefix, const char* case_name,
  600. const char* test_names) {
  601. typedef typename Tests::Head Head;
  602. // First, register the first test in 'Test' for each type in 'Types'.
  603. TypeParameterizedTest<Fixture, Head, Types>::Register(
  604. prefix, case_name, test_names, 0);
  605. // Next, recurses (at compile time) with the tail of the test list.
  606. return TypeParameterizedTestCase<Fixture, typename Tests::Tail, Types>
  607. ::Register(prefix, case_name, SkipComma(test_names));
  608. }
  609. };
  610. // The base case for the compile time recursion.
  611. template <GTEST_TEMPLATE_ Fixture, typename Types>
  612. class TypeParameterizedTestCase<Fixture, Templates0, Types> {
  613. public:
  614. static bool Register(const char* /*prefix*/, const char* /*case_name*/,
  615. const char* /*test_names*/) {
  616. return true;
  617. }
  618. };
  619. #endif // GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P
  620. // Returns the current OS stack trace as a String.
  621. //
  622. // The maximum number of stack frames to be included is specified by
  623. // the gtest_stack_trace_depth flag. The skip_count parameter
  624. // specifies the number of top frames to be skipped, which doesn't
  625. // count against the number of frames to be included.
  626. //
  627. // For example, if Foo() calls Bar(), which in turn calls
  628. // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
  629. // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
  630. GTEST_API_ String GetCurrentOsStackTraceExceptTop(UnitTest* unit_test,
  631. int skip_count);
  632. // Helpers for suppressing warnings on unreachable code or constant
  633. // condition.
  634. // Always returns true.
  635. GTEST_API_ bool AlwaysTrue();
  636. // Always returns false.
  637. inline bool AlwaysFalse() { return !AlwaysTrue(); }
  638. // Helper for suppressing false warning from Clang on a const char*
  639. // variable declared in a conditional expression always being NULL in
  640. // the else branch.
  641. struct GTEST_API_ ConstCharPtr {
  642. ConstCharPtr(const char* str) : value(str) {}
  643. operator bool() const { return true; }
  644. const char* value;
  645. };
  646. // A simple Linear Congruential Generator for generating random
  647. // numbers with a uniform distribution. Unlike rand() and srand(), it
  648. // doesn't use global state (and therefore can't interfere with user
  649. // code). Unlike rand_r(), it's portable. An LCG isn't very random,
  650. // but it's good enough for our purposes.
  651. class GTEST_API_ Random {
  652. public:
  653. static const UInt32 kMaxRange = 1u << 31;
  654. explicit Random(UInt32 seed) : state_(seed) {}
  655. void Reseed(UInt32 seed) { state_ = seed; }
  656. // Generates a random number from [0, range). Crashes if 'range' is
  657. // 0 or greater than kMaxRange.
  658. UInt32 Generate(UInt32 range);
  659. private:
  660. UInt32 state_;
  661. GTEST_DISALLOW_COPY_AND_ASSIGN_(Random);
  662. };
  663. // Defining a variable of type CompileAssertTypesEqual<T1, T2> will cause a
  664. // compiler error iff T1 and T2 are different types.
  665. template <typename T1, typename T2>
  666. struct CompileAssertTypesEqual;
  667. template <typename T>
  668. struct CompileAssertTypesEqual<T, T> {
  669. };
  670. // Removes the reference from a type if it is a reference type,
  671. // otherwise leaves it unchanged. This is the same as
  672. // tr1::remove_reference, which is not widely available yet.
  673. template <typename T>
  674. struct RemoveReference { typedef T type; }; // NOLINT
  675. template <typename T>
  676. struct RemoveReference<T&> { typedef T type; }; // NOLINT
  677. // A handy wrapper around RemoveReference that works when the argument
  678. // T depends on template parameters.
  679. #define GTEST_REMOVE_REFERENCE_(T) \
  680. typename ::testing::internal::RemoveReference<T>::type
  681. // Removes const from a type if it is a const type, otherwise leaves
  682. // it unchanged. This is the same as tr1::remove_const, which is not
  683. // widely available yet.
  684. template <typename T>
  685. struct RemoveConst { typedef T type; }; // NOLINT
  686. template <typename T>
  687. struct RemoveConst<const T> { typedef T type; }; // NOLINT
  688. // MSVC 8.0, Sun C++, and IBM XL C++ have a bug which causes the above
  689. // definition to fail to remove the const in 'const int[3]' and 'const
  690. // char[3][4]'. The following specialization works around the bug.
  691. // However, it causes trouble with GCC and thus needs to be
  692. // conditionally compiled.
  693. #if defined(_MSC_VER) || defined(__SUNPRO_CC) || defined(__IBMCPP__)
  694. template <typename T, size_t N>
  695. struct RemoveConst<const T[N]> {
  696. typedef typename RemoveConst<T>::type type[N];
  697. };
  698. #endif
  699. // A handy wrapper around RemoveConst that works when the argument
  700. // T depends on template parameters.
  701. #define GTEST_REMOVE_CONST_(T) \
  702. typename ::testing::internal::RemoveConst<T>::type
  703. // Turns const U&, U&, const U, and U all into U.
  704. #define GTEST_REMOVE_REFERENCE_AND_CONST_(T) \
  705. GTEST_REMOVE_CONST_(GTEST_REMOVE_REFERENCE_(T))
  706. // Adds reference to a type if it is not a reference type,
  707. // otherwise leaves it unchanged. This is the same as
  708. // tr1::add_reference, which is not widely available yet.
  709. template <typename T>
  710. struct AddReference { typedef T& type; }; // NOLINT
  711. template <typename T>
  712. struct AddReference<T&> { typedef T& type; }; // NOLINT
  713. // A handy wrapper around AddReference that works when the argument T
  714. // depends on template parameters.
  715. #define GTEST_ADD_REFERENCE_(T) \
  716. typename ::testing::internal::AddReference<T>::type
  717. // Adds a reference to const on top of T as necessary. For example,
  718. // it transforms
  719. //
  720. // char ==> const char&
  721. // const char ==> const char&
  722. // char& ==> const char&
  723. // const char& ==> const char&
  724. //
  725. // The argument T must depend on some template parameters.
  726. #define GTEST_REFERENCE_TO_CONST_(T) \
  727. GTEST_ADD_REFERENCE_(const GTEST_REMOVE_REFERENCE_(T))
  728. // ImplicitlyConvertible<From, To>::value is a compile-time bool
  729. // constant that's true iff type From can be implicitly converted to
  730. // type To.
  731. template <typename From, typename To>
  732. class ImplicitlyConvertible {
  733. private:
  734. // We need the following helper functions only for their types.
  735. // They have no implementations.
  736. // MakeFrom() is an expression whose type is From. We cannot simply
  737. // use From(), as the type From may not have a public default
  738. // constructor.
  739. static From MakeFrom();
  740. // These two functions are overloaded. Given an expression
  741. // Helper(x), the compiler will pick the first version if x can be
  742. // implicitly converted to type To; otherwise it will pick the
  743. // second version.
  744. //
  745. // The first version returns a value of size 1, and the second
  746. // version returns a value of size 2. Therefore, by checking the
  747. // size of Helper(x), which can be done at compile time, we can tell
  748. // which version of Helper() is used, and hence whether x can be
  749. // implicitly converted to type To.
  750. static char Helper(To);
  751. static char (&Helper(...))[2]; // NOLINT
  752. // We have to put the 'public' section after the 'private' section,
  753. // or MSVC refuses to compile the code.
  754. public:
  755. // MSVC warns about implicitly converting from double to int for
  756. // possible loss of data, so we need to temporarily disable the
  757. // warning.
  758. #ifdef _MSC_VER
  759. # pragma warning(push) // Saves the current warning state.
  760. # pragma warning(disable:4244) // Temporarily disables warning 4244.
  761. static const bool value =
  762. sizeof(Helper(ImplicitlyConvertible::MakeFrom())) == 1;
  763. # pragma warning(pop) // Restores the warning state.
  764. #elif defined(__BORLANDC__)
  765. // C++Builder cannot use member overload resolution during template
  766. // instantiation. The simplest workaround is to use its C++0x type traits
  767. // functions (C++Builder 2009 and above only).
  768. static const bool value = __is_convertible(From, To);
  769. #else
  770. static const bool value =
  771. sizeof(Helper(ImplicitlyConvertible::MakeFrom())) == 1;
  772. #endif // _MSV_VER
  773. };
  774. template <typename From, typename To>
  775. const bool ImplicitlyConvertible<From, To>::value;
  776. // IsAProtocolMessage<T>::value is a compile-time bool constant that's
  777. // true iff T is type ProtocolMessage, proto2::Message, or a subclass
  778. // of those.
  779. template <typename T>
  780. struct IsAProtocolMessage
  781. : public bool_constant<
  782. ImplicitlyConvertible<const T*, const ::ProtocolMessage*>::value ||
  783. ImplicitlyConvertible<const T*, const ::proto2::Message*>::value> {
  784. };
  785. // When the compiler sees expression IsContainerTest<C>(0), if C is an
  786. // STL-style container class, the first overload of IsContainerTest
  787. // will be viable (since both C::iterator* and C::const_iterator* are
  788. // valid types and NULL can be implicitly converted to them). It will
  789. // be picked over the second overload as 'int' is a perfect match for
  790. // the type of argument 0. If C::iterator or C::const_iterator is not
  791. // a valid type, the first overload is not viable, and the second
  792. // overload will be picked. Therefore, we can determine whether C is
  793. // a container class by checking the type of IsContainerTest<C>(0).
  794. // The value of the expression is insignificant.
  795. //
  796. // Note that we look for both C::iterator and C::const_iterator. The
  797. // reason is that C++ injects the name of a class as a member of the
  798. // class itself (e.g. you can refer to class iterator as either
  799. // 'iterator' or 'iterator::iterator'). If we look for C::iterator
  800. // only, for example, we would mistakenly think that a class named
  801. // iterator is an STL container.
  802. //
  803. // Also note that the simpler approach of overloading
  804. // IsContainerTest(typename C::const_iterator*) and
  805. // IsContainerTest(...) doesn't work with Visual Age C++ and Sun C++.
  806. typedef int IsContainer;
  807. template <class C>
  808. IsContainer IsContainerTest(int /* dummy */,
  809. typename C::iterator* /* it */ = NULL,
  810. typename C::const_iterator* /* const_it */ = NULL) {
  811. return 0;
  812. }
  813. typedef char IsNotContainer;
  814. template <class C>
  815. IsNotContainer IsContainerTest(long /* dummy */) { return '\0'; }
  816. // EnableIf<condition>::type is void when 'Cond' is true, and
  817. // undefined when 'Cond' is false. To use SFINAE to make a function
  818. // overload only apply when a particular expression is true, add
  819. // "typename EnableIf<expression>::type* = 0" as the last parameter.
  820. template<bool> struct EnableIf;
  821. template<> struct EnableIf<true> { typedef void type; }; // NOLINT
  822. // Utilities for native arrays.
  823. // ArrayEq() compares two k-dimensional native arrays using the
  824. // elements' operator==, where k can be any integer >= 0. When k is
  825. // 0, ArrayEq() degenerates into comparing a single pair of values.
  826. template <typename T, typename U>
  827. bool ArrayEq(const T* lhs, size_t size, const U* rhs);
  828. // This generic version is used when k is 0.
  829. template <typename T, typename U>
  830. inline bool ArrayEq(const T& lhs, const U& rhs) { return lhs == rhs; }
  831. // This overload is used when k >= 1.
  832. template <typename T, typename U, size_t N>
  833. inline bool ArrayEq(const T(&lhs)[N], const U(&rhs)[N]) {
  834. return internal::ArrayEq(lhs, N, rhs);
  835. }
  836. // This helper reduces code bloat. If we instead put its logic inside
  837. // the previous ArrayEq() function, arrays with different sizes would
  838. // lead to different copies of the template code.
  839. template <typename T, typename U>
  840. bool ArrayEq(const T* lhs, size_t size, const U* rhs) {
  841. for (size_t i = 0; i != size; i++) {
  842. if (!internal::ArrayEq(lhs[i], rhs[i]))
  843. return false;
  844. }
  845. return true;
  846. }
  847. // Finds the first element in the iterator range [begin, end) that
  848. // equals elem. Element may be a native array type itself.
  849. template <typename Iter, typename Element>
  850. Iter ArrayAwareFind(Iter begin, Iter end, const Element& elem) {
  851. for (Iter it = begin; it != end; ++it) {
  852. if (internal::ArrayEq(*it, elem))
  853. return it;
  854. }
  855. return end;
  856. }
  857. // CopyArray() copies a k-dimensional native array using the elements'
  858. // operator=, where k can be any integer >= 0. When k is 0,
  859. // CopyArray() degenerates into copying a single value.
  860. template <typename T, typename U>
  861. void CopyArray(const T* from, size_t size, U* to);
  862. // This generic version is used when k is 0.
  863. template <typename T, typename U>
  864. inline void CopyArray(const T& from, U* to) { *to = from; }
  865. // This overload is used when k >= 1.
  866. template <typename T, typename U, size_t N>
  867. inline void CopyArray(const T(&from)[N], U(*to)[N]) {
  868. internal::CopyArray(from, N, *to);
  869. }
  870. // This helper reduces code bloat. If we instead put its logic inside
  871. // the previous CopyArray() function, arrays with different sizes
  872. // would lead to different copies of the template code.
  873. template <typename T, typename U>
  874. void CopyArray(const T* from, size_t size, U* to) {
  875. for (size_t i = 0; i != size; i++) {
  876. internal::CopyArray(from[i], to + i);
  877. }
  878. }
  879. // The relation between an NativeArray object (see below) and the
  880. // native array it represents.
  881. enum RelationToSource {
  882. kReference, // The NativeArray references the native array.
  883. kCopy // The NativeArray makes a copy of the native array and
  884. // owns the copy.
  885. };
  886. // Adapts a native array to a read-only STL-style container. Instead
  887. // of the complete STL container concept, this adaptor only implements
  888. // members useful for Google Mock's container matchers. New members
  889. // should be added as needed. To simplify the implementation, we only
  890. // support Element being a raw type (i.e. having no top-level const or
  891. // reference modifier). It's the client's responsibility to satisfy
  892. // this requirement. Element can be an array type itself (hence
  893. // multi-dimensional arrays are supported).
  894. template <typename Element>
  895. class NativeArray {
  896. public:
  897. // STL-style container typedefs.
  898. typedef Element value_type;
  899. typedef Element* iterator;
  900. typedef const Element* const_iterator;
  901. // Constructs from a native array.
  902. NativeArray(const Element* array, size_t count, RelationToSource relation) {
  903. Init(array, count, relation);
  904. }
  905. // Copy constructor.
  906. NativeArray(const NativeArray& rhs) {
  907. Init(rhs.array_, rhs.size_, rhs.relation_to_source_);
  908. }
  909. ~NativeArray() {
  910. // Ensures that the user doesn't instantiate NativeArray with a
  911. // const or reference type.
  912. static_cast<void>(StaticAssertTypeEqHelper<Element,
  913. GTEST_REMOVE_REFERENCE_AND_CONST_(Element)>());
  914. if (relation_to_source_ == kCopy)
  915. delete[] array_;
  916. }
  917. // STL-style container methods.
  918. size_t size() const { return size_; }
  919. const_iterator begin() const { return array_; }
  920. const_iterator end() const { return array_ + size_; }
  921. bool operator==(const NativeArray& rhs) const {
  922. return size() == rhs.size() &&
  923. ArrayEq(begin(), size(), rhs.begin());
  924. }
  925. private:
  926. // Initializes this object; makes a copy of the input array if
  927. // 'relation' is kCopy.
  928. void Init(const Element* array, size_t a_size, RelationToSource relation) {
  929. if (relation == kReference) {
  930. array_ = array;
  931. } else {
  932. Element* const copy = new Element[a_size];
  933. CopyArray(array, a_size, copy);
  934. array_ = copy;
  935. }
  936. size_ = a_size;
  937. relation_to_source_ = relation;
  938. }
  939. const Element* array_;
  940. size_t size_;
  941. RelationToSource relation_to_source_;
  942. GTEST_DISALLOW_ASSIGN_(NativeArray);
  943. };
  944. } // namespace internal
  945. } // namespace testing
  946. #define GTEST_MESSAGE_AT_(file, line, message, result_type) \
  947. ::testing::internal::AssertHelper(result_type, file, line, message) \
  948. = ::testing::Message()
  949. #define GTEST_MESSAGE_(message, result_type) \
  950. GTEST_MESSAGE_AT_(__FILE__, __LINE__, message, result_type)
  951. #define GTEST_FATAL_FAILURE_(message) \
  952. return GTEST_MESSAGE_(message, ::testing::TestPartResult::kFatalFailure)
  953. #define GTEST_NONFATAL_FAILURE_(message) \
  954. GTEST_MESSAGE_(message, ::testing::TestPartResult::kNonFatalFailure)
  955. #define GTEST_SUCCESS_(message) \
  956. GTEST_MESSAGE_(message, ::testing::TestPartResult::kSuccess)
  957. // Suppresses MSVC warnings 4072 (unreachable code) for the code following
  958. // statement if it returns or throws (or doesn't return or throw in some
  959. // situations).
  960. #define GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) \
  961. if (::testing::internal::AlwaysTrue()) { statement; }
  962. #define GTEST_TEST_THROW_(statement, expected_exception, fail) \
  963. GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
  964. if (::testing::internal::ConstCharPtr gtest_msg = "") { \
  965. bool gtest_caught_expected = false; \
  966. try { \
  967. GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
  968. } \
  969. catch (expected_exception const&) { \
  970. gtest_caught_expected = true; \
  971. } \
  972. catch (...) { \
  973. gtest_msg.value = \
  974. "Expected: " #statement " throws an exception of type " \
  975. #expected_exception ".\n Actual: it throws a different type."; \
  976. goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
  977. } \
  978. if (!gtest_caught_expected) { \
  979. gtest_msg.value = \
  980. "Expected: " #statement " throws an exception of type " \
  981. #expected_exception ".\n Actual: it throws nothing."; \
  982. goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
  983. } \
  984. } else \
  985. GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__): \
  986. fail(gtest_msg.value)
  987. #define GTEST_TEST_NO_THROW_(statement, fail) \
  988. GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
  989. if (::testing::internal::AlwaysTrue()) { \
  990. try { \
  991. GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
  992. } \
  993. catch (...) { \
  994. goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \
  995. } \
  996. } else \
  997. GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__): \
  998. fail("Expected: " #statement " doesn't throw an exception.\n" \
  999. " Actual: it throws.")
  1000. #define GTEST_TEST_ANY_THROW_(statement, fail) \
  1001. GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
  1002. if (::testing::internal::AlwaysTrue()) { \
  1003. bool gtest_caught_any = false; \
  1004. try { \
  1005. GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
  1006. } \
  1007. catch (...) { \
  1008. gtest_caught_any = true; \
  1009. } \
  1010. if (!gtest_caught_any) { \
  1011. goto GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__); \
  1012. } \
  1013. } else \
  1014. GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__): \
  1015. fail("Expected: " #statement " throws an exception.\n" \
  1016. " Actual: it doesn't.")
  1017. // Implements Boolean test assertions such as EXPECT_TRUE. expression can be
  1018. // either a boolean expression or an AssertionResult. text is a textual
  1019. // represenation of expression as it was passed into the EXPECT_TRUE.
  1020. #define GTEST_TEST_BOOLEAN_(expression, text, actual, expected, fail) \
  1021. GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
  1022. if (const ::testing::AssertionResult gtest_ar_ = \
  1023. ::testing::AssertionResult(expression)) \
  1024. ; \
  1025. else \
  1026. fail(::testing::internal::GetBoolAssertionFailureMessage(\
  1027. gtest_ar_, text, #actual, #expected).c_str())
  1028. #define GTEST_TEST_NO_FATAL_FAILURE_(statement, fail) \
  1029. GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
  1030. if (::testing::internal::AlwaysTrue()) { \
  1031. ::testing::internal::HasNewFatalFailureHelper gtest_fatal_failure_checker; \
  1032. GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
  1033. if (gtest_fatal_failure_checker.has_new_fatal_failure()) { \
  1034. goto GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__); \
  1035. } \
  1036. } else \
  1037. GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__): \
  1038. fail("Expected: " #statement " doesn't generate new fatal " \
  1039. "failures in the current thread.\n" \
  1040. " Actual: it does.")
  1041. // Expands to the name of the class that implements the given test.
  1042. #define GTEST_TEST_CLASS_NAME_(test_case_name, test_name) \
  1043. test_case_name##_##test_name##_Test
  1044. // Helper macro for defining tests.
  1045. #define GTEST_TEST_(test_case_name, test_name, parent_class, parent_id)\
  1046. class GTEST_TEST_CLASS_NAME_(test_case_name, test_name) : public parent_class {\
  1047. public:\
  1048. GTEST_TEST_CLASS_NAME_(test_case_name, test_name)() {}\
  1049. private:\
  1050. virtual void TestBody();\
  1051. static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_;\
  1052. GTEST_DISALLOW_COPY_AND_ASSIGN_(\
  1053. GTEST_TEST_CLASS_NAME_(test_case_name, test_name));\
  1054. };\
  1055. \
  1056. ::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_case_name, test_name)\
  1057. ::test_info_ =\
  1058. ::testing::internal::MakeAndRegisterTestInfo(\
  1059. #test_case_name, #test_name, NULL, NULL, \
  1060. (parent_id), \
  1061. parent_class::SetUpTestCase, \
  1062. parent_class::TearDownTestCase, \
  1063. new ::testing::internal::TestFactoryImpl<\
  1064. GTEST_TEST_CLASS_NAME_(test_case_name, test_name)>);\
  1065. void GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::TestBody()
  1066. #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_