/Unittests/googletest/include/gtest/internal/gtest-internal.h

http://unladen-swallow.googlecode.com/ · C++ Header · 910 lines · 431 code · 123 blank · 356 comment · 31 complexity · 614c7ca967516d24e8c9b9055c5079a3 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. template <typename E> class Vector; // A generic vector.
  106. // How many times InitGoogleTest() has been called.
  107. extern int g_init_gtest_count;
  108. // The text used in failure messages to indicate the start of the
  109. // stack trace.
  110. extern const char kStackTraceMarker[];
  111. // A secret type that Google Test users don't know about. It has no
  112. // definition on purpose. Therefore it's impossible to create a
  113. // Secret object, which is what we want.
  114. class Secret;
  115. // Two overloaded helpers for checking at compile time whether an
  116. // expression is a null pointer literal (i.e. NULL or any 0-valued
  117. // compile-time integral constant). Their return values have
  118. // different sizes, so we can use sizeof() to test which version is
  119. // picked by the compiler. These helpers have no implementations, as
  120. // we only need their signatures.
  121. //
  122. // Given IsNullLiteralHelper(x), the compiler will pick the first
  123. // version if x can be implicitly converted to Secret*, and pick the
  124. // second version otherwise. Since Secret is a secret and incomplete
  125. // type, the only expression a user can write that has type Secret* is
  126. // a null pointer literal. Therefore, we know that x is a null
  127. // pointer literal if and only if the first version is picked by the
  128. // compiler.
  129. char IsNullLiteralHelper(Secret* p);
  130. char (&IsNullLiteralHelper(...))[2]; // NOLINT
  131. // A compile-time bool constant that is true if and only if x is a
  132. // null pointer literal (i.e. NULL or any 0-valued compile-time
  133. // integral constant).
  134. #ifdef GTEST_ELLIPSIS_NEEDS_COPY_
  135. // Passing non-POD classes through ellipsis (...) crashes the ARM
  136. // compiler. The Nokia Symbian and the IBM XL C/C++ compiler try to
  137. // instantiate a copy constructor for objects passed through ellipsis
  138. // (...), failing for uncopyable objects. Hence we define this to
  139. // false (and lose support for NULL detection).
  140. #define GTEST_IS_NULL_LITERAL_(x) false
  141. #else
  142. #define GTEST_IS_NULL_LITERAL_(x) \
  143. (sizeof(::testing::internal::IsNullLiteralHelper(x)) == 1)
  144. #endif // GTEST_ELLIPSIS_NEEDS_COPY_
  145. // Appends the user-supplied message to the Google-Test-generated message.
  146. String AppendUserMessage(const String& gtest_msg,
  147. const Message& user_msg);
  148. // A helper class for creating scoped traces in user programs.
  149. class ScopedTrace {
  150. public:
  151. // The c'tor pushes the given source file location and message onto
  152. // a trace stack maintained by Google Test.
  153. ScopedTrace(const char* file, int line, const Message& message);
  154. // The d'tor pops the info pushed by the c'tor.
  155. //
  156. // Note that the d'tor is not virtual in order to be efficient.
  157. // Don't inherit from ScopedTrace!
  158. ~ScopedTrace();
  159. private:
  160. GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedTrace);
  161. } GTEST_ATTRIBUTE_UNUSED_; // A ScopedTrace object does its job in its
  162. // c'tor and d'tor. Therefore it doesn't
  163. // need to be used otherwise.
  164. // Converts a streamable value to a String. A NULL pointer is
  165. // converted to "(null)". When the input value is a ::string,
  166. // ::std::string, ::wstring, or ::std::wstring object, each NUL
  167. // character in it is replaced with "\\0".
  168. // Declared here but defined in gtest.h, so that it has access
  169. // to the definition of the Message class, required by the ARM
  170. // compiler.
  171. template <typename T>
  172. String StreamableToString(const T& streamable);
  173. // Formats a value to be used in a failure message.
  174. #ifdef GTEST_NEEDS_IS_POINTER_
  175. // These are needed as the Nokia Symbian and IBM XL C/C++ compilers
  176. // cannot decide between const T& and const T* in a function template.
  177. // These compilers _can_ decide between class template specializations
  178. // for T and T*, so a tr1::type_traits-like is_pointer works, and we
  179. // can overload on that.
  180. // This overload makes sure that all pointers (including
  181. // those to char or wchar_t) are printed as raw pointers.
  182. template <typename T>
  183. inline String FormatValueForFailureMessage(internal::true_type /*dummy*/,
  184. T* pointer) {
  185. return StreamableToString(static_cast<const void*>(pointer));
  186. }
  187. template <typename T>
  188. inline String FormatValueForFailureMessage(internal::false_type /*dummy*/,
  189. const T& value) {
  190. return StreamableToString(value);
  191. }
  192. template <typename T>
  193. inline String FormatForFailureMessage(const T& value) {
  194. return FormatValueForFailureMessage(
  195. typename internal::is_pointer<T>::type(), value);
  196. }
  197. #else
  198. // These are needed as the above solution using is_pointer has the
  199. // limitation that T cannot be a type without external linkage, when
  200. // compiled using MSVC.
  201. template <typename T>
  202. inline String FormatForFailureMessage(const T& value) {
  203. return StreamableToString(value);
  204. }
  205. // This overload makes sure that all pointers (including
  206. // those to char or wchar_t) are printed as raw pointers.
  207. template <typename T>
  208. inline String FormatForFailureMessage(T* pointer) {
  209. return StreamableToString(static_cast<const void*>(pointer));
  210. }
  211. #endif // GTEST_NEEDS_IS_POINTER_
  212. // These overloaded versions handle narrow and wide characters.
  213. String FormatForFailureMessage(char ch);
  214. String FormatForFailureMessage(wchar_t wchar);
  215. // When this operand is a const char* or char*, and the other operand
  216. // is a ::std::string or ::string, we print this operand as a C string
  217. // rather than a pointer. We do the same for wide strings.
  218. // This internal macro is used to avoid duplicated code.
  219. #define GTEST_FORMAT_IMPL_(operand2_type, operand1_printer)\
  220. inline String FormatForComparisonFailureMessage(\
  221. operand2_type::value_type* str, const operand2_type& /*operand2*/) {\
  222. return operand1_printer(str);\
  223. }\
  224. inline String FormatForComparisonFailureMessage(\
  225. const operand2_type::value_type* str, const operand2_type& /*operand2*/) {\
  226. return operand1_printer(str);\
  227. }
  228. #if GTEST_HAS_STD_STRING
  229. GTEST_FORMAT_IMPL_(::std::string, String::ShowCStringQuoted)
  230. #endif // GTEST_HAS_STD_STRING
  231. #if GTEST_HAS_STD_WSTRING
  232. GTEST_FORMAT_IMPL_(::std::wstring, String::ShowWideCStringQuoted)
  233. #endif // GTEST_HAS_STD_WSTRING
  234. #if GTEST_HAS_GLOBAL_STRING
  235. GTEST_FORMAT_IMPL_(::string, String::ShowCStringQuoted)
  236. #endif // GTEST_HAS_GLOBAL_STRING
  237. #if GTEST_HAS_GLOBAL_WSTRING
  238. GTEST_FORMAT_IMPL_(::wstring, String::ShowWideCStringQuoted)
  239. #endif // GTEST_HAS_GLOBAL_WSTRING
  240. #undef GTEST_FORMAT_IMPL_
  241. // Constructs and returns the message for an equality assertion
  242. // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
  243. //
  244. // The first four parameters are the expressions used in the assertion
  245. // and their values, as strings. For example, for ASSERT_EQ(foo, bar)
  246. // where foo is 5 and bar is 6, we have:
  247. //
  248. // expected_expression: "foo"
  249. // actual_expression: "bar"
  250. // expected_value: "5"
  251. // actual_value: "6"
  252. //
  253. // The ignoring_case parameter is true iff the assertion is a
  254. // *_STRCASEEQ*. When it's true, the string " (ignoring case)" will
  255. // be inserted into the message.
  256. AssertionResult EqFailure(const char* expected_expression,
  257. const char* actual_expression,
  258. const String& expected_value,
  259. const String& actual_value,
  260. bool ignoring_case);
  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. 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. AssertionResult IsHRESULTSuccess(const char* expr, long hr); // NOLINT
  476. AssertionResult IsHRESULTFailure(const char* expr, long hr); // NOLINT
  477. #endif // GTEST_OS_WINDOWS
  478. // Formats a source file path and a line number as they would appear
  479. // in a compiler error message.
  480. inline String FormatFileLocation(const char* file, int line) {
  481. const char* const file_name = file == NULL ? "unknown file" : file;
  482. if (line < 0) {
  483. return String::Format("%s:", file_name);
  484. }
  485. #ifdef _MSC_VER
  486. return String::Format("%s(%d):", file_name, line);
  487. #else
  488. return String::Format("%s:%d:", file_name, line);
  489. #endif // _MSC_VER
  490. }
  491. // Types of SetUpTestCase() and TearDownTestCase() functions.
  492. typedef void (*SetUpTestCaseFunc)();
  493. typedef void (*TearDownTestCaseFunc)();
  494. // Creates a new TestInfo object and registers it with Google Test;
  495. // returns the created object.
  496. //
  497. // Arguments:
  498. //
  499. // test_case_name: name of the test case
  500. // name: name of the test
  501. // test_case_comment: a comment on the test case that will be included in
  502. // the test output
  503. // comment: a comment on the test that will be included in the
  504. // test output
  505. // fixture_class_id: ID of the test fixture class
  506. // set_up_tc: pointer to the function that sets up the test case
  507. // tear_down_tc: pointer to the function that tears down the test case
  508. // factory: pointer to the factory that creates a test object.
  509. // The newly created TestInfo instance will assume
  510. // ownership of the factory object.
  511. TestInfo* MakeAndRegisterTestInfo(
  512. const char* test_case_name, const char* name,
  513. const char* test_case_comment, const char* comment,
  514. TypeId fixture_class_id,
  515. SetUpTestCaseFunc set_up_tc,
  516. TearDownTestCaseFunc tear_down_tc,
  517. TestFactoryBase* factory);
  518. #if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P
  519. // State of the definition of a type-parameterized test case.
  520. class TypedTestCasePState {
  521. public:
  522. TypedTestCasePState() : registered_(false) {}
  523. // Adds the given test name to defined_test_names_ and return true
  524. // if the test case hasn't been registered; otherwise aborts the
  525. // program.
  526. bool AddTestName(const char* file, int line, const char* case_name,
  527. const char* test_name) {
  528. if (registered_) {
  529. fprintf(stderr, "%s Test %s must be defined before "
  530. "REGISTER_TYPED_TEST_CASE_P(%s, ...).\n",
  531. FormatFileLocation(file, line).c_str(), test_name, case_name);
  532. fflush(stderr);
  533. posix::Abort();
  534. }
  535. defined_test_names_.insert(test_name);
  536. return true;
  537. }
  538. // Verifies that registered_tests match the test names in
  539. // defined_test_names_; returns registered_tests if successful, or
  540. // aborts the program otherwise.
  541. const char* VerifyRegisteredTestNames(
  542. const char* file, int line, const char* registered_tests);
  543. private:
  544. bool registered_;
  545. ::std::set<const char*> defined_test_names_;
  546. };
  547. // Skips to the first non-space char after the first comma in 'str';
  548. // returns NULL if no comma is found in 'str'.
  549. inline const char* SkipComma(const char* str) {
  550. const char* comma = strchr(str, ',');
  551. if (comma == NULL) {
  552. return NULL;
  553. }
  554. while (isspace(*(++comma))) {}
  555. return comma;
  556. }
  557. // Returns the prefix of 'str' before the first comma in it; returns
  558. // the entire string if it contains no comma.
  559. inline String GetPrefixUntilComma(const char* str) {
  560. const char* comma = strchr(str, ',');
  561. return comma == NULL ? String(str) : String(str, comma - str);
  562. }
  563. // TypeParameterizedTest<Fixture, TestSel, Types>::Register()
  564. // registers a list of type-parameterized tests with Google Test. The
  565. // return value is insignificant - we just need to return something
  566. // such that we can call this function in a namespace scope.
  567. //
  568. // Implementation note: The GTEST_TEMPLATE_ macro declares a template
  569. // template parameter. It's defined in gtest-type-util.h.
  570. template <GTEST_TEMPLATE_ Fixture, class TestSel, typename Types>
  571. class TypeParameterizedTest {
  572. public:
  573. // 'index' is the index of the test in the type list 'Types'
  574. // specified in INSTANTIATE_TYPED_TEST_CASE_P(Prefix, TestCase,
  575. // Types). Valid values for 'index' are [0, N - 1] where N is the
  576. // length of Types.
  577. static bool Register(const char* prefix, const char* case_name,
  578. const char* test_names, int index) {
  579. typedef typename Types::Head Type;
  580. typedef Fixture<Type> FixtureClass;
  581. typedef typename GTEST_BIND_(TestSel, Type) TestClass;
  582. // First, registers the first type-parameterized test in the type
  583. // list.
  584. MakeAndRegisterTestInfo(
  585. String::Format("%s%s%s/%d", prefix, prefix[0] == '\0' ? "" : "/",
  586. case_name, index).c_str(),
  587. GetPrefixUntilComma(test_names).c_str(),
  588. String::Format("TypeParam = %s", GetTypeName<Type>().c_str()).c_str(),
  589. "",
  590. GetTypeId<FixtureClass>(),
  591. TestClass::SetUpTestCase,
  592. TestClass::TearDownTestCase,
  593. new TestFactoryImpl<TestClass>);
  594. // Next, recurses (at compile time) with the tail of the type list.
  595. return TypeParameterizedTest<Fixture, TestSel, typename Types::Tail>
  596. ::Register(prefix, case_name, test_names, index + 1);
  597. }
  598. };
  599. // The base case for the compile time recursion.
  600. template <GTEST_TEMPLATE_ Fixture, class TestSel>
  601. class TypeParameterizedTest<Fixture, TestSel, Types0> {
  602. public:
  603. static bool Register(const char* /*prefix*/, const char* /*case_name*/,
  604. const char* /*test_names*/, int /*index*/) {
  605. return true;
  606. }
  607. };
  608. // TypeParameterizedTestCase<Fixture, Tests, Types>::Register()
  609. // registers *all combinations* of 'Tests' and 'Types' with Google
  610. // Test. The return value is insignificant - we just need to return
  611. // something such that we can call this function in a namespace scope.
  612. template <GTEST_TEMPLATE_ Fixture, typename Tests, typename Types>
  613. class TypeParameterizedTestCase {
  614. public:
  615. static bool Register(const char* prefix, const char* case_name,
  616. const char* test_names) {
  617. typedef typename Tests::Head Head;
  618. // First, register the first test in 'Test' for each type in 'Types'.
  619. TypeParameterizedTest<Fixture, Head, Types>::Register(
  620. prefix, case_name, test_names, 0);
  621. // Next, recurses (at compile time) with the tail of the test list.
  622. return TypeParameterizedTestCase<Fixture, typename Tests::Tail, Types>
  623. ::Register(prefix, case_name, SkipComma(test_names));
  624. }
  625. };
  626. // The base case for the compile time recursion.
  627. template <GTEST_TEMPLATE_ Fixture, typename Types>
  628. class TypeParameterizedTestCase<Fixture, Templates0, Types> {
  629. public:
  630. static bool Register(const char* /*prefix*/, const char* /*case_name*/,
  631. const char* /*test_names*/) {
  632. return true;
  633. }
  634. };
  635. #endif // GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P
  636. // Returns the current OS stack trace as a String.
  637. //
  638. // The maximum number of stack frames to be included is specified by
  639. // the gtest_stack_trace_depth flag. The skip_count parameter
  640. // specifies the number of top frames to be skipped, which doesn't
  641. // count against the number of frames to be included.
  642. //
  643. // For example, if Foo() calls Bar(), which in turn calls
  644. // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
  645. // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
  646. String GetCurrentOsStackTraceExceptTop(UnitTest* unit_test, int skip_count);
  647. // Helpers for suppressing warnings on unreachable code or constant
  648. // condition.
  649. // Always returns true.
  650. bool AlwaysTrue();
  651. // Always returns false.
  652. inline bool AlwaysFalse() { return !AlwaysTrue(); }
  653. // A simple Linear Congruential Generator for generating random
  654. // numbers with a uniform distribution. Unlike rand() and srand(), it
  655. // doesn't use global state (and therefore can't interfere with user
  656. // code). Unlike rand_r(), it's portable. An LCG isn't very random,
  657. // but it's good enough for our purposes.
  658. class Random {
  659. public:
  660. static const UInt32 kMaxRange = 1u << 31;
  661. explicit Random(UInt32 seed) : state_(seed) {}
  662. void Reseed(UInt32 seed) { state_ = seed; }
  663. // Generates a random number from [0, range). Crashes if 'range' is
  664. // 0 or greater than kMaxRange.
  665. UInt32 Generate(UInt32 range);
  666. private:
  667. UInt32 state_;
  668. GTEST_DISALLOW_COPY_AND_ASSIGN_(Random);
  669. };
  670. } // namespace internal
  671. } // namespace testing
  672. #define GTEST_MESSAGE_(message, result_type) \
  673. ::testing::internal::AssertHelper(result_type, __FILE__, __LINE__, message) \
  674. = ::testing::Message()
  675. #define GTEST_FATAL_FAILURE_(message) \
  676. return GTEST_MESSAGE_(message, ::testing::TestPartResult::kFatalFailure)
  677. #define GTEST_NONFATAL_FAILURE_(message) \
  678. GTEST_MESSAGE_(message, ::testing::TestPartResult::kNonFatalFailure)
  679. #define GTEST_SUCCESS_(message) \
  680. GTEST_MESSAGE_(message, ::testing::TestPartResult::kSuccess)
  681. // Suppresses MSVC warnings 4072 (unreachable code) for the code following
  682. // statement if it returns or throws (or doesn't return or throw in some
  683. // situations).
  684. #define GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) \
  685. if (::testing::internal::AlwaysTrue()) { statement; }
  686. #define GTEST_TEST_THROW_(statement, expected_exception, fail) \
  687. GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
  688. if (const char* gtest_msg = "") { \
  689. bool gtest_caught_expected = false; \
  690. try { \
  691. GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
  692. } \
  693. catch (expected_exception const&) { \
  694. gtest_caught_expected = true; \
  695. } \
  696. catch (...) { \
  697. gtest_msg = "Expected: " #statement " throws an exception of type " \
  698. #expected_exception ".\n Actual: it throws a different " \
  699. "type."; \
  700. goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
  701. } \
  702. if (!gtest_caught_expected) { \
  703. gtest_msg = "Expected: " #statement " throws an exception of type " \
  704. #expected_exception ".\n Actual: it throws nothing."; \
  705. goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
  706. } \
  707. } else \
  708. GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__): \
  709. fail(gtest_msg)
  710. #define GTEST_TEST_NO_THROW_(statement, fail) \
  711. GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
  712. if (const char* gtest_msg = "") { \
  713. try { \
  714. GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
  715. } \
  716. catch (...) { \
  717. gtest_msg = "Expected: " #statement " doesn't throw an exception.\n" \
  718. " Actual: it throws."; \
  719. goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \
  720. } \
  721. } else \
  722. GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__): \
  723. fail(gtest_msg)
  724. #define GTEST_TEST_ANY_THROW_(statement, fail) \
  725. GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
  726. if (const char* gtest_msg = "") { \
  727. bool gtest_caught_any = false; \
  728. try { \
  729. GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
  730. } \
  731. catch (...) { \
  732. gtest_caught_any = true; \
  733. } \
  734. if (!gtest_caught_any) { \
  735. gtest_msg = "Expected: " #statement " throws an exception.\n" \
  736. " Actual: it doesn't."; \
  737. goto GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__); \
  738. } \
  739. } else \
  740. GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__): \
  741. fail(gtest_msg)
  742. #define GTEST_TEST_BOOLEAN_(boolexpr, booltext, actual, expected, fail) \
  743. GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
  744. if (::testing::internal::IsTrue(boolexpr)) \
  745. ; \
  746. else \
  747. fail("Value of: " booltext "\n Actual: " #actual "\nExpected: " #expected)
  748. #define GTEST_TEST_NO_FATAL_FAILURE_(statement, fail) \
  749. GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
  750. if (const char* gtest_msg = "") { \
  751. ::testing::internal::HasNewFatalFailureHelper gtest_fatal_failure_checker; \
  752. GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
  753. if (gtest_fatal_failure_checker.has_new_fatal_failure()) { \
  754. gtest_msg = "Expected: " #statement " doesn't generate new fatal " \
  755. "failures in the current thread.\n" \
  756. " Actual: it does."; \
  757. goto GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__); \
  758. } \
  759. } else \
  760. GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__): \
  761. fail(gtest_msg)
  762. // Expands to the name of the class that implements the given test.
  763. #define GTEST_TEST_CLASS_NAME_(test_case_name, test_name) \
  764. test_case_name##_##test_name##_Test
  765. // Helper macro for defining tests.
  766. #define GTEST_TEST_(test_case_name, test_name, parent_class, parent_id)\
  767. class GTEST_TEST_CLASS_NAME_(test_case_name, test_name) : public parent_class {\
  768. public:\
  769. GTEST_TEST_CLASS_NAME_(test_case_name, test_name)() {}\
  770. private:\
  771. virtual void TestBody();\
  772. static ::testing::TestInfo* const test_info_;\
  773. GTEST_DISALLOW_COPY_AND_ASSIGN_(\
  774. GTEST_TEST_CLASS_NAME_(test_case_name, test_name));\
  775. };\
  776. \
  777. ::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_case_name, test_name)\
  778. ::test_info_ =\
  779. ::testing::internal::MakeAndRegisterTestInfo(\
  780. #test_case_name, #test_name, "", "", \
  781. (parent_id), \
  782. parent_class::SetUpTestCase, \
  783. parent_class::TearDownTestCase, \
  784. new ::testing::internal::TestFactoryImpl<\
  785. GTEST_TEST_CLASS_NAME_(test_case_name, test_name)>);\
  786. void GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::TestBody()
  787. #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_