gtest-internal.h 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571
  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 <functional>
  53. #include <iomanip>
  54. #include <limits>
  55. #include <map>
  56. #include <set>
  57. #include <string>
  58. #include <type_traits>
  59. #include <utility>
  60. #include <vector>
  61. #include "gtest/gtest-message.h"
  62. #include "gtest/internal/gtest-filepath.h"
  63. #include "gtest/internal/gtest-string.h"
  64. #include "gtest/internal/gtest-type-util.h"
  65. // Due to C++ preprocessor weirdness, we need double indirection to
  66. // concatenate two tokens when one of them is __LINE__. Writing
  67. //
  68. // foo ## __LINE__
  69. //
  70. // will result in the token foo__LINE__, instead of foo followed by
  71. // the current line number. For more details, see
  72. // http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.6
  73. #define GTEST_CONCAT_TOKEN_(foo, bar) GTEST_CONCAT_TOKEN_IMPL_(foo, bar)
  74. #define GTEST_CONCAT_TOKEN_IMPL_(foo, bar) foo##bar
  75. // Stringifies its argument.
  76. // Work around a bug in visual studio which doesn't accept code like this:
  77. //
  78. // #define GTEST_STRINGIFY_(name) #name
  79. // #define MACRO(a, b, c) ... GTEST_STRINGIFY_(a) ...
  80. // MACRO(, x, y)
  81. //
  82. // Complaining about the argument to GTEST_STRINGIFY_ being empty.
  83. // This is allowed by the spec.
  84. #define GTEST_STRINGIFY_HELPER_(name, ...) #name
  85. #define GTEST_STRINGIFY_(...) GTEST_STRINGIFY_HELPER_(__VA_ARGS__, )
  86. namespace proto2 {
  87. class MessageLite;
  88. }
  89. namespace testing {
  90. // Forward declarations.
  91. class AssertionResult; // Result of an assertion.
  92. class Message; // Represents a failure message.
  93. class Test; // Represents a test.
  94. class TestInfo; // Information about a test.
  95. class TestPartResult; // Result of a test part.
  96. class UnitTest; // A collection of test suites.
  97. template <typename T>
  98. ::std::string PrintToString(const T& value);
  99. namespace internal {
  100. struct TraceInfo; // Information about a trace point.
  101. class TestInfoImpl; // Opaque implementation of TestInfo
  102. class UnitTestImpl; // Opaque implementation of UnitTest
  103. // The text used in failure messages to indicate the start of the
  104. // stack trace.
  105. GTEST_API_ extern const char kStackTraceMarker[];
  106. // An IgnoredValue object can be implicitly constructed from ANY value.
  107. class IgnoredValue {
  108. struct Sink {};
  109. public:
  110. // This constructor template allows any value to be implicitly
  111. // converted to IgnoredValue. The object has no data member and
  112. // doesn't try to remember anything about the argument. We
  113. // deliberately omit the 'explicit' keyword in order to allow the
  114. // conversion to be implicit.
  115. // Disable the conversion if T already has a magical conversion operator.
  116. // Otherwise we get ambiguity.
  117. template <typename T,
  118. typename std::enable_if<!std::is_convertible<T, Sink>::value,
  119. int>::type = 0>
  120. IgnoredValue(const T& /* ignored */) {} // NOLINT(runtime/explicit)
  121. };
  122. // Appends the user-supplied message to the Google-Test-generated message.
  123. GTEST_API_ std::string AppendUserMessage(const std::string& gtest_msg,
  124. const Message& user_msg);
  125. #if GTEST_HAS_EXCEPTIONS
  126. GTEST_DISABLE_MSC_WARNINGS_PUSH_(
  127. 4275 /* an exported class was derived from a class that was not exported */)
  128. // This exception is thrown by (and only by) a failed Google Test
  129. // assertion when GTEST_FLAG(throw_on_failure) is true (if exceptions
  130. // are enabled). We derive it from std::runtime_error, which is for
  131. // errors presumably detectable only at run time. Since
  132. // std::runtime_error inherits from std::exception, many testing
  133. // frameworks know how to extract and print the message inside it.
  134. class GTEST_API_ GoogleTestFailureException : public ::std::runtime_error {
  135. public:
  136. explicit GoogleTestFailureException(const TestPartResult& failure);
  137. };
  138. GTEST_DISABLE_MSC_WARNINGS_POP_() // 4275
  139. #endif // GTEST_HAS_EXCEPTIONS
  140. namespace edit_distance {
  141. // Returns the optimal edits to go from 'left' to 'right'.
  142. // All edits cost the same, with replace having lower priority than
  143. // add/remove.
  144. // Simple implementation of the Wagner-Fischer algorithm.
  145. // See http://en.wikipedia.org/wiki/Wagner-Fischer_algorithm
  146. enum EditType { kMatch, kAdd, kRemove, kReplace };
  147. GTEST_API_ std::vector<EditType> CalculateOptimalEdits(
  148. const std::vector<size_t>& left, const std::vector<size_t>& right);
  149. // Same as above, but the input is represented as strings.
  150. GTEST_API_ std::vector<EditType> CalculateOptimalEdits(
  151. const std::vector<std::string>& left,
  152. const std::vector<std::string>& right);
  153. // Create a diff of the input strings in Unified diff format.
  154. GTEST_API_ std::string CreateUnifiedDiff(const std::vector<std::string>& left,
  155. const std::vector<std::string>& right,
  156. size_t context = 2);
  157. } // namespace edit_distance
  158. // Constructs and returns the message for an equality assertion
  159. // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
  160. //
  161. // The first four parameters are the expressions used in the assertion
  162. // and their values, as strings. For example, for ASSERT_EQ(foo, bar)
  163. // where foo is 5 and bar is 6, we have:
  164. //
  165. // expected_expression: "foo"
  166. // actual_expression: "bar"
  167. // expected_value: "5"
  168. // actual_value: "6"
  169. //
  170. // The ignoring_case parameter is true if and only if the assertion is a
  171. // *_STRCASEEQ*. When it's true, the string " (ignoring case)" will
  172. // be inserted into the message.
  173. GTEST_API_ AssertionResult EqFailure(const char* expected_expression,
  174. const char* actual_expression,
  175. const std::string& expected_value,
  176. const std::string& actual_value,
  177. bool ignoring_case);
  178. // Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
  179. GTEST_API_ std::string GetBoolAssertionFailureMessage(
  180. const AssertionResult& assertion_result, const char* expression_text,
  181. const char* actual_predicate_value, const char* expected_predicate_value);
  182. // This template class represents an IEEE floating-point number
  183. // (either single-precision or double-precision, depending on the
  184. // template parameters).
  185. //
  186. // The purpose of this class is to do more sophisticated number
  187. // comparison. (Due to round-off error, etc, it's very unlikely that
  188. // two floating-points will be equal exactly. Hence a naive
  189. // comparison by the == operation often doesn't work.)
  190. //
  191. // Format of IEEE floating-point:
  192. //
  193. // The most-significant bit being the leftmost, an IEEE
  194. // floating-point looks like
  195. //
  196. // sign_bit exponent_bits fraction_bits
  197. //
  198. // Here, sign_bit is a single bit that designates the sign of the
  199. // number.
  200. //
  201. // For float, there are 8 exponent bits and 23 fraction bits.
  202. //
  203. // For double, there are 11 exponent bits and 52 fraction bits.
  204. //
  205. // More details can be found at
  206. // http://en.wikipedia.org/wiki/IEEE_floating-point_standard.
  207. //
  208. // Template parameter:
  209. //
  210. // RawType: the raw floating-point type (either float or double)
  211. template <typename RawType>
  212. class FloatingPoint {
  213. public:
  214. // Defines the unsigned integer type that has the same size as the
  215. // floating point number.
  216. typedef typename TypeWithSize<sizeof(RawType)>::UInt Bits;
  217. // Constants.
  218. // # of bits in a number.
  219. static const size_t kBitCount = 8 * sizeof(RawType);
  220. // # of fraction bits in a number.
  221. static const size_t kFractionBitCount =
  222. std::numeric_limits<RawType>::digits - 1;
  223. // # of exponent bits in a number.
  224. static const size_t kExponentBitCount = kBitCount - 1 - kFractionBitCount;
  225. // The mask for the sign bit.
  226. static const Bits kSignBitMask = static_cast<Bits>(1) << (kBitCount - 1);
  227. // The mask for the fraction bits.
  228. static const Bits kFractionBitMask = ~static_cast<Bits>(0) >>
  229. (kExponentBitCount + 1);
  230. // The mask for the exponent bits.
  231. static const Bits kExponentBitMask = ~(kSignBitMask | kFractionBitMask);
  232. // How many ULP's (Units in the Last Place) we want to tolerate when
  233. // comparing two numbers. The larger the value, the more error we
  234. // allow. A 0 value means that two numbers must be exactly the same
  235. // to be considered equal.
  236. //
  237. // The maximum error of a single floating-point operation is 0.5
  238. // units in the last place. On Intel CPU's, all floating-point
  239. // calculations are done with 80-bit precision, while double has 64
  240. // bits. Therefore, 4 should be enough for ordinary use.
  241. //
  242. // See the following article for more details on ULP:
  243. // http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
  244. static const uint32_t kMaxUlps = 4;
  245. // Constructs a FloatingPoint from a raw floating-point number.
  246. //
  247. // On an Intel CPU, passing a non-normalized NAN (Not a Number)
  248. // around may change its bits, although the new value is guaranteed
  249. // to be also a NAN. Therefore, don't expect this constructor to
  250. // preserve the bits in x when x is a NAN.
  251. explicit FloatingPoint(const RawType& x) { u_.value_ = x; }
  252. // Static methods
  253. // Reinterprets a bit pattern as a floating-point number.
  254. //
  255. // This function is needed to test the AlmostEquals() method.
  256. static RawType ReinterpretBits(const Bits bits) {
  257. FloatingPoint fp(0);
  258. fp.u_.bits_ = bits;
  259. return fp.u_.value_;
  260. }
  261. // Returns the floating-point number that represent positive infinity.
  262. static RawType Infinity() { return ReinterpretBits(kExponentBitMask); }
  263. // Returns the maximum representable finite floating-point number.
  264. static RawType Max();
  265. // Non-static methods
  266. // Returns the bits that represents this number.
  267. const Bits& bits() const { return u_.bits_; }
  268. // Returns the exponent bits of this number.
  269. Bits exponent_bits() const { return kExponentBitMask & u_.bits_; }
  270. // Returns the fraction bits of this number.
  271. Bits fraction_bits() const { return kFractionBitMask & u_.bits_; }
  272. // Returns the sign bit of this number.
  273. Bits sign_bit() const { return kSignBitMask & u_.bits_; }
  274. // Returns true if and only if this is NAN (not a number).
  275. bool is_nan() const {
  276. // It's a NAN if the exponent bits are all ones and the fraction
  277. // bits are not entirely zeros.
  278. return (exponent_bits() == kExponentBitMask) && (fraction_bits() != 0);
  279. }
  280. // Returns true if and only if this number is at most kMaxUlps ULP's away
  281. // from rhs. In particular, this function:
  282. //
  283. // - returns false if either number is (or both are) NAN.
  284. // - treats really large numbers as almost equal to infinity.
  285. // - thinks +0.0 and -0.0 are 0 DLP's apart.
  286. bool AlmostEquals(const FloatingPoint& rhs) const {
  287. // The IEEE standard says that any comparison operation involving
  288. // a NAN must return false.
  289. if (is_nan() || rhs.is_nan()) return false;
  290. return DistanceBetweenSignAndMagnitudeNumbers(u_.bits_, rhs.u_.bits_) <=
  291. kMaxUlps;
  292. }
  293. private:
  294. // The data type used to store the actual floating-point number.
  295. union FloatingPointUnion {
  296. RawType value_; // The raw floating-point number.
  297. Bits bits_; // The bits that represent the number.
  298. };
  299. // Converts an integer from the sign-and-magnitude representation to
  300. // the biased representation. More precisely, let N be 2 to the
  301. // power of (kBitCount - 1), an integer x is represented by the
  302. // unsigned number x + N.
  303. //
  304. // For instance,
  305. //
  306. // -N + 1 (the most negative number representable using
  307. // sign-and-magnitude) is represented by 1;
  308. // 0 is represented by N; and
  309. // N - 1 (the biggest number representable using
  310. // sign-and-magnitude) is represented by 2N - 1.
  311. //
  312. // Read http://en.wikipedia.org/wiki/Signed_number_representations
  313. // for more details on signed number representations.
  314. static Bits SignAndMagnitudeToBiased(const Bits& sam) {
  315. if (kSignBitMask & sam) {
  316. // sam represents a negative number.
  317. return ~sam + 1;
  318. } else {
  319. // sam represents a positive number.
  320. return kSignBitMask | sam;
  321. }
  322. }
  323. // Given two numbers in the sign-and-magnitude representation,
  324. // returns the distance between them as an unsigned number.
  325. static Bits DistanceBetweenSignAndMagnitudeNumbers(const Bits& sam1,
  326. const Bits& sam2) {
  327. const Bits biased1 = SignAndMagnitudeToBiased(sam1);
  328. const Bits biased2 = SignAndMagnitudeToBiased(sam2);
  329. return (biased1 >= biased2) ? (biased1 - biased2) : (biased2 - biased1);
  330. }
  331. FloatingPointUnion u_;
  332. };
  333. // We cannot use std::numeric_limits<T>::max() as it clashes with the max()
  334. // macro defined by <windows.h>.
  335. template <>
  336. inline float FloatingPoint<float>::Max() {
  337. return FLT_MAX;
  338. }
  339. template <>
  340. inline double FloatingPoint<double>::Max() {
  341. return DBL_MAX;
  342. }
  343. // Typedefs the instances of the FloatingPoint template class that we
  344. // care to use.
  345. typedef FloatingPoint<float> Float;
  346. typedef FloatingPoint<double> Double;
  347. // In order to catch the mistake of putting tests that use different
  348. // test fixture classes in the same test suite, we need to assign
  349. // unique IDs to fixture classes and compare them. The TypeId type is
  350. // used to hold such IDs. The user should treat TypeId as an opaque
  351. // type: the only operation allowed on TypeId values is to compare
  352. // them for equality using the == operator.
  353. typedef const void* TypeId;
  354. template <typename T>
  355. class TypeIdHelper {
  356. public:
  357. // dummy_ must not have a const type. Otherwise an overly eager
  358. // compiler (e.g. MSVC 7.1 & 8.0) may try to merge
  359. // TypeIdHelper<T>::dummy_ for different Ts as an "optimization".
  360. static bool dummy_;
  361. };
  362. template <typename T>
  363. bool TypeIdHelper<T>::dummy_ = false;
  364. // GetTypeId<T>() returns the ID of type T. Different values will be
  365. // returned for different types. Calling the function twice with the
  366. // same type argument is guaranteed to return the same ID.
  367. template <typename T>
  368. TypeId GetTypeId() {
  369. // The compiler is required to allocate a different
  370. // TypeIdHelper<T>::dummy_ variable for each T used to instantiate
  371. // the template. Therefore, the address of dummy_ is guaranteed to
  372. // be unique.
  373. return &(TypeIdHelper<T>::dummy_);
  374. }
  375. // Returns the type ID of ::testing::Test. Always call this instead
  376. // of GetTypeId< ::testing::Test>() to get the type ID of
  377. // ::testing::Test, as the latter may give the wrong result due to a
  378. // suspected linker bug when compiling Google Test as a Mac OS X
  379. // framework.
  380. GTEST_API_ TypeId GetTestTypeId();
  381. // Defines the abstract factory interface that creates instances
  382. // of a Test object.
  383. class TestFactoryBase {
  384. public:
  385. virtual ~TestFactoryBase() {}
  386. // Creates a test instance to run. The instance is both created and destroyed
  387. // within TestInfoImpl::Run()
  388. virtual Test* CreateTest() = 0;
  389. protected:
  390. TestFactoryBase() {}
  391. private:
  392. TestFactoryBase(const TestFactoryBase&) = delete;
  393. TestFactoryBase& operator=(const TestFactoryBase&) = delete;
  394. };
  395. // This class provides implementation of TestFactoryBase interface.
  396. // It is used in TEST and TEST_F macros.
  397. template <class TestClass>
  398. class TestFactoryImpl : public TestFactoryBase {
  399. public:
  400. Test* CreateTest() override { return new TestClass; }
  401. };
  402. #if GTEST_OS_WINDOWS
  403. // Predicate-formatters for implementing the HRESULT checking macros
  404. // {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED}
  405. // We pass a long instead of HRESULT to avoid causing an
  406. // include dependency for the HRESULT type.
  407. GTEST_API_ AssertionResult IsHRESULTSuccess(const char* expr,
  408. long hr); // NOLINT
  409. GTEST_API_ AssertionResult IsHRESULTFailure(const char* expr,
  410. long hr); // NOLINT
  411. #endif // GTEST_OS_WINDOWS
  412. // Types of SetUpTestSuite() and TearDownTestSuite() functions.
  413. using SetUpTestSuiteFunc = void (*)();
  414. using TearDownTestSuiteFunc = void (*)();
  415. struct CodeLocation {
  416. CodeLocation(const std::string& a_file, int a_line)
  417. : file(a_file), line(a_line) {}
  418. std::string file;
  419. int line;
  420. };
  421. // Helper to identify which setup function for TestCase / TestSuite to call.
  422. // Only one function is allowed, either TestCase or TestSute but not both.
  423. // Utility functions to help SuiteApiResolver
  424. using SetUpTearDownSuiteFuncType = void (*)();
  425. inline SetUpTearDownSuiteFuncType GetNotDefaultOrNull(
  426. SetUpTearDownSuiteFuncType a, SetUpTearDownSuiteFuncType def) {
  427. return a == def ? nullptr : a;
  428. }
  429. template <typename T>
  430. // Note that SuiteApiResolver inherits from T because
  431. // SetUpTestSuite()/TearDownTestSuite() could be protected. This way
  432. // SuiteApiResolver can access them.
  433. struct SuiteApiResolver : T {
  434. // testing::Test is only forward declared at this point. So we make it a
  435. // dependent class for the compiler to be OK with it.
  436. using Test =
  437. typename std::conditional<sizeof(T) != 0, ::testing::Test, void>::type;
  438. static SetUpTearDownSuiteFuncType GetSetUpCaseOrSuite(const char* filename,
  439. int line_num) {
  440. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  441. SetUpTearDownSuiteFuncType test_case_fp =
  442. GetNotDefaultOrNull(&T::SetUpTestCase, &Test::SetUpTestCase);
  443. SetUpTearDownSuiteFuncType test_suite_fp =
  444. GetNotDefaultOrNull(&T::SetUpTestSuite, &Test::SetUpTestSuite);
  445. GTEST_CHECK_(!test_case_fp || !test_suite_fp)
  446. << "Test can not provide both SetUpTestSuite and SetUpTestCase, please "
  447. "make sure there is only one present at "
  448. << filename << ":" << line_num;
  449. return test_case_fp != nullptr ? test_case_fp : test_suite_fp;
  450. #else
  451. (void)(filename);
  452. (void)(line_num);
  453. return &T::SetUpTestSuite;
  454. #endif
  455. }
  456. static SetUpTearDownSuiteFuncType GetTearDownCaseOrSuite(const char* filename,
  457. int line_num) {
  458. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  459. SetUpTearDownSuiteFuncType test_case_fp =
  460. GetNotDefaultOrNull(&T::TearDownTestCase, &Test::TearDownTestCase);
  461. SetUpTearDownSuiteFuncType test_suite_fp =
  462. GetNotDefaultOrNull(&T::TearDownTestSuite, &Test::TearDownTestSuite);
  463. GTEST_CHECK_(!test_case_fp || !test_suite_fp)
  464. << "Test can not provide both TearDownTestSuite and TearDownTestCase,"
  465. " please make sure there is only one present at"
  466. << filename << ":" << line_num;
  467. return test_case_fp != nullptr ? test_case_fp : test_suite_fp;
  468. #else
  469. (void)(filename);
  470. (void)(line_num);
  471. return &T::TearDownTestSuite;
  472. #endif
  473. }
  474. };
  475. // Creates a new TestInfo object and registers it with Google Test;
  476. // returns the created object.
  477. //
  478. // Arguments:
  479. //
  480. // test_suite_name: name of the test suite
  481. // name: name of the test
  482. // type_param: the name of the test's type parameter, or NULL if
  483. // this is not a typed or a type-parameterized test.
  484. // value_param: text representation of the test's value parameter,
  485. // or NULL if this is not a type-parameterized test.
  486. // code_location: code location where the test is defined
  487. // fixture_class_id: ID of the test fixture class
  488. // set_up_tc: pointer to the function that sets up the test suite
  489. // tear_down_tc: pointer to the function that tears down the test suite
  490. // factory: pointer to the factory that creates a test object.
  491. // The newly created TestInfo instance will assume
  492. // ownership of the factory object.
  493. GTEST_API_ TestInfo* MakeAndRegisterTestInfo(
  494. const char* test_suite_name, const char* name, const char* type_param,
  495. const char* value_param, CodeLocation code_location,
  496. TypeId fixture_class_id, SetUpTestSuiteFunc set_up_tc,
  497. TearDownTestSuiteFunc tear_down_tc, TestFactoryBase* factory);
  498. // If *pstr starts with the given prefix, modifies *pstr to be right
  499. // past the prefix and returns true; otherwise leaves *pstr unchanged
  500. // and returns false. None of pstr, *pstr, and prefix can be NULL.
  501. GTEST_API_ bool SkipPrefix(const char* prefix, const char** pstr);
  502. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
  503. /* class A needs to have dll-interface to be used by clients of class B */)
  504. // State of the definition of a type-parameterized test suite.
  505. class GTEST_API_ TypedTestSuitePState {
  506. public:
  507. TypedTestSuitePState() : registered_(false) {}
  508. // Adds the given test name to defined_test_names_ and return true
  509. // if the test suite hasn't been registered; otherwise aborts the
  510. // program.
  511. bool AddTestName(const char* file, int line, const char* case_name,
  512. const char* test_name) {
  513. if (registered_) {
  514. fprintf(stderr,
  515. "%s Test %s must be defined before "
  516. "REGISTER_TYPED_TEST_SUITE_P(%s, ...).\n",
  517. FormatFileLocation(file, line).c_str(), test_name, case_name);
  518. fflush(stderr);
  519. posix::Abort();
  520. }
  521. registered_tests_.insert(
  522. ::std::make_pair(test_name, CodeLocation(file, line)));
  523. return true;
  524. }
  525. bool TestExists(const std::string& test_name) const {
  526. return registered_tests_.count(test_name) > 0;
  527. }
  528. const CodeLocation& GetCodeLocation(const std::string& test_name) const {
  529. RegisteredTestsMap::const_iterator it = registered_tests_.find(test_name);
  530. GTEST_CHECK_(it != registered_tests_.end());
  531. return it->second;
  532. }
  533. // Verifies that registered_tests match the test names in
  534. // defined_test_names_; returns registered_tests if successful, or
  535. // aborts the program otherwise.
  536. const char* VerifyRegisteredTestNames(const char* test_suite_name,
  537. const char* file, int line,
  538. const char* registered_tests);
  539. private:
  540. typedef ::std::map<std::string, CodeLocation, std::less<>> RegisteredTestsMap;
  541. bool registered_;
  542. RegisteredTestsMap registered_tests_;
  543. };
  544. // Legacy API is deprecated but still available
  545. #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  546. using TypedTestCasePState = TypedTestSuitePState;
  547. #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
  548. GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
  549. // Skips to the first non-space char after the first comma in 'str';
  550. // returns NULL if no comma is found in 'str'.
  551. inline const char* SkipComma(const char* str) {
  552. const char* comma = strchr(str, ',');
  553. if (comma == nullptr) {
  554. return nullptr;
  555. }
  556. while (IsSpace(*(++comma))) {
  557. }
  558. return comma;
  559. }
  560. // Returns the prefix of 'str' before the first comma in it; returns
  561. // the entire string if it contains no comma.
  562. inline std::string GetPrefixUntilComma(const char* str) {
  563. const char* comma = strchr(str, ',');
  564. return comma == nullptr ? str : std::string(str, comma);
  565. }
  566. // Splits a given string on a given delimiter, populating a given
  567. // vector with the fields.
  568. void SplitString(const ::std::string& str, char delimiter,
  569. ::std::vector<::std::string>* dest);
  570. // The default argument to the template below for the case when the user does
  571. // not provide a name generator.
  572. struct DefaultNameGenerator {
  573. template <typename T>
  574. static std::string GetName(int i) {
  575. return StreamableToString(i);
  576. }
  577. };
  578. template <typename Provided = DefaultNameGenerator>
  579. struct NameGeneratorSelector {
  580. typedef Provided type;
  581. };
  582. template <typename NameGenerator>
  583. void GenerateNamesRecursively(internal::None, std::vector<std::string>*, int) {}
  584. template <typename NameGenerator, typename Types>
  585. void GenerateNamesRecursively(Types, std::vector<std::string>* result, int i) {
  586. result->push_back(NameGenerator::template GetName<typename Types::Head>(i));
  587. GenerateNamesRecursively<NameGenerator>(typename Types::Tail(), result,
  588. i + 1);
  589. }
  590. template <typename NameGenerator, typename Types>
  591. std::vector<std::string> GenerateNames() {
  592. std::vector<std::string> result;
  593. GenerateNamesRecursively<NameGenerator>(Types(), &result, 0);
  594. return result;
  595. }
  596. // TypeParameterizedTest<Fixture, TestSel, Types>::Register()
  597. // registers a list of type-parameterized tests with Google Test. The
  598. // return value is insignificant - we just need to return something
  599. // such that we can call this function in a namespace scope.
  600. //
  601. // Implementation note: The GTEST_TEMPLATE_ macro declares a template
  602. // template parameter. It's defined in gtest-type-util.h.
  603. template <GTEST_TEMPLATE_ Fixture, class TestSel, typename Types>
  604. class TypeParameterizedTest {
  605. public:
  606. // 'index' is the index of the test in the type list 'Types'
  607. // specified in INSTANTIATE_TYPED_TEST_SUITE_P(Prefix, TestSuite,
  608. // Types). Valid values for 'index' are [0, N - 1] where N is the
  609. // length of Types.
  610. static bool Register(const char* prefix, const CodeLocation& code_location,
  611. const char* case_name, const char* test_names, int index,
  612. const std::vector<std::string>& type_names =
  613. GenerateNames<DefaultNameGenerator, Types>()) {
  614. typedef typename Types::Head Type;
  615. typedef Fixture<Type> FixtureClass;
  616. typedef typename GTEST_BIND_(TestSel, Type) TestClass;
  617. // First, registers the first type-parameterized test in the type
  618. // list.
  619. MakeAndRegisterTestInfo(
  620. (std::string(prefix) + (prefix[0] == '\0' ? "" : "/") + case_name +
  621. "/" + type_names[static_cast<size_t>(index)])
  622. .c_str(),
  623. StripTrailingSpaces(GetPrefixUntilComma(test_names)).c_str(),
  624. GetTypeName<Type>().c_str(),
  625. nullptr, // No value parameter.
  626. code_location, GetTypeId<FixtureClass>(),
  627. SuiteApiResolver<TestClass>::GetSetUpCaseOrSuite(
  628. code_location.file.c_str(), code_location.line),
  629. SuiteApiResolver<TestClass>::GetTearDownCaseOrSuite(
  630. code_location.file.c_str(), code_location.line),
  631. new TestFactoryImpl<TestClass>);
  632. // Next, recurses (at compile time) with the tail of the type list.
  633. return TypeParameterizedTest<Fixture, TestSel,
  634. typename Types::Tail>::Register(prefix,
  635. code_location,
  636. case_name,
  637. test_names,
  638. index + 1,
  639. type_names);
  640. }
  641. };
  642. // The base case for the compile time recursion.
  643. template <GTEST_TEMPLATE_ Fixture, class TestSel>
  644. class TypeParameterizedTest<Fixture, TestSel, internal::None> {
  645. public:
  646. static bool Register(const char* /*prefix*/, const CodeLocation&,
  647. const char* /*case_name*/, const char* /*test_names*/,
  648. int /*index*/,
  649. const std::vector<std::string>& =
  650. std::vector<std::string>() /*type_names*/) {
  651. return true;
  652. }
  653. };
  654. GTEST_API_ void RegisterTypeParameterizedTestSuite(const char* test_suite_name,
  655. CodeLocation code_location);
  656. GTEST_API_ void RegisterTypeParameterizedTestSuiteInstantiation(
  657. const char* case_name);
  658. // TypeParameterizedTestSuite<Fixture, Tests, Types>::Register()
  659. // registers *all combinations* of 'Tests' and 'Types' with Google
  660. // Test. The return value is insignificant - we just need to return
  661. // something such that we can call this function in a namespace scope.
  662. template <GTEST_TEMPLATE_ Fixture, typename Tests, typename Types>
  663. class TypeParameterizedTestSuite {
  664. public:
  665. static bool Register(const char* prefix, CodeLocation code_location,
  666. const TypedTestSuitePState* state, const char* case_name,
  667. const char* test_names,
  668. const std::vector<std::string>& type_names =
  669. GenerateNames<DefaultNameGenerator, Types>()) {
  670. RegisterTypeParameterizedTestSuiteInstantiation(case_name);
  671. std::string test_name =
  672. StripTrailingSpaces(GetPrefixUntilComma(test_names));
  673. if (!state->TestExists(test_name)) {
  674. fprintf(stderr, "Failed to get code location for test %s.%s at %s.",
  675. case_name, test_name.c_str(),
  676. FormatFileLocation(code_location.file.c_str(), code_location.line)
  677. .c_str());
  678. fflush(stderr);
  679. posix::Abort();
  680. }
  681. const CodeLocation& test_location = state->GetCodeLocation(test_name);
  682. typedef typename Tests::Head Head;
  683. // First, register the first test in 'Test' for each type in 'Types'.
  684. TypeParameterizedTest<Fixture, Head, Types>::Register(
  685. prefix, test_location, case_name, test_names, 0, type_names);
  686. // Next, recurses (at compile time) with the tail of the test list.
  687. return TypeParameterizedTestSuite<Fixture, typename Tests::Tail,
  688. Types>::Register(prefix, code_location,
  689. state, case_name,
  690. SkipComma(test_names),
  691. type_names);
  692. }
  693. };
  694. // The base case for the compile time recursion.
  695. template <GTEST_TEMPLATE_ Fixture, typename Types>
  696. class TypeParameterizedTestSuite<Fixture, internal::None, Types> {
  697. public:
  698. static bool Register(const char* /*prefix*/, const CodeLocation&,
  699. const TypedTestSuitePState* /*state*/,
  700. const char* /*case_name*/, const char* /*test_names*/,
  701. const std::vector<std::string>& =
  702. std::vector<std::string>() /*type_names*/) {
  703. return true;
  704. }
  705. };
  706. // Returns the current OS stack trace as an std::string.
  707. //
  708. // The maximum number of stack frames to be included is specified by
  709. // the gtest_stack_trace_depth flag. The skip_count parameter
  710. // specifies the number of top frames to be skipped, which doesn't
  711. // count against the number of frames to be included.
  712. //
  713. // For example, if Foo() calls Bar(), which in turn calls
  714. // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
  715. // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
  716. GTEST_API_ std::string GetCurrentOsStackTraceExceptTop(int skip_count);
  717. // Helpers for suppressing warnings on unreachable code or constant
  718. // condition.
  719. // Always returns true.
  720. GTEST_API_ bool AlwaysTrue();
  721. // Always returns false.
  722. inline bool AlwaysFalse() { return !AlwaysTrue(); }
  723. // Helper for suppressing false warning from Clang on a const char*
  724. // variable declared in a conditional expression always being NULL in
  725. // the else branch.
  726. struct GTEST_API_ ConstCharPtr {
  727. ConstCharPtr(const char* str) : value(str) {}
  728. operator bool() const { return true; }
  729. const char* value;
  730. };
  731. // Helper for declaring std::string within 'if' statement
  732. // in pre C++17 build environment.
  733. struct TrueWithString {
  734. TrueWithString() = default;
  735. explicit TrueWithString(const char* str) : value(str) {}
  736. explicit TrueWithString(const std::string& str) : value(str) {}
  737. explicit operator bool() const { return true; }
  738. std::string value;
  739. };
  740. // A simple Linear Congruential Generator for generating random
  741. // numbers with a uniform distribution. Unlike rand() and srand(), it
  742. // doesn't use global state (and therefore can't interfere with user
  743. // code). Unlike rand_r(), it's portable. An LCG isn't very random,
  744. // but it's good enough for our purposes.
  745. class GTEST_API_ Random {
  746. public:
  747. static const uint32_t kMaxRange = 1u << 31;
  748. explicit Random(uint32_t seed) : state_(seed) {}
  749. void Reseed(uint32_t seed) { state_ = seed; }
  750. // Generates a random number from [0, range). Crashes if 'range' is
  751. // 0 or greater than kMaxRange.
  752. uint32_t Generate(uint32_t range);
  753. private:
  754. uint32_t state_;
  755. Random(const Random&) = delete;
  756. Random& operator=(const Random&) = delete;
  757. };
  758. // Turns const U&, U&, const U, and U all into U.
  759. #define GTEST_REMOVE_REFERENCE_AND_CONST_(T) \
  760. typename std::remove_const<typename std::remove_reference<T>::type>::type
  761. // HasDebugStringAndShortDebugString<T>::value is a compile-time bool constant
  762. // that's true if and only if T has methods DebugString() and ShortDebugString()
  763. // that return std::string.
  764. template <typename T>
  765. class HasDebugStringAndShortDebugString {
  766. private:
  767. template <typename C>
  768. static auto CheckDebugString(C*) -> typename std::is_same<
  769. std::string, decltype(std::declval<const C>().DebugString())>::type;
  770. template <typename>
  771. static std::false_type CheckDebugString(...);
  772. template <typename C>
  773. static auto CheckShortDebugString(C*) -> typename std::is_same<
  774. std::string, decltype(std::declval<const C>().ShortDebugString())>::type;
  775. template <typename>
  776. static std::false_type CheckShortDebugString(...);
  777. using HasDebugStringType = decltype(CheckDebugString<T>(nullptr));
  778. using HasShortDebugStringType = decltype(CheckShortDebugString<T>(nullptr));
  779. public:
  780. static constexpr bool value =
  781. HasDebugStringType::value && HasShortDebugStringType::value;
  782. };
  783. template <typename T>
  784. constexpr bool HasDebugStringAndShortDebugString<T>::value;
  785. // When the compiler sees expression IsContainerTest<C>(0), if C is an
  786. // STL-style container class, the first overload of IsContainerTest
  787. // will be viable (since both C::iterator* and C::const_iterator* are
  788. // valid types and NULL can be implicitly converted to them). It will
  789. // be picked over the second overload as 'int' is a perfect match for
  790. // the type of argument 0. If C::iterator or C::const_iterator is not
  791. // a valid type, the first overload is not viable, and the second
  792. // overload will be picked. Therefore, we can determine whether C is
  793. // a container class by checking the type of IsContainerTest<C>(0).
  794. // The value of the expression is insignificant.
  795. //
  796. // In C++11 mode we check the existence of a const_iterator and that an
  797. // iterator is properly implemented for the container.
  798. //
  799. // For pre-C++11 that we look for both C::iterator and C::const_iterator.
  800. // The reason is that C++ injects the name of a class as a member of the
  801. // class itself (e.g. you can refer to class iterator as either
  802. // 'iterator' or 'iterator::iterator'). If we look for C::iterator
  803. // only, for example, we would mistakenly think that a class named
  804. // iterator is an STL container.
  805. //
  806. // Also note that the simpler approach of overloading
  807. // IsContainerTest(typename C::const_iterator*) and
  808. // IsContainerTest(...) doesn't work with Visual Age C++ and Sun C++.
  809. typedef int IsContainer;
  810. template <class C,
  811. class Iterator = decltype(::std::declval<const C&>().begin()),
  812. class = decltype(::std::declval<const C&>().end()),
  813. class = decltype(++::std::declval<Iterator&>()),
  814. class = decltype(*::std::declval<Iterator>()),
  815. class = typename C::const_iterator>
  816. IsContainer IsContainerTest(int /* dummy */) {
  817. return 0;
  818. }
  819. typedef char IsNotContainer;
  820. template <class C>
  821. IsNotContainer IsContainerTest(long /* dummy */) {
  822. return '\0';
  823. }
  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) {
  876. return lhs == rhs;
  877. }
  878. // This overload is used when k >= 1.
  879. template <typename T, typename U, size_t N>
  880. inline bool ArrayEq(const T (&lhs)[N], const U (&rhs)[N]) {
  881. return internal::ArrayEq(lhs, N, rhs);
  882. }
  883. // This helper reduces code bloat. If we instead put its logic inside
  884. // the previous ArrayEq() function, arrays with different sizes would
  885. // lead to different copies of the template code.
  886. template <typename T, typename U>
  887. bool ArrayEq(const T* lhs, size_t size, const U* rhs) {
  888. for (size_t i = 0; i != size; i++) {
  889. if (!internal::ArrayEq(lhs[i], rhs[i])) return false;
  890. }
  891. return true;
  892. }
  893. // Finds the first element in the iterator range [begin, end) that
  894. // equals elem. Element may be a native array type itself.
  895. template <typename Iter, typename Element>
  896. Iter ArrayAwareFind(Iter begin, Iter end, const Element& elem) {
  897. for (Iter it = begin; it != end; ++it) {
  898. if (internal::ArrayEq(*it, elem)) 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) {
  910. *to = from;
  911. }
  912. // This overload is used when k >= 1.
  913. template <typename T, typename U, size_t N>
  914. inline void CopyArray(const T (&from)[N], U (*to)[N]) {
  915. internal::CopyArray(from, N, *to);
  916. }
  917. // This helper reduces code bloat. If we instead put its logic inside
  918. // the previous CopyArray() function, arrays with different sizes
  919. // would lead to different copies of the template code.
  920. template <typename T, typename U>
  921. void CopyArray(const T* from, size_t size, U* to) {
  922. for (size_t i = 0; i != size; i++) {
  923. internal::CopyArray(from[i], to + i);
  924. }
  925. }
  926. // The relation between an NativeArray object (see below) and the
  927. // native array it represents.
  928. // We use 2 different structs to allow non-copyable types to be used, as long
  929. // as RelationToSourceReference() is passed.
  930. struct RelationToSourceReference {};
  931. struct RelationToSourceCopy {};
  932. // Adapts a native array to a read-only STL-style container. Instead
  933. // of the complete STL container concept, this adaptor only implements
  934. // members useful for Google Mock's container matchers. New members
  935. // should be added as needed. To simplify the implementation, we only
  936. // support Element being a raw type (i.e. having no top-level const or
  937. // reference modifier). It's the client's responsibility to satisfy
  938. // this requirement. Element can be an array type itself (hence
  939. // multi-dimensional arrays are supported).
  940. template <typename Element>
  941. class NativeArray {
  942. public:
  943. // STL-style container typedefs.
  944. typedef Element value_type;
  945. typedef Element* iterator;
  946. typedef const Element* const_iterator;
  947. // Constructs from a native array. References the source.
  948. NativeArray(const Element* array, size_t count, RelationToSourceReference) {
  949. InitRef(array, count);
  950. }
  951. // Constructs from a native array. Copies the source.
  952. NativeArray(const Element* array, size_t count, RelationToSourceCopy) {
  953. InitCopy(array, count);
  954. }
  955. // Copy constructor.
  956. NativeArray(const NativeArray& rhs) {
  957. (this->*rhs.clone_)(rhs.array_, rhs.size_);
  958. }
  959. ~NativeArray() {
  960. if (clone_ != &NativeArray::InitRef) delete[] array_;
  961. }
  962. // STL-style container methods.
  963. size_t size() const { return size_; }
  964. const_iterator begin() const { return array_; }
  965. const_iterator end() const { return array_ + size_; }
  966. bool operator==(const NativeArray& rhs) const {
  967. return size() == rhs.size() && 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: " + \
  1256. gtest_msg.value) \
  1257. .c_str())
  1258. #define GTEST_TEST_ANY_THROW_(statement, fail) \
  1259. GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
  1260. if (::testing::internal::AlwaysTrue()) { \
  1261. bool gtest_caught_any = false; \
  1262. try { \
  1263. GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
  1264. } catch (...) { \
  1265. gtest_caught_any = true; \
  1266. } \
  1267. if (!gtest_caught_any) { \
  1268. goto GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__); \
  1269. } \
  1270. } else \
  1271. GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__) \
  1272. : fail("Expected: " #statement \
  1273. " throws an exception.\n" \
  1274. " Actual: it doesn't.")
  1275. // Implements Boolean test assertions such as EXPECT_TRUE. expression can be
  1276. // either a boolean expression or an AssertionResult. text is a textual
  1277. // representation of expression as it was passed into the EXPECT_TRUE.
  1278. #define GTEST_TEST_BOOLEAN_(expression, text, actual, expected, fail) \
  1279. GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
  1280. if (const ::testing::AssertionResult gtest_ar_ = \
  1281. ::testing::AssertionResult(expression)) \
  1282. ; \
  1283. else \
  1284. fail(::testing::internal::GetBoolAssertionFailureMessage( \
  1285. gtest_ar_, text, #actual, #expected) \
  1286. .c_str())
  1287. #define GTEST_TEST_NO_FATAL_FAILURE_(statement, fail) \
  1288. GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
  1289. if (::testing::internal::AlwaysTrue()) { \
  1290. ::testing::internal::HasNewFatalFailureHelper gtest_fatal_failure_checker; \
  1291. GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
  1292. if (gtest_fatal_failure_checker.has_new_fatal_failure()) { \
  1293. goto GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__); \
  1294. } \
  1295. } else \
  1296. GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__) \
  1297. : fail("Expected: " #statement \
  1298. " doesn't generate new fatal " \
  1299. "failures in the current thread.\n" \
  1300. " Actual: it does.")
  1301. // Expands to the name of the class that implements the given test.
  1302. #define GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \
  1303. test_suite_name##_##test_name##_Test
  1304. // Helper macro for defining tests.
  1305. #define GTEST_TEST_(test_suite_name, test_name, parent_class, parent_id) \
  1306. static_assert(sizeof(GTEST_STRINGIFY_(test_suite_name)) > 1, \
  1307. "test_suite_name must not be empty"); \
  1308. static_assert(sizeof(GTEST_STRINGIFY_(test_name)) > 1, \
  1309. "test_name must not be empty"); \
  1310. class GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \
  1311. : public parent_class { \
  1312. public: \
  1313. GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() = default; \
  1314. ~GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() override = default; \
  1315. GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \
  1316. (const GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) &) = delete; \
  1317. GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) & operator=( \
  1318. const GTEST_TEST_CLASS_NAME_(test_suite_name, \
  1319. test_name) &) = delete; /* NOLINT */ \
  1320. GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \
  1321. (GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) &&) noexcept = delete; \
  1322. GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) & operator=( \
  1323. GTEST_TEST_CLASS_NAME_(test_suite_name, \
  1324. test_name) &&) noexcept = delete; /* NOLINT */ \
  1325. \
  1326. private: \
  1327. void TestBody() override; \
  1328. static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_; \
  1329. }; \
  1330. \
  1331. ::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_suite_name, \
  1332. test_name)::test_info_ = \
  1333. ::testing::internal::MakeAndRegisterTestInfo( \
  1334. #test_suite_name, #test_name, nullptr, nullptr, \
  1335. ::testing::internal::CodeLocation(__FILE__, __LINE__), (parent_id), \
  1336. ::testing::internal::SuiteApiResolver< \
  1337. parent_class>::GetSetUpCaseOrSuite(__FILE__, __LINE__), \
  1338. ::testing::internal::SuiteApiResolver< \
  1339. parent_class>::GetTearDownCaseOrSuite(__FILE__, __LINE__), \
  1340. new ::testing::internal::TestFactoryImpl<GTEST_TEST_CLASS_NAME_( \
  1341. test_suite_name, test_name)>); \
  1342. void GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)::TestBody()
  1343. #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_