PageRenderTime 31ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 0ms

/fsvpclient/Resources/gtest/include/gtest/internal/gtest-internal.h

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