gtest-internal.h 43 KB

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