gtest-internal.h 50 KB

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