gtest-internal.h 62 KB

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