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