/thirdparty/breakpad/third_party/protobuf/protobuf/gtest/include/gtest/internal/gtest-internal.h

http://github.com/tomahawk-player/tomahawk · C++ Header · 923 lines · 439 code · 124 blank · 360 comment · 31 complexity · b5c8b71bffeafaf47006fa90eb19f187 MD5 · raw file

  1. // Copyright 2005, Google Inc.
  2. // All rights reserved.
  3. //
  4. // Redistribution and use in source and binary forms, with or without
  5. // modification, are permitted provided that the following conditions are
  6. // met:
  7. //
  8. // * Redistributions of source code must retain the above copyright
  9. // notice, this list of conditions and the following disclaimer.
  10. // * Redistributions in binary form must reproduce the above
  11. // copyright notice, this list of conditions and the following disclaimer
  12. // in the documentation and/or other materials provided with the
  13. // distribution.
  14. // * Neither the name of Google Inc. nor the names of its
  15. // contributors may be used to endorse or promote products derived from
  16. // this software without specific prior written permission.
  17. //
  18. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  22. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  23. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  24. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  25. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  26. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  28. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. //
  30. // Authors: wan@google.com (Zhanyong Wan), eefacm@gmail.com (Sean Mcafee)
  31. //
  32. // The Google C++ Testing Framework (Google Test)
  33. //
  34. // This header file declares functions and macros used internally by
  35. // Google Test. They are subject to change without notice.
  36. #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
  37. #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
  38. #include <gtest/internal/gtest-port.h>
  39. #if GTEST_OS_LINUX
  40. #include <stdlib.h>
  41. #include <sys/types.h>
  42. #include <sys/wait.h>
  43. #include <unistd.h>
  44. #endif // GTEST_OS_LINUX
  45. #include <ctype.h>
  46. #include <string.h>
  47. #include <iomanip>
  48. #include <limits>
  49. #include <set>
  50. #include <gtest/internal/gtest-string.h>
  51. #include <gtest/internal/gtest-filepath.h>
  52. #include <gtest/internal/gtest-type-util.h>
  53. // Due to C++ preprocessor weirdness, we need double indirection to
  54. // concatenate two tokens when one of them is __LINE__. Writing
  55. //
  56. // foo ## __LINE__
  57. //
  58. // will result in the token foo__LINE__, instead of foo followed by
  59. // the current line number. For more details, see
  60. // http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.6
  61. #define GTEST_CONCAT_TOKEN_(foo, bar) GTEST_CONCAT_TOKEN_IMPL_(foo, bar)
  62. #define GTEST_CONCAT_TOKEN_IMPL_(foo, bar) foo ## bar
  63. // Google Test defines the testing::Message class to allow construction of
  64. // test messages via the << operator. The idea is that anything
  65. // streamable to std::ostream can be streamed to a testing::Message.
  66. // This allows a user to use his own types in Google Test assertions by
  67. // overloading the << operator.
  68. //
  69. // util/gtl/stl_logging-inl.h overloads << for STL containers. These
  70. // overloads cannot be defined in the std namespace, as that will be
  71. // undefined behavior. Therefore, they are defined in the global
  72. // namespace instead.
  73. //
  74. // C++'s symbol lookup rule (i.e. Koenig lookup) says that these
  75. // overloads are visible in either the std namespace or the global
  76. // namespace, but not other namespaces, including the testing
  77. // namespace which Google Test's Message class is in.
  78. //
  79. // To allow STL containers (and other types that has a << operator
  80. // defined in the global namespace) to be used in Google Test assertions,
  81. // testing::Message must access the custom << operator from the global
  82. // namespace. Hence this helper function.
  83. //
  84. // Note: Jeffrey Yasskin suggested an alternative fix by "using
  85. // ::operator<<;" in the definition of Message's operator<<. That fix
  86. // doesn't require a helper function, but unfortunately doesn't
  87. // compile with MSVC.
  88. template <typename T>
  89. inline void GTestStreamToHelper(std::ostream* os, const T& val) {
  90. *os << val;
  91. }
  92. namespace testing {
  93. // Forward declaration of classes.
  94. class AssertionResult; // Result of an assertion.
  95. class Message; // Represents a failure message.
  96. class Test; // Represents a test.
  97. class TestInfo; // Information about a test.
  98. class TestPartResult; // Result of a test part.
  99. class UnitTest; // A collection of test cases.
  100. namespace internal {
  101. struct TraceInfo; // Information about a trace point.
  102. class ScopedTrace; // Implements scoped trace.
  103. class TestInfoImpl; // Opaque implementation of TestInfo
  104. class UnitTestImpl; // Opaque implementation of UnitTest
  105. // How many times InitGoogleTest() has been called.
  106. extern int g_init_gtest_count;
  107. // The text used in failure messages to indicate the start of the
  108. // stack trace.
  109. GTEST_API_ extern const char kStackTraceMarker[];
  110. // A secret type that Google Test users don't know about. It has no
  111. // definition on purpose. Therefore it's impossible to create a
  112. // Secret object, which is what we want.
  113. class Secret;
  114. // Two overloaded helpers for checking at compile time whether an
  115. // expression is a null pointer literal (i.e. NULL or any 0-valued
  116. // compile-time integral constant). Their return values have
  117. // different sizes, so we can use sizeof() to test which version is
  118. // picked by the compiler. These helpers have no implementations, as
  119. // we only need their signatures.
  120. //
  121. // Given IsNullLiteralHelper(x), the compiler will pick the first
  122. // version if x can be implicitly converted to Secret*, and pick the
  123. // second version otherwise. Since Secret is a secret and incomplete
  124. // type, the only expression a user can write that has type Secret* is
  125. // a null pointer literal. Therefore, we know that x is a null
  126. // pointer literal if and only if the first version is picked by the
  127. // compiler.
  128. char IsNullLiteralHelper(Secret* p);
  129. char (&IsNullLiteralHelper(...))[2]; // NOLINT
  130. // A compile-time bool constant that is true if and only if x is a
  131. // null pointer literal (i.e. NULL or any 0-valued compile-time
  132. // integral constant).
  133. #ifdef GTEST_ELLIPSIS_NEEDS_POD_
  134. // We lose support for NULL detection where the compiler doesn't like
  135. // passing non-POD classes through ellipsis (...).
  136. #define GTEST_IS_NULL_LITERAL_(x) false
  137. #else
  138. #define GTEST_IS_NULL_LITERAL_(x) \
  139. (sizeof(::testing::internal::IsNullLiteralHelper(x)) == 1)
  140. #endif // GTEST_ELLIPSIS_NEEDS_POD_
  141. // Appends the user-supplied message to the Google-Test-generated message.
  142. GTEST_API_ String AppendUserMessage(const String& gtest_msg,
  143. const Message& user_msg);
  144. // A helper class for creating scoped traces in user programs.
  145. class GTEST_API_ ScopedTrace {
  146. public:
  147. // The c'tor pushes the given source file location and message onto
  148. // a trace stack maintained by Google Test.
  149. ScopedTrace(const char* file, int line, const Message& message);
  150. // The d'tor pops the info pushed by the c'tor.
  151. //
  152. // Note that the d'tor is not virtual in order to be efficient.
  153. // Don't inherit from ScopedTrace!
  154. ~ScopedTrace();
  155. private:
  156. GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedTrace);
  157. } GTEST_ATTRIBUTE_UNUSED_; // A ScopedTrace object does its job in its
  158. // c'tor and d'tor. Therefore it doesn't
  159. // need to be used otherwise.
  160. // Converts a streamable value to a String. A NULL pointer is
  161. // converted to "(null)". When the input value is a ::string,
  162. // ::std::string, ::wstring, or ::std::wstring object, each NUL
  163. // character in it is replaced with "\\0".
  164. // Declared here but defined in gtest.h, so that it has access
  165. // to the definition of the Message class, required by the ARM
  166. // compiler.
  167. template <typename T>
  168. String StreamableToString(const T& streamable);
  169. // Formats a value to be used in a failure message.
  170. #ifdef GTEST_NEEDS_IS_POINTER_
  171. // These are needed as the Nokia Symbian and IBM XL C/C++ compilers
  172. // cannot decide between const T& and const T* in a function template.
  173. // These compilers _can_ decide between class template specializations
  174. // for T and T*, so a tr1::type_traits-like is_pointer works, and we
  175. // can overload on that.
  176. // This overload makes sure that all pointers (including
  177. // those to char or wchar_t) are printed as raw pointers.
  178. template <typename T>
  179. inline String FormatValueForFailureMessage(internal::true_type /*dummy*/,
  180. T* pointer) {
  181. return StreamableToString(static_cast<const void*>(pointer));
  182. }
  183. template <typename T>
  184. inline String FormatValueForFailureMessage(internal::false_type /*dummy*/,
  185. const T& value) {
  186. return StreamableToString(value);
  187. }
  188. template <typename T>
  189. inline String FormatForFailureMessage(const T& value) {
  190. return FormatValueForFailureMessage(
  191. typename internal::is_pointer<T>::type(), value);
  192. }
  193. #else
  194. // These are needed as the above solution using is_pointer has the
  195. // limitation that T cannot be a type without external linkage, when
  196. // compiled using MSVC.
  197. template <typename T>
  198. inline String FormatForFailureMessage(const T& value) {
  199. return StreamableToString(value);
  200. }
  201. // This overload makes sure that all pointers (including
  202. // those to char or wchar_t) are printed as raw pointers.
  203. template <typename T>
  204. inline String FormatForFailureMessage(T* pointer) {
  205. return StreamableToString(static_cast<const void*>(pointer));
  206. }
  207. #endif // GTEST_NEEDS_IS_POINTER_
  208. // These overloaded versions handle narrow and wide characters.
  209. GTEST_API_ String FormatForFailureMessage(char ch);
  210. GTEST_API_ String FormatForFailureMessage(wchar_t wchar);
  211. // When this operand is a const char* or char*, and the other operand
  212. // is a ::std::string or ::string, we print this operand as a C string
  213. // rather than a pointer. We do the same for wide strings.
  214. // This internal macro is used to avoid duplicated code.
  215. #define GTEST_FORMAT_IMPL_(operand2_type, operand1_printer)\
  216. inline String FormatForComparisonFailureMessage(\
  217. operand2_type::value_type* str, const operand2_type& /*operand2*/) {\
  218. return operand1_printer(str);\
  219. }\
  220. inline String FormatForComparisonFailureMessage(\
  221. const operand2_type::value_type* str, const operand2_type& /*operand2*/) {\
  222. return operand1_printer(str);\
  223. }
  224. GTEST_FORMAT_IMPL_(::std::string, String::ShowCStringQuoted)
  225. #if GTEST_HAS_STD_WSTRING
  226. GTEST_FORMAT_IMPL_(::std::wstring, String::ShowWideCStringQuoted)
  227. #endif // GTEST_HAS_STD_WSTRING
  228. #if GTEST_HAS_GLOBAL_STRING
  229. GTEST_FORMAT_IMPL_(::string, String::ShowCStringQuoted)
  230. #endif // GTEST_HAS_GLOBAL_STRING
  231. #if GTEST_HAS_GLOBAL_WSTRING
  232. GTEST_FORMAT_IMPL_(::wstring, String::ShowWideCStringQuoted)
  233. #endif // GTEST_HAS_GLOBAL_WSTRING
  234. #undef GTEST_FORMAT_IMPL_
  235. // Constructs and returns the message for an equality assertion
  236. // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
  237. //
  238. // The first four parameters are the expressions used in the assertion
  239. // and their values, as strings. For example, for ASSERT_EQ(foo, bar)
  240. // where foo is 5 and bar is 6, we have:
  241. //
  242. // expected_expression: "foo"
  243. // actual_expression: "bar"
  244. // expected_value: "5"
  245. // actual_value: "6"
  246. //
  247. // The ignoring_case parameter is true iff the assertion is a
  248. // *_STRCASEEQ*. When it's true, the string " (ignoring case)" will
  249. // be inserted into the message.
  250. GTEST_API_ AssertionResult EqFailure(const char* expected_expression,
  251. const char* actual_expression,
  252. const String& expected_value,
  253. const String& actual_value,
  254. bool ignoring_case);
  255. // Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
  256. GTEST_API_ String GetBoolAssertionFailureMessage(
  257. const AssertionResult& assertion_result,
  258. const char* expression_text,
  259. const char* actual_predicate_value,
  260. const char* expected_predicate_value);
  261. // This template class represents an IEEE floating-point number
  262. // (either single-precision or double-precision, depending on the
  263. // template parameters).
  264. //
  265. // The purpose of this class is to do more sophisticated number
  266. // comparison. (Due to round-off error, etc, it's very unlikely that
  267. // two floating-points will be equal exactly. Hence a naive
  268. // comparison by the == operation often doesn't work.)
  269. //
  270. // Format of IEEE floating-point:
  271. //
  272. // The most-significant bit being the leftmost, an IEEE
  273. // floating-point looks like
  274. //
  275. // sign_bit exponent_bits fraction_bits
  276. //
  277. // Here, sign_bit is a single bit that designates the sign of the
  278. // number.
  279. //
  280. // For float, there are 8 exponent bits and 23 fraction bits.
  281. //
  282. // For double, there are 11 exponent bits and 52 fraction bits.
  283. //
  284. // More details can be found at
  285. // http://en.wikipedia.org/wiki/IEEE_floating-point_standard.
  286. //
  287. // Template parameter:
  288. //
  289. // RawType: the raw floating-point type (either float or double)
  290. template <typename RawType>
  291. class FloatingPoint {
  292. public:
  293. // Defines the unsigned integer type that has the same size as the
  294. // floating point number.
  295. typedef typename TypeWithSize<sizeof(RawType)>::UInt Bits;
  296. // Constants.
  297. // # of bits in a number.
  298. static const size_t kBitCount = 8*sizeof(RawType);
  299. // # of fraction bits in a number.
  300. static const size_t kFractionBitCount =
  301. std::numeric_limits<RawType>::digits - 1;
  302. // # of exponent bits in a number.
  303. static const size_t kExponentBitCount = kBitCount - 1 - kFractionBitCount;
  304. // The mask for the sign bit.
  305. static const Bits kSignBitMask = static_cast<Bits>(1) << (kBitCount - 1);
  306. // The mask for the fraction bits.
  307. static const Bits kFractionBitMask =
  308. ~static_cast<Bits>(0) >> (kExponentBitCount + 1);
  309. // The mask for the exponent bits.
  310. static const Bits kExponentBitMask = ~(kSignBitMask | kFractionBitMask);
  311. // How many ULP's (Units in the Last Place) we want to tolerate when
  312. // comparing two numbers. The larger the value, the more error we
  313. // allow. A 0 value means that two numbers must be exactly the same
  314. // to be considered equal.
  315. //
  316. // The maximum error of a single floating-point operation is 0.5
  317. // units in the last place. On Intel CPU's, all floating-point
  318. // calculations are done with 80-bit precision, while double has 64
  319. // bits. Therefore, 4 should be enough for ordinary use.
  320. //
  321. // See the following article for more details on ULP:
  322. // http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm.
  323. static const size_t kMaxUlps = 4;
  324. // Constructs a FloatingPoint from a raw floating-point number.
  325. //
  326. // On an Intel CPU, passing a non-normalized NAN (Not a Number)
  327. // around may change its bits, although the new value is guaranteed
  328. // to be also a NAN. Therefore, don't expect this constructor to
  329. // preserve the bits in x when x is a NAN.
  330. explicit FloatingPoint(const RawType& x) { u_.value_ = x; }
  331. // Static methods
  332. // Reinterprets a bit pattern as a floating-point number.
  333. //
  334. // This function is needed to test the AlmostEquals() method.
  335. static RawType ReinterpretBits(const Bits bits) {
  336. FloatingPoint fp(0);
  337. fp.u_.bits_ = bits;
  338. return fp.u_.value_;
  339. }
  340. // Returns the floating-point number that represent positive infinity.
  341. static RawType Infinity() {
  342. return ReinterpretBits(kExponentBitMask);
  343. }
  344. // Non-static methods
  345. // Returns the bits that represents this number.
  346. const Bits &bits() const { return u_.bits_; }
  347. // Returns the exponent bits of this number.
  348. Bits exponent_bits() const { return kExponentBitMask & u_.bits_; }
  349. // Returns the fraction bits of this number.
  350. Bits fraction_bits() const { return kFractionBitMask & u_.bits_; }
  351. // Returns the sign bit of this number.
  352. Bits sign_bit() const { return kSignBitMask & u_.bits_; }
  353. // Returns true iff this is NAN (not a number).
  354. bool is_nan() const {
  355. // It's a NAN if the exponent bits are all ones and the fraction
  356. // bits are not entirely zeros.
  357. return (exponent_bits() == kExponentBitMask) && (fraction_bits() != 0);
  358. }
  359. // Returns true iff this number is at most kMaxUlps ULP's away from
  360. // rhs. In particular, this function:
  361. //
  362. // - returns false if either number is (or both are) NAN.
  363. // - treats really large numbers as almost equal to infinity.
  364. // - thinks +0.0 and -0.0 are 0 DLP's apart.
  365. bool AlmostEquals(const FloatingPoint& rhs) const {
  366. // The IEEE standard says that any comparison operation involving
  367. // a NAN must return false.
  368. if (is_nan() || rhs.is_nan()) return false;
  369. return DistanceBetweenSignAndMagnitudeNumbers(u_.bits_, rhs.u_.bits_)
  370. <= kMaxUlps;
  371. }
  372. private:
  373. // The data type used to store the actual floating-point number.
  374. union FloatingPointUnion {
  375. RawType value_; // The raw floating-point number.
  376. Bits bits_; // The bits that represent the number.
  377. };
  378. // Converts an integer from the sign-and-magnitude representation to
  379. // the biased representation. More precisely, let N be 2 to the
  380. // power of (kBitCount - 1), an integer x is represented by the
  381. // unsigned number x + N.
  382. //
  383. // For instance,
  384. //
  385. // -N + 1 (the most negative number representable using
  386. // sign-and-magnitude) is represented by 1;
  387. // 0 is represented by N; and
  388. // N - 1 (the biggest number representable using
  389. // sign-and-magnitude) is represented by 2N - 1.
  390. //
  391. // Read http://en.wikipedia.org/wiki/Signed_number_representations
  392. // for more details on signed number representations.
  393. static Bits SignAndMagnitudeToBiased(const Bits &sam) {
  394. if (kSignBitMask & sam) {
  395. // sam represents a negative number.
  396. return ~sam + 1;
  397. } else {
  398. // sam represents a positive number.
  399. return kSignBitMask | sam;
  400. }
  401. }
  402. // Given two numbers in the sign-and-magnitude representation,
  403. // returns the distance between them as an unsigned number.
  404. static Bits DistanceBetweenSignAndMagnitudeNumbers(const Bits &sam1,
  405. const Bits &sam2) {
  406. const Bits biased1 = SignAndMagnitudeToBiased(sam1);
  407. const Bits biased2 = SignAndMagnitudeToBiased(sam2);
  408. return (biased1 >= biased2) ? (biased1 - biased2) : (biased2 - biased1);
  409. }
  410. FloatingPointUnion u_;
  411. };
  412. // Typedefs the instances of the FloatingPoint template class that we
  413. // care to use.
  414. typedef FloatingPoint<float> Float;
  415. typedef FloatingPoint<double> Double;
  416. // In order to catch the mistake of putting tests that use different
  417. // test fixture classes in the same test case, we need to assign
  418. // unique IDs to fixture classes and compare them. The TypeId type is
  419. // used to hold such IDs. The user should treat TypeId as an opaque
  420. // type: the only operation allowed on TypeId values is to compare
  421. // them for equality using the == operator.
  422. typedef const void* TypeId;
  423. template <typename T>
  424. class TypeIdHelper {
  425. public:
  426. // dummy_ must not have a const type. Otherwise an overly eager
  427. // compiler (e.g. MSVC 7.1 & 8.0) may try to merge
  428. // TypeIdHelper<T>::dummy_ for different Ts as an "optimization".
  429. static bool dummy_;
  430. };
  431. template <typename T>
  432. bool TypeIdHelper<T>::dummy_ = false;
  433. // GetTypeId<T>() returns the ID of type T. Different values will be
  434. // returned for different types. Calling the function twice with the
  435. // same type argument is guaranteed to return the same ID.
  436. template <typename T>
  437. TypeId GetTypeId() {
  438. // The compiler is required to allocate a different
  439. // TypeIdHelper<T>::dummy_ variable for each T used to instantiate
  440. // the template. Therefore, the address of dummy_ is guaranteed to
  441. // be unique.
  442. return &(TypeIdHelper<T>::dummy_);
  443. }
  444. // Returns the type ID of ::testing::Test. Always call this instead
  445. // of GetTypeId< ::testing::Test>() to get the type ID of
  446. // ::testing::Test, as the latter may give the wrong result due to a
  447. // suspected linker bug when compiling Google Test as a Mac OS X
  448. // framework.
  449. GTEST_API_ TypeId GetTestTypeId();
  450. // Defines the abstract factory interface that creates instances
  451. // of a Test object.
  452. class TestFactoryBase {
  453. public:
  454. virtual ~TestFactoryBase() {}
  455. // Creates a test instance to run. The instance is both created and destroyed
  456. // within TestInfoImpl::Run()
  457. virtual Test* CreateTest() = 0;
  458. protected:
  459. TestFactoryBase() {}
  460. private:
  461. GTEST_DISALLOW_COPY_AND_ASSIGN_(TestFactoryBase);
  462. };
  463. // This class provides implementation of TeastFactoryBase interface.
  464. // It is used in TEST and TEST_F macros.
  465. template <class TestClass>
  466. class TestFactoryImpl : public TestFactoryBase {
  467. public:
  468. virtual Test* CreateTest() { return new TestClass; }
  469. };
  470. #if GTEST_OS_WINDOWS
  471. // Predicate-formatters for implementing the HRESULT checking macros
  472. // {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED}
  473. // We pass a long instead of HRESULT to avoid causing an
  474. // include dependency for the HRESULT type.
  475. GTEST_API_ AssertionResult IsHRESULTSuccess(const char* expr,
  476. long hr); // NOLINT
  477. GTEST_API_ AssertionResult IsHRESULTFailure(const char* expr,
  478. long hr); // NOLINT
  479. #endif // GTEST_OS_WINDOWS
  480. // Formats a source file path and a line number as they would appear
  481. // in a compiler error message.
  482. inline String FormatFileLocation(const char* file, int line) {
  483. const char* const file_name = file == NULL ? "unknown file" : file;
  484. if (line < 0) {
  485. return String::Format("%s:", file_name);
  486. }
  487. #ifdef _MSC_VER
  488. return String::Format("%s(%d):", file_name, line);
  489. #else
  490. return String::Format("%s:%d:", file_name, line);
  491. #endif // _MSC_VER
  492. }
  493. // Types of SetUpTestCase() and TearDownTestCase() functions.
  494. typedef void (*SetUpTestCaseFunc)();
  495. typedef void (*TearDownTestCaseFunc)();
  496. // Creates a new TestInfo object and registers it with Google Test;
  497. // returns the created object.
  498. //
  499. // Arguments:
  500. //
  501. // test_case_name: name of the test case
  502. // name: name of the test
  503. // test_case_comment: a comment on the test case that will be included in
  504. // the test output
  505. // comment: a comment on the test that will be included in the
  506. // test output
  507. // fixture_class_id: ID of the test fixture class
  508. // set_up_tc: pointer to the function that sets up the test case
  509. // tear_down_tc: pointer to the function that tears down the test case
  510. // factory: pointer to the factory that creates a test object.
  511. // The newly created TestInfo instance will assume
  512. // ownership of the factory object.
  513. GTEST_API_ TestInfo* MakeAndRegisterTestInfo(
  514. const char* test_case_name, const char* name,
  515. const char* test_case_comment, const char* comment,
  516. TypeId fixture_class_id,
  517. SetUpTestCaseFunc set_up_tc,
  518. TearDownTestCaseFunc tear_down_tc,
  519. TestFactoryBase* factory);
  520. // If *pstr starts with the given prefix, modifies *pstr to be right
  521. // past the prefix and returns true; otherwise leaves *pstr unchanged
  522. // and returns false. None of pstr, *pstr, and prefix can be NULL.
  523. bool SkipPrefix(const char* prefix, const char** pstr);
  524. #if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P
  525. // State of the definition of a type-parameterized test case.
  526. class GTEST_API_ TypedTestCasePState {
  527. public:
  528. TypedTestCasePState() : registered_(false) {}
  529. // Adds the given test name to defined_test_names_ and return true
  530. // if the test case hasn't been registered; otherwise aborts the
  531. // program.
  532. bool AddTestName(const char* file, int line, const char* case_name,
  533. const char* test_name) {
  534. if (registered_) {
  535. fprintf(stderr, "%s Test %s must be defined before "
  536. "REGISTER_TYPED_TEST_CASE_P(%s, ...).\n",
  537. FormatFileLocation(file, line).c_str(), test_name, case_name);
  538. fflush(stderr);
  539. posix::Abort();
  540. }
  541. defined_test_names_.insert(test_name);
  542. return true;
  543. }
  544. // Verifies that registered_tests match the test names in
  545. // defined_test_names_; returns registered_tests if successful, or
  546. // aborts the program otherwise.
  547. const char* VerifyRegisteredTestNames(
  548. const char* file, int line, const char* registered_tests);
  549. private:
  550. bool registered_;
  551. ::std::set<const char*> defined_test_names_;
  552. };
  553. // Skips to the first non-space char after the first comma in 'str';
  554. // returns NULL if no comma is found in 'str'.
  555. inline const char* SkipComma(const char* str) {
  556. const char* comma = strchr(str, ',');
  557. if (comma == NULL) {
  558. return NULL;
  559. }
  560. while (isspace(*(++comma))) {}
  561. return comma;
  562. }
  563. // Returns the prefix of 'str' before the first comma in it; returns
  564. // the entire string if it contains no comma.
  565. inline String GetPrefixUntilComma(const char* str) {
  566. const char* comma = strchr(str, ',');
  567. return comma == NULL ? String(str) : String(str, comma - str);
  568. }
  569. // TypeParameterizedTest<Fixture, TestSel, Types>::Register()
  570. // registers a list of type-parameterized tests with Google Test. The
  571. // return value is insignificant - we just need to return something
  572. // such that we can call this function in a namespace scope.
  573. //
  574. // Implementation note: The GTEST_TEMPLATE_ macro declares a template
  575. // template parameter. It's defined in gtest-type-util.h.
  576. template <GTEST_TEMPLATE_ Fixture, class TestSel, typename Types>
  577. class TypeParameterizedTest {
  578. public:
  579. // 'index' is the index of the test in the type list 'Types'
  580. // specified in INSTANTIATE_TYPED_TEST_CASE_P(Prefix, TestCase,
  581. // Types). Valid values for 'index' are [0, N - 1] where N is the
  582. // length of Types.
  583. static bool Register(const char* prefix, const char* case_name,
  584. const char* test_names, int index) {
  585. typedef typename Types::Head Type;
  586. typedef Fixture<Type> FixtureClass;
  587. typedef typename GTEST_BIND_(TestSel, Type) TestClass;
  588. // First, registers the first type-parameterized test in the type
  589. // list.
  590. MakeAndRegisterTestInfo(
  591. String::Format("%s%s%s/%d", prefix, prefix[0] == '\0' ? "" : "/",
  592. case_name, index).c_str(),
  593. GetPrefixUntilComma(test_names).c_str(),
  594. String::Format("TypeParam = %s", GetTypeName<Type>().c_str()).c_str(),
  595. "",
  596. GetTypeId<FixtureClass>(),
  597. TestClass::SetUpTestCase,
  598. TestClass::TearDownTestCase,
  599. new TestFactoryImpl<TestClass>);
  600. // Next, recurses (at compile time) with the tail of the type list.
  601. return TypeParameterizedTest<Fixture, TestSel, typename Types::Tail>
  602. ::Register(prefix, case_name, test_names, index + 1);
  603. }
  604. };
  605. // The base case for the compile time recursion.
  606. template <GTEST_TEMPLATE_ Fixture, class TestSel>
  607. class TypeParameterizedTest<Fixture, TestSel, Types0> {
  608. public:
  609. static bool Register(const char* /*prefix*/, const char* /*case_name*/,
  610. const char* /*test_names*/, int /*index*/) {
  611. return true;
  612. }
  613. };
  614. // TypeParameterizedTestCase<Fixture, Tests, Types>::Register()
  615. // registers *all combinations* of 'Tests' and 'Types' with Google
  616. // Test. The return value is insignificant - we just need to return
  617. // something such that we can call this function in a namespace scope.
  618. template <GTEST_TEMPLATE_ Fixture, typename Tests, typename Types>
  619. class TypeParameterizedTestCase {
  620. public:
  621. static bool Register(const char* prefix, const char* case_name,
  622. const char* test_names) {
  623. typedef typename Tests::Head Head;
  624. // First, register the first test in 'Test' for each type in 'Types'.
  625. TypeParameterizedTest<Fixture, Head, Types>::Register(
  626. prefix, case_name, test_names, 0);
  627. // Next, recurses (at compile time) with the tail of the test list.
  628. return TypeParameterizedTestCase<Fixture, typename Tests::Tail, Types>
  629. ::Register(prefix, case_name, SkipComma(test_names));
  630. }
  631. };
  632. // The base case for the compile time recursion.
  633. template <GTEST_TEMPLATE_ Fixture, typename Types>
  634. class TypeParameterizedTestCase<Fixture, Templates0, Types> {
  635. public:
  636. static bool Register(const char* /*prefix*/, const char* /*case_name*/,
  637. const char* /*test_names*/) {
  638. return true;
  639. }
  640. };
  641. #endif // GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P
  642. // Returns the current OS stack trace as a String.
  643. //
  644. // The maximum number of stack frames to be included is specified by
  645. // the gtest_stack_trace_depth flag. The skip_count parameter
  646. // specifies the number of top frames to be skipped, which doesn't
  647. // count against the number of frames to be included.
  648. //
  649. // For example, if Foo() calls Bar(), which in turn calls
  650. // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
  651. // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
  652. GTEST_API_ String GetCurrentOsStackTraceExceptTop(UnitTest* unit_test,
  653. int skip_count);
  654. // Helpers for suppressing warnings on unreachable code or constant
  655. // condition.
  656. // Always returns true.
  657. GTEST_API_ bool AlwaysTrue();
  658. // Always returns false.
  659. inline bool AlwaysFalse() { return !AlwaysTrue(); }
  660. // A simple Linear Congruential Generator for generating random
  661. // numbers with a uniform distribution. Unlike rand() and srand(), it
  662. // doesn't use global state (and therefore can't interfere with user
  663. // code). Unlike rand_r(), it's portable. An LCG isn't very random,
  664. // but it's good enough for our purposes.
  665. class GTEST_API_ Random {
  666. public:
  667. static const UInt32 kMaxRange = 1u << 31;
  668. explicit Random(UInt32 seed) : state_(seed) {}
  669. void Reseed(UInt32 seed) { state_ = seed; }
  670. // Generates a random number from [0, range). Crashes if 'range' is
  671. // 0 or greater than kMaxRange.
  672. UInt32 Generate(UInt32 range);
  673. private:
  674. UInt32 state_;
  675. GTEST_DISALLOW_COPY_AND_ASSIGN_(Random);
  676. };
  677. } // namespace internal
  678. } // namespace testing
  679. #define GTEST_MESSAGE_(message, result_type) \
  680. ::testing::internal::AssertHelper(result_type, __FILE__, __LINE__, message) \
  681. = ::testing::Message()
  682. #define GTEST_FATAL_FAILURE_(message) \
  683. return GTEST_MESSAGE_(message, ::testing::TestPartResult::kFatalFailure)
  684. #define GTEST_NONFATAL_FAILURE_(message) \
  685. GTEST_MESSAGE_(message, ::testing::TestPartResult::kNonFatalFailure)
  686. #define GTEST_SUCCESS_(message) \
  687. GTEST_MESSAGE_(message, ::testing::TestPartResult::kSuccess)
  688. // Suppresses MSVC warnings 4072 (unreachable code) for the code following
  689. // statement if it returns or throws (or doesn't return or throw in some
  690. // situations).
  691. #define GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) \
  692. if (::testing::internal::AlwaysTrue()) { statement; }
  693. #define GTEST_TEST_THROW_(statement, expected_exception, fail) \
  694. GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
  695. if (const char* gtest_msg = "") { \
  696. bool gtest_caught_expected = false; \
  697. try { \
  698. GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
  699. } \
  700. catch (expected_exception const&) { \
  701. gtest_caught_expected = true; \
  702. } \
  703. catch (...) { \
  704. gtest_msg = "Expected: " #statement " throws an exception of type " \
  705. #expected_exception ".\n Actual: it throws a different " \
  706. "type."; \
  707. goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
  708. } \
  709. if (!gtest_caught_expected) { \
  710. gtest_msg = "Expected: " #statement " throws an exception of type " \
  711. #expected_exception ".\n Actual: it throws nothing."; \
  712. goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
  713. } \
  714. } else \
  715. GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__): \
  716. fail(gtest_msg)
  717. #define GTEST_TEST_NO_THROW_(statement, fail) \
  718. GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
  719. if (const char* gtest_msg = "") { \
  720. try { \
  721. GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
  722. } \
  723. catch (...) { \
  724. gtest_msg = "Expected: " #statement " doesn't throw an exception.\n" \
  725. " Actual: it throws."; \
  726. goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \
  727. } \
  728. } else \
  729. GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__): \
  730. fail(gtest_msg)
  731. #define GTEST_TEST_ANY_THROW_(statement, fail) \
  732. GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
  733. if (const char* gtest_msg = "") { \
  734. bool gtest_caught_any = false; \
  735. try { \
  736. GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
  737. } \
  738. catch (...) { \
  739. gtest_caught_any = true; \
  740. } \
  741. if (!gtest_caught_any) { \
  742. gtest_msg = "Expected: " #statement " throws an exception.\n" \
  743. " Actual: it doesn't."; \
  744. goto GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__); \
  745. } \
  746. } else \
  747. GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__): \
  748. fail(gtest_msg)
  749. // Implements Boolean test assertions such as EXPECT_TRUE. expression can be
  750. // either a boolean expression or an AssertionResult. text is a textual
  751. // represenation of expression as it was passed into the EXPECT_TRUE.
  752. #define GTEST_TEST_BOOLEAN_(expression, text, actual, expected, fail) \
  753. GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
  754. if (const ::testing::AssertionResult gtest_ar_ = \
  755. ::testing::AssertionResult(expression)) \
  756. ; \
  757. else \
  758. fail(::testing::internal::GetBoolAssertionFailureMessage(\
  759. gtest_ar_, text, #actual, #expected).c_str())
  760. #define GTEST_TEST_NO_FATAL_FAILURE_(statement, fail) \
  761. GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
  762. if (const char* gtest_msg = "") { \
  763. ::testing::internal::HasNewFatalFailureHelper gtest_fatal_failure_checker; \
  764. GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
  765. if (gtest_fatal_failure_checker.has_new_fatal_failure()) { \
  766. gtest_msg = "Expected: " #statement " doesn't generate new fatal " \
  767. "failures in the current thread.\n" \
  768. " Actual: it does."; \
  769. goto GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__); \
  770. } \
  771. } else \
  772. GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__): \
  773. fail(gtest_msg)
  774. // Expands to the name of the class that implements the given test.
  775. #define GTEST_TEST_CLASS_NAME_(test_case_name, test_name) \
  776. test_case_name##_##test_name##_Test
  777. // Helper macro for defining tests.
  778. #define GTEST_TEST_(test_case_name, test_name, parent_class, parent_id)\
  779. class GTEST_TEST_CLASS_NAME_(test_case_name, test_name) : public parent_class {\
  780. public:\
  781. GTEST_TEST_CLASS_NAME_(test_case_name, test_name)() {}\
  782. private:\
  783. virtual void TestBody();\
  784. static ::testing::TestInfo* const test_info_;\
  785. GTEST_DISALLOW_COPY_AND_ASSIGN_(\
  786. GTEST_TEST_CLASS_NAME_(test_case_name, test_name));\
  787. };\
  788. \
  789. ::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_case_name, test_name)\
  790. ::test_info_ =\
  791. ::testing::internal::MakeAndRegisterTestInfo(\
  792. #test_case_name, #test_name, "", "", \
  793. (parent_id), \
  794. parent_class::SetUpTestCase, \
  795. parent_class::TearDownTestCase, \
  796. new ::testing::internal::TestFactoryImpl<\
  797. GTEST_TEST_CLASS_NAME_(test_case_name, test_name)>);\
  798. void GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::TestBody()
  799. #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_