gtest-internal.h 46 KB

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