gtest-internal.h 61 KB

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