gtest-internal.h 62 KB

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