gtest-internal.h 53 KB

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