gtest.h 87 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346
  1. // Copyright 2005, Google Inc.
  2. // All rights reserved.
  3. //
  4. // Redistribution and use in source and binary forms, with or without
  5. // modification, are permitted provided that the following conditions are
  6. // met:
  7. //
  8. // * Redistributions of source code must retain the above copyright
  9. // notice, this list of conditions and the following disclaimer.
  10. // * Redistributions in binary form must reproduce the above
  11. // copyright notice, this list of conditions and the following disclaimer
  12. // in the documentation and/or other materials provided with the
  13. // distribution.
  14. // * Neither the name of Google Inc. nor the names of its
  15. // contributors may be used to endorse or promote products derived from
  16. // this software without specific prior written permission.
  17. //
  18. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  22. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  23. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  24. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  25. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  26. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  28. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. //
  30. // The Google C++ Testing and Mocking Framework (Google Test)
  31. //
  32. // This header file defines the public API for Google Test. It should be
  33. // included by any test program that uses Google Test.
  34. //
  35. // IMPORTANT NOTE: Due to limitation of the C++ language, we have to
  36. // leave some internal implementation details in this header file.
  37. // They are clearly marked by comments like this:
  38. //
  39. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  40. //
  41. // Such code is NOT meant to be used by a user directly, and is subject
  42. // to CHANGE WITHOUT NOTICE. Therefore DO NOT DEPEND ON IT in a user
  43. // program!
  44. //
  45. // Acknowledgment: Google Test borrowed the idea of automatic test
  46. // registration from Barthelemy Dagenais' (barthelemy@prologique.com)
  47. // easyUnit framework.
  48. // GOOGLETEST_CM0001 DO NOT DELETE
  49. #ifndef GTEST_INCLUDE_GTEST_GTEST_H_
  50. #define GTEST_INCLUDE_GTEST_GTEST_H_
  51. #include <limits>
  52. #include <ostream>
  53. #include <vector>
  54. #include "gtest/internal/gtest-internal.h"
  55. #include "gtest/internal/gtest-string.h"
  56. #include "gtest/gtest-death-test.h"
  57. #include "gtest/gtest-message.h"
  58. #include "gtest/gtest-param-test.h"
  59. #include "gtest/gtest-printers.h"
  60. #include "gtest/gtest_prod.h"
  61. #include "gtest/gtest-test-part.h"
  62. #include "gtest/gtest-typed-test.h"
  63. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
  64. /* class A needs to have dll-interface to be used by clients of class B */)
  65. // Depending on the platform, different string classes are available.
  66. // On Linux, in addition to ::std::string, Google also makes use of
  67. // class ::string, which has the same interface as ::std::string, but
  68. // has a different implementation.
  69. //
  70. // You can define GTEST_HAS_GLOBAL_STRING to 1 to indicate that
  71. // ::string is available AND is a distinct type to ::std::string, or
  72. // define it to 0 to indicate otherwise.
  73. //
  74. // If ::std::string and ::string are the same class on your platform
  75. // due to aliasing, you should define GTEST_HAS_GLOBAL_STRING to 0.
  76. //
  77. // If you do not define GTEST_HAS_GLOBAL_STRING, it is defined
  78. // heuristically.
  79. namespace testing {
  80. // Silence C4100 (unreferenced formal parameter) and 4805
  81. // unsafe mix of type 'const int' and type 'const bool'
  82. #ifdef _MSC_VER
  83. # pragma warning(push)
  84. # pragma warning(disable:4805)
  85. # pragma warning(disable:4100)
  86. #endif
  87. // Declares the flags.
  88. // This flag temporary enables the disabled tests.
  89. GTEST_DECLARE_bool_(also_run_disabled_tests);
  90. // This flag brings the debugger on an assertion failure.
  91. GTEST_DECLARE_bool_(break_on_failure);
  92. // This flag controls whether Google Test catches all test-thrown exceptions
  93. // and logs them as failures.
  94. GTEST_DECLARE_bool_(catch_exceptions);
  95. // This flag enables using colors in terminal output. Available values are
  96. // "yes" to enable colors, "no" (disable colors), or "auto" (the default)
  97. // to let Google Test decide.
  98. GTEST_DECLARE_string_(color);
  99. // This flag sets up the filter to select by name using a glob pattern
  100. // the tests to run. If the filter is not given all tests are executed.
  101. GTEST_DECLARE_string_(filter);
  102. // This flag controls whether Google Test installs a signal handler that dumps
  103. // debugging information when fatal signals are raised.
  104. GTEST_DECLARE_bool_(install_failure_signal_handler);
  105. // This flag causes the Google Test to list tests. None of the tests listed
  106. // are actually run if the flag is provided.
  107. GTEST_DECLARE_bool_(list_tests);
  108. // This flag controls whether Google Test emits a detailed XML report to a file
  109. // in addition to its normal textual output.
  110. GTEST_DECLARE_string_(output);
  111. // This flags control whether Google Test prints the elapsed time for each
  112. // test.
  113. GTEST_DECLARE_bool_(print_time);
  114. // This flags control whether Google Test prints UTF8 characters as text.
  115. GTEST_DECLARE_bool_(print_utf8);
  116. // This flag specifies the random number seed.
  117. GTEST_DECLARE_int32_(random_seed);
  118. // This flag sets how many times the tests are repeated. The default value
  119. // is 1. If the value is -1 the tests are repeating forever.
  120. GTEST_DECLARE_int32_(repeat);
  121. // This flag controls whether Google Test includes Google Test internal
  122. // stack frames in failure stack traces.
  123. GTEST_DECLARE_bool_(show_internal_stack_frames);
  124. // When this flag is specified, tests' order is randomized on every iteration.
  125. GTEST_DECLARE_bool_(shuffle);
  126. // This flag specifies the maximum number of stack frames to be
  127. // printed in a failure message.
  128. GTEST_DECLARE_int32_(stack_trace_depth);
  129. // When this flag is specified, a failed assertion will throw an
  130. // exception if exceptions are enabled, or exit the program with a
  131. // non-zero code otherwise. For use with an external test framework.
  132. GTEST_DECLARE_bool_(throw_on_failure);
  133. // When this flag is set with a "host:port" string, on supported
  134. // platforms test results are streamed to the specified port on
  135. // the specified host machine.
  136. GTEST_DECLARE_string_(stream_result_to);
  137. #if GTEST_USE_OWN_FLAGFILE_FLAG_
  138. GTEST_DECLARE_string_(flagfile);
  139. #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
  140. // The upper limit for valid stack trace depths.
  141. const int kMaxStackTraceDepth = 100;
  142. namespace internal {
  143. class AssertHelper;
  144. class DefaultGlobalTestPartResultReporter;
  145. class ExecDeathTest;
  146. class NoExecDeathTest;
  147. class FinalSuccessChecker;
  148. class GTestFlagSaver;
  149. class StreamingListenerTest;
  150. class TestResultAccessor;
  151. class TestEventListenersAccessor;
  152. class TestEventRepeater;
  153. class UnitTestRecordPropertyTestHelper;
  154. class WindowsDeathTest;
  155. class FuchsiaDeathTest;
  156. class UnitTestImpl* GetUnitTestImpl();
  157. void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
  158. const std::string& message);
  159. } // namespace internal
  160. // The friend relationship of some of these classes is cyclic.
  161. // If we don't forward declare them the compiler might confuse the classes
  162. // in friendship clauses with same named classes on the scope.
  163. class Test;
  164. class TestCase;
  165. class TestInfo;
  166. class UnitTest;
  167. // A class for indicating whether an assertion was successful. When
  168. // the assertion wasn't successful, the AssertionResult object
  169. // remembers a non-empty message that describes how it failed.
  170. //
  171. // To create an instance of this class, use one of the factory functions
  172. // (AssertionSuccess() and AssertionFailure()).
  173. //
  174. // This class is useful for two purposes:
  175. // 1. Defining predicate functions to be used with Boolean test assertions
  176. // EXPECT_TRUE/EXPECT_FALSE and their ASSERT_ counterparts
  177. // 2. Defining predicate-format functions to be
  178. // used with predicate assertions (ASSERT_PRED_FORMAT*, etc).
  179. //
  180. // For example, if you define IsEven predicate:
  181. //
  182. // testing::AssertionResult IsEven(int n) {
  183. // if ((n % 2) == 0)
  184. // return testing::AssertionSuccess();
  185. // else
  186. // return testing::AssertionFailure() << n << " is odd";
  187. // }
  188. //
  189. // Then the failed expectation EXPECT_TRUE(IsEven(Fib(5)))
  190. // will print the message
  191. //
  192. // Value of: IsEven(Fib(5))
  193. // Actual: false (5 is odd)
  194. // Expected: true
  195. //
  196. // instead of a more opaque
  197. //
  198. // Value of: IsEven(Fib(5))
  199. // Actual: false
  200. // Expected: true
  201. //
  202. // in case IsEven is a simple Boolean predicate.
  203. //
  204. // If you expect your predicate to be reused and want to support informative
  205. // messages in EXPECT_FALSE and ASSERT_FALSE (negative assertions show up
  206. // about half as often as positive ones in our tests), supply messages for
  207. // both success and failure cases:
  208. //
  209. // testing::AssertionResult IsEven(int n) {
  210. // if ((n % 2) == 0)
  211. // return testing::AssertionSuccess() << n << " is even";
  212. // else
  213. // return testing::AssertionFailure() << n << " is odd";
  214. // }
  215. //
  216. // Then a statement EXPECT_FALSE(IsEven(Fib(6))) will print
  217. //
  218. // Value of: IsEven(Fib(6))
  219. // Actual: true (8 is even)
  220. // Expected: false
  221. //
  222. // NB: Predicates that support negative Boolean assertions have reduced
  223. // performance in positive ones so be careful not to use them in tests
  224. // that have lots (tens of thousands) of positive Boolean assertions.
  225. //
  226. // To use this class with EXPECT_PRED_FORMAT assertions such as:
  227. //
  228. // // Verifies that Foo() returns an even number.
  229. // EXPECT_PRED_FORMAT1(IsEven, Foo());
  230. //
  231. // you need to define:
  232. //
  233. // testing::AssertionResult IsEven(const char* expr, int n) {
  234. // if ((n % 2) == 0)
  235. // return testing::AssertionSuccess();
  236. // else
  237. // return testing::AssertionFailure()
  238. // << "Expected: " << expr << " is even\n Actual: it's " << n;
  239. // }
  240. //
  241. // If Foo() returns 5, you will see the following message:
  242. //
  243. // Expected: Foo() is even
  244. // Actual: it's 5
  245. //
  246. class GTEST_API_ AssertionResult {
  247. public:
  248. // Copy constructor.
  249. // Used in EXPECT_TRUE/FALSE(assertion_result).
  250. AssertionResult(const AssertionResult& other);
  251. #if defined(_MSC_VER) && _MSC_VER < 1910
  252. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800 /* forcing value to bool */)
  253. #endif
  254. // Used in the EXPECT_TRUE/FALSE(bool_expression).
  255. //
  256. // T must be contextually convertible to bool.
  257. //
  258. // The second parameter prevents this overload from being considered if
  259. // the argument is implicitly convertible to AssertionResult. In that case
  260. // we want AssertionResult's copy constructor to be used.
  261. template <typename T>
  262. explicit AssertionResult(
  263. const T& success,
  264. typename internal::EnableIf<
  265. !internal::ImplicitlyConvertible<T, AssertionResult>::value>::type*
  266. /*enabler*/ = NULL)
  267. : success_(success) {}
  268. #if defined(_MSC_VER) && _MSC_VER < 1910
  269. GTEST_DISABLE_MSC_WARNINGS_POP_()
  270. #endif
  271. // Assignment operator.
  272. AssertionResult& operator=(AssertionResult other) {
  273. swap(other);
  274. return *this;
  275. }
  276. // Returns true iff the assertion succeeded.
  277. operator bool() const { return success_; } // NOLINT
  278. // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
  279. AssertionResult operator!() const;
  280. // Returns the text streamed into this AssertionResult. Test assertions
  281. // use it when they fail (i.e., the predicate's outcome doesn't match the
  282. // assertion's expectation). When nothing has been streamed into the
  283. // object, returns an empty string.
  284. const char* message() const {
  285. return message_.get() != NULL ? message_->c_str() : "";
  286. }
  287. // FIXME: Remove this after making sure no clients use it.
  288. // Deprecated; please use message() instead.
  289. const char* failure_message() const { return message(); }
  290. // Streams a custom failure message into this object.
  291. template <typename T> AssertionResult& operator<<(const T& value) {
  292. AppendMessage(Message() << value);
  293. return *this;
  294. }
  295. // Allows streaming basic output manipulators such as endl or flush into
  296. // this object.
  297. AssertionResult& operator<<(
  298. ::std::ostream& (*basic_manipulator)(::std::ostream& stream)) {
  299. AppendMessage(Message() << basic_manipulator);
  300. return *this;
  301. }
  302. private:
  303. // Appends the contents of message to message_.
  304. void AppendMessage(const Message& a_message) {
  305. if (message_.get() == NULL)
  306. message_.reset(new ::std::string);
  307. message_->append(a_message.GetString().c_str());
  308. }
  309. // Swap the contents of this AssertionResult with other.
  310. void swap(AssertionResult& other);
  311. // Stores result of the assertion predicate.
  312. bool success_;
  313. // Stores the message describing the condition in case the expectation
  314. // construct is not satisfied with the predicate's outcome.
  315. // Referenced via a pointer to avoid taking too much stack frame space
  316. // with test assertions.
  317. internal::scoped_ptr< ::std::string> message_;
  318. };
  319. // Makes a successful assertion result.
  320. GTEST_API_ AssertionResult AssertionSuccess();
  321. // Makes a failed assertion result.
  322. GTEST_API_ AssertionResult AssertionFailure();
  323. // Makes a failed assertion result with the given failure message.
  324. // Deprecated; use AssertionFailure() << msg.
  325. GTEST_API_ AssertionResult AssertionFailure(const Message& msg);
  326. } // namespace testing
  327. // Includes the auto-generated header that implements a family of generic
  328. // predicate assertion macros. This include comes late because it relies on
  329. // APIs declared above.
  330. #include "gtest/gtest_pred_impl.h"
  331. namespace testing {
  332. // The abstract class that all tests inherit from.
  333. //
  334. // In Google Test, a unit test program contains one or many TestCases, and
  335. // each TestCase contains one or many Tests.
  336. //
  337. // When you define a test using the TEST macro, you don't need to
  338. // explicitly derive from Test - the TEST macro automatically does
  339. // this for you.
  340. //
  341. // The only time you derive from Test is when defining a test fixture
  342. // to be used in a TEST_F. For example:
  343. //
  344. // class FooTest : public testing::Test {
  345. // protected:
  346. // void SetUp() override { ... }
  347. // void TearDown() override { ... }
  348. // ...
  349. // };
  350. //
  351. // TEST_F(FooTest, Bar) { ... }
  352. // TEST_F(FooTest, Baz) { ... }
  353. //
  354. // Test is not copyable.
  355. class GTEST_API_ Test {
  356. public:
  357. friend class TestInfo;
  358. // Defines types for pointers to functions that set up and tear down
  359. // a test case.
  360. typedef internal::SetUpTestCaseFunc SetUpTestCaseFunc;
  361. typedef internal::TearDownTestCaseFunc TearDownTestCaseFunc;
  362. // The d'tor is virtual as we intend to inherit from Test.
  363. virtual ~Test();
  364. // Sets up the stuff shared by all tests in this test case.
  365. //
  366. // Google Test will call Foo::SetUpTestCase() before running the first
  367. // test in test case Foo. Hence a sub-class can define its own
  368. // SetUpTestCase() method to shadow the one defined in the super
  369. // class.
  370. static void SetUpTestCase() {}
  371. // Tears down the stuff shared by all tests in this test case.
  372. //
  373. // Google Test will call Foo::TearDownTestCase() after running the last
  374. // test in test case Foo. Hence a sub-class can define its own
  375. // TearDownTestCase() method to shadow the one defined in the super
  376. // class.
  377. static void TearDownTestCase() {}
  378. // Returns true iff the current test has a fatal failure.
  379. static bool HasFatalFailure();
  380. // Returns true iff the current test has a non-fatal failure.
  381. static bool HasNonfatalFailure();
  382. // Returns true iff the current test has a (either fatal or
  383. // non-fatal) failure.
  384. static bool HasFailure() { return HasFatalFailure() || HasNonfatalFailure(); }
  385. // Logs a property for the current test, test case, or for the entire
  386. // invocation of the test program when used outside of the context of a
  387. // test case. Only the last value for a given key is remembered. These
  388. // are public static so they can be called from utility functions that are
  389. // not members of the test fixture. Calls to RecordProperty made during
  390. // lifespan of the test (from the moment its constructor starts to the
  391. // moment its destructor finishes) will be output in XML as attributes of
  392. // the <testcase> element. Properties recorded from fixture's
  393. // SetUpTestCase or TearDownTestCase are logged as attributes of the
  394. // corresponding <testsuite> element. Calls to RecordProperty made in the
  395. // global context (before or after invocation of RUN_ALL_TESTS and from
  396. // SetUp/TearDown method of Environment objects registered with Google
  397. // Test) will be output as attributes of the <testsuites> element.
  398. static void RecordProperty(const std::string& key, const std::string& value);
  399. static void RecordProperty(const std::string& key, int value);
  400. protected:
  401. // Creates a Test object.
  402. Test();
  403. // Sets up the test fixture.
  404. virtual void SetUp();
  405. // Tears down the test fixture.
  406. virtual void TearDown();
  407. private:
  408. // Returns true iff the current test has the same fixture class as
  409. // the first test in the current test case.
  410. static bool HasSameFixtureClass();
  411. // Runs the test after the test fixture has been set up.
  412. //
  413. // A sub-class must implement this to define the test logic.
  414. //
  415. // DO NOT OVERRIDE THIS FUNCTION DIRECTLY IN A USER PROGRAM.
  416. // Instead, use the TEST or TEST_F macro.
  417. virtual void TestBody() = 0;
  418. // Sets up, executes, and tears down the test.
  419. void Run();
  420. // Deletes self. We deliberately pick an unusual name for this
  421. // internal method to avoid clashing with names used in user TESTs.
  422. void DeleteSelf_() { delete this; }
  423. const internal::scoped_ptr< GTEST_FLAG_SAVER_ > gtest_flag_saver_;
  424. // Often a user misspells SetUp() as Setup() and spends a long time
  425. // wondering why it is never called by Google Test. The declaration of
  426. // the following method is solely for catching such an error at
  427. // compile time:
  428. //
  429. // - The return type is deliberately chosen to be not void, so it
  430. // will be a conflict if void Setup() is declared in the user's
  431. // test fixture.
  432. //
  433. // - This method is private, so it will be another compiler error
  434. // if the method is called from the user's test fixture.
  435. //
  436. // DO NOT OVERRIDE THIS FUNCTION.
  437. //
  438. // If you see an error about overriding the following function or
  439. // about it being private, you have mis-spelled SetUp() as Setup().
  440. struct Setup_should_be_spelled_SetUp {};
  441. virtual Setup_should_be_spelled_SetUp* Setup() { return NULL; }
  442. // We disallow copying Tests.
  443. GTEST_DISALLOW_COPY_AND_ASSIGN_(Test);
  444. };
  445. typedef internal::TimeInMillis TimeInMillis;
  446. // A copyable object representing a user specified test property which can be
  447. // output as a key/value string pair.
  448. //
  449. // Don't inherit from TestProperty as its destructor is not virtual.
  450. class TestProperty {
  451. public:
  452. // C'tor. TestProperty does NOT have a default constructor.
  453. // Always use this constructor (with parameters) to create a
  454. // TestProperty object.
  455. TestProperty(const std::string& a_key, const std::string& a_value) :
  456. key_(a_key), value_(a_value) {
  457. }
  458. // Gets the user supplied key.
  459. const char* key() const {
  460. return key_.c_str();
  461. }
  462. // Gets the user supplied value.
  463. const char* value() const {
  464. return value_.c_str();
  465. }
  466. // Sets a new value, overriding the one supplied in the constructor.
  467. void SetValue(const std::string& new_value) {
  468. value_ = new_value;
  469. }
  470. private:
  471. // The key supplied by the user.
  472. std::string key_;
  473. // The value supplied by the user.
  474. std::string value_;
  475. };
  476. // The result of a single Test. This includes a list of
  477. // TestPartResults, a list of TestProperties, a count of how many
  478. // death tests there are in the Test, and how much time it took to run
  479. // the Test.
  480. //
  481. // TestResult is not copyable.
  482. class GTEST_API_ TestResult {
  483. public:
  484. // Creates an empty TestResult.
  485. TestResult();
  486. // D'tor. Do not inherit from TestResult.
  487. ~TestResult();
  488. // Gets the number of all test parts. This is the sum of the number
  489. // of successful test parts and the number of failed test parts.
  490. int total_part_count() const;
  491. // Returns the number of the test properties.
  492. int test_property_count() const;
  493. // Returns true iff the test passed (i.e. no test part failed).
  494. bool Passed() const { return !Failed(); }
  495. // Returns true iff the test failed.
  496. bool Failed() const;
  497. // Returns true iff the test fatally failed.
  498. bool HasFatalFailure() const;
  499. // Returns true iff the test has a non-fatal failure.
  500. bool HasNonfatalFailure() const;
  501. // Returns the elapsed time, in milliseconds.
  502. TimeInMillis elapsed_time() const { return elapsed_time_; }
  503. // Returns the i-th test part result among all the results. i can range from 0
  504. // to total_part_count() - 1. If i is not in that range, aborts the program.
  505. const TestPartResult& GetTestPartResult(int i) const;
  506. // Returns the i-th test property. i can range from 0 to
  507. // test_property_count() - 1. If i is not in that range, aborts the
  508. // program.
  509. const TestProperty& GetTestProperty(int i) const;
  510. private:
  511. friend class TestInfo;
  512. friend class TestCase;
  513. friend class UnitTest;
  514. friend class internal::DefaultGlobalTestPartResultReporter;
  515. friend class internal::ExecDeathTest;
  516. friend class internal::TestResultAccessor;
  517. friend class internal::UnitTestImpl;
  518. friend class internal::WindowsDeathTest;
  519. friend class internal::FuchsiaDeathTest;
  520. // Gets the vector of TestPartResults.
  521. const std::vector<TestPartResult>& test_part_results() const {
  522. return test_part_results_;
  523. }
  524. // Gets the vector of TestProperties.
  525. const std::vector<TestProperty>& test_properties() const {
  526. return test_properties_;
  527. }
  528. // Sets the elapsed time.
  529. void set_elapsed_time(TimeInMillis elapsed) { elapsed_time_ = elapsed; }
  530. // Adds a test property to the list. The property is validated and may add
  531. // a non-fatal failure if invalid (e.g., if it conflicts with reserved
  532. // key names). If a property is already recorded for the same key, the
  533. // value will be updated, rather than storing multiple values for the same
  534. // key. xml_element specifies the element for which the property is being
  535. // recorded and is used for validation.
  536. void RecordProperty(const std::string& xml_element,
  537. const TestProperty& test_property);
  538. // Adds a failure if the key is a reserved attribute of Google Test
  539. // testcase tags. Returns true if the property is valid.
  540. // FIXME: Validate attribute names are legal and human readable.
  541. static bool ValidateTestProperty(const std::string& xml_element,
  542. const TestProperty& test_property);
  543. // Adds a test part result to the list.
  544. void AddTestPartResult(const TestPartResult& test_part_result);
  545. // Returns the death test count.
  546. int death_test_count() const { return death_test_count_; }
  547. // Increments the death test count, returning the new count.
  548. int increment_death_test_count() { return ++death_test_count_; }
  549. // Clears the test part results.
  550. void ClearTestPartResults();
  551. // Clears the object.
  552. void Clear();
  553. // Protects mutable state of the property vector and of owned
  554. // properties, whose values may be updated.
  555. internal::Mutex test_properites_mutex_;
  556. // The vector of TestPartResults
  557. std::vector<TestPartResult> test_part_results_;
  558. // The vector of TestProperties
  559. std::vector<TestProperty> test_properties_;
  560. // Running count of death tests.
  561. int death_test_count_;
  562. // The elapsed time, in milliseconds.
  563. TimeInMillis elapsed_time_;
  564. // We disallow copying TestResult.
  565. GTEST_DISALLOW_COPY_AND_ASSIGN_(TestResult);
  566. }; // class TestResult
  567. // A TestInfo object stores the following information about a test:
  568. //
  569. // Test case name
  570. // Test name
  571. // Whether the test should be run
  572. // A function pointer that creates the test object when invoked
  573. // Test result
  574. //
  575. // The constructor of TestInfo registers itself with the UnitTest
  576. // singleton such that the RUN_ALL_TESTS() macro knows which tests to
  577. // run.
  578. class GTEST_API_ TestInfo {
  579. public:
  580. // Destructs a TestInfo object. This function is not virtual, so
  581. // don't inherit from TestInfo.
  582. ~TestInfo();
  583. // Returns the test case name.
  584. const char* test_case_name() const { return test_case_name_.c_str(); }
  585. // Returns the test name.
  586. const char* name() const { return name_.c_str(); }
  587. // Returns the name of the parameter type, or NULL if this is not a typed
  588. // or a type-parameterized test.
  589. const char* type_param() const {
  590. if (type_param_.get() != NULL)
  591. return type_param_->c_str();
  592. return NULL;
  593. }
  594. // Returns the text representation of the value parameter, or NULL if this
  595. // is not a value-parameterized test.
  596. const char* value_param() const {
  597. if (value_param_.get() != NULL)
  598. return value_param_->c_str();
  599. return NULL;
  600. }
  601. // Returns the file name where this test is defined.
  602. const char* file() const { return location_.file.c_str(); }
  603. // Returns the line where this test is defined.
  604. int line() const { return location_.line; }
  605. // Return true if this test should not be run because it's in another shard.
  606. bool is_in_another_shard() const { return is_in_another_shard_; }
  607. // Returns true if this test should run, that is if the test is not
  608. // disabled (or it is disabled but the also_run_disabled_tests flag has
  609. // been specified) and its full name matches the user-specified filter.
  610. //
  611. // Google Test allows the user to filter the tests by their full names.
  612. // The full name of a test Bar in test case Foo is defined as
  613. // "Foo.Bar". Only the tests that match the filter will run.
  614. //
  615. // A filter is a colon-separated list of glob (not regex) patterns,
  616. // optionally followed by a '-' and a colon-separated list of
  617. // negative patterns (tests to exclude). A test is run if it
  618. // matches one of the positive patterns and does not match any of
  619. // the negative patterns.
  620. //
  621. // For example, *A*:Foo.* is a filter that matches any string that
  622. // contains the character 'A' or starts with "Foo.".
  623. bool should_run() const { return should_run_; }
  624. // Returns true iff this test will appear in the XML report.
  625. bool is_reportable() const {
  626. // The XML report includes tests matching the filter, excluding those
  627. // run in other shards.
  628. return matches_filter_ && !is_in_another_shard_;
  629. }
  630. // Returns the result of the test.
  631. const TestResult* result() const { return &result_; }
  632. private:
  633. #if GTEST_HAS_DEATH_TEST
  634. friend class internal::DefaultDeathTestFactory;
  635. #endif // GTEST_HAS_DEATH_TEST
  636. friend class Test;
  637. friend class TestCase;
  638. friend class internal::UnitTestImpl;
  639. friend class internal::StreamingListenerTest;
  640. friend TestInfo* internal::MakeAndRegisterTestInfo(
  641. const char* test_case_name,
  642. const char* name,
  643. const char* type_param,
  644. const char* value_param,
  645. internal::CodeLocation code_location,
  646. internal::TypeId fixture_class_id,
  647. Test::SetUpTestCaseFunc set_up_tc,
  648. Test::TearDownTestCaseFunc tear_down_tc,
  649. internal::TestFactoryBase* factory);
  650. // Constructs a TestInfo object. The newly constructed instance assumes
  651. // ownership of the factory object.
  652. TestInfo(const std::string& test_case_name,
  653. const std::string& name,
  654. const char* a_type_param, // NULL if not a type-parameterized test
  655. const char* a_value_param, // NULL if not a value-parameterized test
  656. internal::CodeLocation a_code_location,
  657. internal::TypeId fixture_class_id,
  658. internal::TestFactoryBase* factory);
  659. // Increments the number of death tests encountered in this test so
  660. // far.
  661. int increment_death_test_count() {
  662. return result_.increment_death_test_count();
  663. }
  664. // Creates the test object, runs it, records its result, and then
  665. // deletes it.
  666. void Run();
  667. static void ClearTestResult(TestInfo* test_info) {
  668. test_info->result_.Clear();
  669. }
  670. // These fields are immutable properties of the test.
  671. const std::string test_case_name_; // Test case name
  672. const std::string name_; // Test name
  673. // Name of the parameter type, or NULL if this is not a typed or a
  674. // type-parameterized test.
  675. const internal::scoped_ptr<const ::std::string> type_param_;
  676. // Text representation of the value parameter, or NULL if this is not a
  677. // value-parameterized test.
  678. const internal::scoped_ptr<const ::std::string> value_param_;
  679. internal::CodeLocation location_;
  680. const internal::TypeId fixture_class_id_; // ID of the test fixture class
  681. bool should_run_; // True iff this test should run
  682. bool is_disabled_; // True iff this test is disabled
  683. bool matches_filter_; // True if this test matches the
  684. // user-specified filter.
  685. bool is_in_another_shard_; // Will be run in another shard.
  686. internal::TestFactoryBase* const factory_; // The factory that creates
  687. // the test object
  688. // This field is mutable and needs to be reset before running the
  689. // test for the second time.
  690. TestResult result_;
  691. GTEST_DISALLOW_COPY_AND_ASSIGN_(TestInfo);
  692. };
  693. // A test case, which consists of a vector of TestInfos.
  694. //
  695. // TestCase is not copyable.
  696. class GTEST_API_ TestCase {
  697. public:
  698. // Creates a TestCase with the given name.
  699. //
  700. // TestCase does NOT have a default constructor. Always use this
  701. // constructor to create a TestCase object.
  702. //
  703. // Arguments:
  704. //
  705. // name: name of the test case
  706. // a_type_param: the name of the test's type parameter, or NULL if
  707. // this is not a type-parameterized test.
  708. // set_up_tc: pointer to the function that sets up the test case
  709. // tear_down_tc: pointer to the function that tears down the test case
  710. TestCase(const char* name, const char* a_type_param,
  711. Test::SetUpTestCaseFunc set_up_tc,
  712. Test::TearDownTestCaseFunc tear_down_tc);
  713. // Destructor of TestCase.
  714. virtual ~TestCase();
  715. // Gets the name of the TestCase.
  716. const char* name() const { return name_.c_str(); }
  717. // Returns the name of the parameter type, or NULL if this is not a
  718. // type-parameterized test case.
  719. const char* type_param() const {
  720. if (type_param_.get() != NULL)
  721. return type_param_->c_str();
  722. return NULL;
  723. }
  724. // Returns true if any test in this test case should run.
  725. bool should_run() const { return should_run_; }
  726. // Gets the number of successful tests in this test case.
  727. int successful_test_count() const;
  728. // Gets the number of failed tests in this test case.
  729. int failed_test_count() const;
  730. // Gets the number of disabled tests that will be reported in the XML report.
  731. int reportable_disabled_test_count() const;
  732. // Gets the number of disabled tests in this test case.
  733. int disabled_test_count() const;
  734. // Gets the number of tests to be printed in the XML report.
  735. int reportable_test_count() const;
  736. // Get the number of tests in this test case that should run.
  737. int test_to_run_count() const;
  738. // Gets the number of all tests in this test case.
  739. int total_test_count() const;
  740. // Returns true iff the test case passed.
  741. bool Passed() const { return !Failed(); }
  742. // Returns true iff the test case failed.
  743. bool Failed() const { return failed_test_count() > 0; }
  744. // Returns the elapsed time, in milliseconds.
  745. TimeInMillis elapsed_time() const { return elapsed_time_; }
  746. // Returns the i-th test among all the tests. i can range from 0 to
  747. // total_test_count() - 1. If i is not in that range, returns NULL.
  748. const TestInfo* GetTestInfo(int i) const;
  749. // Returns the TestResult that holds test properties recorded during
  750. // execution of SetUpTestCase and TearDownTestCase.
  751. const TestResult& ad_hoc_test_result() const { return ad_hoc_test_result_; }
  752. private:
  753. friend class Test;
  754. friend class internal::UnitTestImpl;
  755. // Gets the (mutable) vector of TestInfos in this TestCase.
  756. std::vector<TestInfo*>& test_info_list() { return test_info_list_; }
  757. // Gets the (immutable) vector of TestInfos in this TestCase.
  758. const std::vector<TestInfo*>& test_info_list() const {
  759. return test_info_list_;
  760. }
  761. // Returns the i-th test among all the tests. i can range from 0 to
  762. // total_test_count() - 1. If i is not in that range, returns NULL.
  763. TestInfo* GetMutableTestInfo(int i);
  764. // Sets the should_run member.
  765. void set_should_run(bool should) { should_run_ = should; }
  766. // Adds a TestInfo to this test case. Will delete the TestInfo upon
  767. // destruction of the TestCase object.
  768. void AddTestInfo(TestInfo * test_info);
  769. // Clears the results of all tests in this test case.
  770. void ClearResult();
  771. // Clears the results of all tests in the given test case.
  772. static void ClearTestCaseResult(TestCase* test_case) {
  773. test_case->ClearResult();
  774. }
  775. // Runs every test in this TestCase.
  776. void Run();
  777. // Runs SetUpTestCase() for this TestCase. This wrapper is needed
  778. // for catching exceptions thrown from SetUpTestCase().
  779. void RunSetUpTestCase() { (*set_up_tc_)(); }
  780. // Runs TearDownTestCase() for this TestCase. This wrapper is
  781. // needed for catching exceptions thrown from TearDownTestCase().
  782. void RunTearDownTestCase() { (*tear_down_tc_)(); }
  783. // Returns true iff test passed.
  784. static bool TestPassed(const TestInfo* test_info) {
  785. return test_info->should_run() && test_info->result()->Passed();
  786. }
  787. // Returns true iff test failed.
  788. static bool TestFailed(const TestInfo* test_info) {
  789. return test_info->should_run() && test_info->result()->Failed();
  790. }
  791. // Returns true iff the test is disabled and will be reported in the XML
  792. // report.
  793. static bool TestReportableDisabled(const TestInfo* test_info) {
  794. return test_info->is_reportable() && test_info->is_disabled_;
  795. }
  796. // Returns true iff test is disabled.
  797. static bool TestDisabled(const TestInfo* test_info) {
  798. return test_info->is_disabled_;
  799. }
  800. // Returns true iff this test will appear in the XML report.
  801. static bool TestReportable(const TestInfo* test_info) {
  802. return test_info->is_reportable();
  803. }
  804. // Returns true if the given test should run.
  805. static bool ShouldRunTest(const TestInfo* test_info) {
  806. return test_info->should_run();
  807. }
  808. // Shuffles the tests in this test case.
  809. void ShuffleTests(internal::Random* random);
  810. // Restores the test order to before the first shuffle.
  811. void UnshuffleTests();
  812. // Name of the test case.
  813. std::string name_;
  814. // Name of the parameter type, or NULL if this is not a typed or a
  815. // type-parameterized test.
  816. const internal::scoped_ptr<const ::std::string> type_param_;
  817. // The vector of TestInfos in their original order. It owns the
  818. // elements in the vector.
  819. std::vector<TestInfo*> test_info_list_;
  820. // Provides a level of indirection for the test list to allow easy
  821. // shuffling and restoring the test order. The i-th element in this
  822. // vector is the index of the i-th test in the shuffled test list.
  823. std::vector<int> test_indices_;
  824. // Pointer to the function that sets up the test case.
  825. Test::SetUpTestCaseFunc set_up_tc_;
  826. // Pointer to the function that tears down the test case.
  827. Test::TearDownTestCaseFunc tear_down_tc_;
  828. // True iff any test in this test case should run.
  829. bool should_run_;
  830. // Elapsed time, in milliseconds.
  831. TimeInMillis elapsed_time_;
  832. // Holds test properties recorded during execution of SetUpTestCase and
  833. // TearDownTestCase.
  834. TestResult ad_hoc_test_result_;
  835. // We disallow copying TestCases.
  836. GTEST_DISALLOW_COPY_AND_ASSIGN_(TestCase);
  837. };
  838. // An Environment object is capable of setting up and tearing down an
  839. // environment. You should subclass this to define your own
  840. // environment(s).
  841. //
  842. // An Environment object does the set-up and tear-down in virtual
  843. // methods SetUp() and TearDown() instead of the constructor and the
  844. // destructor, as:
  845. //
  846. // 1. You cannot safely throw from a destructor. This is a problem
  847. // as in some cases Google Test is used where exceptions are enabled, and
  848. // we may want to implement ASSERT_* using exceptions where they are
  849. // available.
  850. // 2. You cannot use ASSERT_* directly in a constructor or
  851. // destructor.
  852. class Environment {
  853. public:
  854. // The d'tor is virtual as we need to subclass Environment.
  855. virtual ~Environment() {}
  856. // Override this to define how to set up the environment.
  857. virtual void SetUp() {}
  858. // Override this to define how to tear down the environment.
  859. virtual void TearDown() {}
  860. private:
  861. // If you see an error about overriding the following function or
  862. // about it being private, you have mis-spelled SetUp() as Setup().
  863. struct Setup_should_be_spelled_SetUp {};
  864. virtual Setup_should_be_spelled_SetUp* Setup() { return NULL; }
  865. };
  866. #if GTEST_HAS_EXCEPTIONS
  867. // Exception which can be thrown from TestEventListener::OnTestPartResult.
  868. class GTEST_API_ AssertionException
  869. : public internal::GoogleTestFailureException {
  870. public:
  871. explicit AssertionException(const TestPartResult& result)
  872. : GoogleTestFailureException(result) {}
  873. };
  874. #endif // GTEST_HAS_EXCEPTIONS
  875. // The interface for tracing execution of tests. The methods are organized in
  876. // the order the corresponding events are fired.
  877. class TestEventListener {
  878. public:
  879. virtual ~TestEventListener() {}
  880. // Fired before any test activity starts.
  881. virtual void OnTestProgramStart(const UnitTest& unit_test) = 0;
  882. // Fired before each iteration of tests starts. There may be more than
  883. // one iteration if GTEST_FLAG(repeat) is set. iteration is the iteration
  884. // index, starting from 0.
  885. virtual void OnTestIterationStart(const UnitTest& unit_test,
  886. int iteration) = 0;
  887. // Fired before environment set-up for each iteration of tests starts.
  888. virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test) = 0;
  889. // Fired after environment set-up for each iteration of tests ends.
  890. virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test) = 0;
  891. // Fired before the test case starts.
  892. virtual void OnTestCaseStart(const TestCase& test_case) = 0;
  893. // Fired before the test starts.
  894. virtual void OnTestStart(const TestInfo& test_info) = 0;
  895. // Fired after a failed assertion or a SUCCEED() invocation.
  896. // If you want to throw an exception from this function to skip to the next
  897. // TEST, it must be AssertionException defined above, or inherited from it.
  898. virtual void OnTestPartResult(const TestPartResult& test_part_result) = 0;
  899. // Fired after the test ends.
  900. virtual void OnTestEnd(const TestInfo& test_info) = 0;
  901. // Fired after the test case ends.
  902. virtual void OnTestCaseEnd(const TestCase& test_case) = 0;
  903. // Fired before environment tear-down for each iteration of tests starts.
  904. virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test) = 0;
  905. // Fired after environment tear-down for each iteration of tests ends.
  906. virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) = 0;
  907. // Fired after each iteration of tests finishes.
  908. virtual void OnTestIterationEnd(const UnitTest& unit_test,
  909. int iteration) = 0;
  910. // Fired after all test activities have ended.
  911. virtual void OnTestProgramEnd(const UnitTest& unit_test) = 0;
  912. };
  913. // The convenience class for users who need to override just one or two
  914. // methods and are not concerned that a possible change to a signature of
  915. // the methods they override will not be caught during the build. For
  916. // comments about each method please see the definition of TestEventListener
  917. // above.
  918. class EmptyTestEventListener : public TestEventListener {
  919. public:
  920. virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {}
  921. virtual void OnTestIterationStart(const UnitTest& /*unit_test*/,
  922. int /*iteration*/) {}
  923. virtual void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) {}
  924. virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {}
  925. virtual void OnTestCaseStart(const TestCase& /*test_case*/) {}
  926. virtual void OnTestStart(const TestInfo& /*test_info*/) {}
  927. virtual void OnTestPartResult(const TestPartResult& /*test_part_result*/) {}
  928. virtual void OnTestEnd(const TestInfo& /*test_info*/) {}
  929. virtual void OnTestCaseEnd(const TestCase& /*test_case*/) {}
  930. virtual void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) {}
  931. virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {}
  932. virtual void OnTestIterationEnd(const UnitTest& /*unit_test*/,
  933. int /*iteration*/) {}
  934. virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {}
  935. };
  936. // TestEventListeners lets users add listeners to track events in Google Test.
  937. class GTEST_API_ TestEventListeners {
  938. public:
  939. TestEventListeners();
  940. ~TestEventListeners();
  941. // Appends an event listener to the end of the list. Google Test assumes
  942. // the ownership of the listener (i.e. it will delete the listener when
  943. // the test program finishes).
  944. void Append(TestEventListener* listener);
  945. // Removes the given event listener from the list and returns it. It then
  946. // becomes the caller's responsibility to delete the listener. Returns
  947. // NULL if the listener is not found in the list.
  948. TestEventListener* Release(TestEventListener* listener);
  949. // Returns the standard listener responsible for the default console
  950. // output. Can be removed from the listeners list to shut down default
  951. // console output. Note that removing this object from the listener list
  952. // with Release transfers its ownership to the caller and makes this
  953. // function return NULL the next time.
  954. TestEventListener* default_result_printer() const {
  955. return default_result_printer_;
  956. }
  957. // Returns the standard listener responsible for the default XML output
  958. // controlled by the --gtest_output=xml flag. Can be removed from the
  959. // listeners list by users who want to shut down the default XML output
  960. // controlled by this flag and substitute it with custom one. Note that
  961. // removing this object from the listener list with Release transfers its
  962. // ownership to the caller and makes this function return NULL the next
  963. // time.
  964. TestEventListener* default_xml_generator() const {
  965. return default_xml_generator_;
  966. }
  967. private:
  968. friend class TestCase;
  969. friend class TestInfo;
  970. friend class internal::DefaultGlobalTestPartResultReporter;
  971. friend class internal::NoExecDeathTest;
  972. friend class internal::TestEventListenersAccessor;
  973. friend class internal::UnitTestImpl;
  974. // Returns repeater that broadcasts the TestEventListener events to all
  975. // subscribers.
  976. TestEventListener* repeater();
  977. // Sets the default_result_printer attribute to the provided listener.
  978. // The listener is also added to the listener list and previous
  979. // default_result_printer is removed from it and deleted. The listener can
  980. // also be NULL in which case it will not be added to the list. Does
  981. // nothing if the previous and the current listener objects are the same.
  982. void SetDefaultResultPrinter(TestEventListener* listener);
  983. // Sets the default_xml_generator attribute to the provided listener. The
  984. // listener is also added to the listener list and previous
  985. // default_xml_generator is removed from it and deleted. The listener can
  986. // also be NULL in which case it will not be added to the list. Does
  987. // nothing if the previous and the current listener objects are the same.
  988. void SetDefaultXmlGenerator(TestEventListener* listener);
  989. // Controls whether events will be forwarded by the repeater to the
  990. // listeners in the list.
  991. bool EventForwardingEnabled() const;
  992. void SuppressEventForwarding();
  993. // The actual list of listeners.
  994. internal::TestEventRepeater* repeater_;
  995. // Listener responsible for the standard result output.
  996. TestEventListener* default_result_printer_;
  997. // Listener responsible for the creation of the XML output file.
  998. TestEventListener* default_xml_generator_;
  999. // We disallow copying TestEventListeners.
  1000. GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventListeners);
  1001. };
  1002. // A UnitTest consists of a vector of TestCases.
  1003. //
  1004. // This is a singleton class. The only instance of UnitTest is
  1005. // created when UnitTest::GetInstance() is first called. This
  1006. // instance is never deleted.
  1007. //
  1008. // UnitTest is not copyable.
  1009. //
  1010. // This class is thread-safe as long as the methods are called
  1011. // according to their specification.
  1012. class GTEST_API_ UnitTest {
  1013. public:
  1014. // Gets the singleton UnitTest object. The first time this method
  1015. // is called, a UnitTest object is constructed and returned.
  1016. // Consecutive calls will return the same object.
  1017. static UnitTest* GetInstance();
  1018. // Runs all tests in this UnitTest object and prints the result.
  1019. // Returns 0 if successful, or 1 otherwise.
  1020. //
  1021. // This method can only be called from the main thread.
  1022. //
  1023. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  1024. int Run() GTEST_MUST_USE_RESULT_;
  1025. // Returns the working directory when the first TEST() or TEST_F()
  1026. // was executed. The UnitTest object owns the string.
  1027. const char* original_working_dir() const;
  1028. // Returns the TestCase object for the test that's currently running,
  1029. // or NULL if no test is running.
  1030. const TestCase* current_test_case() const
  1031. GTEST_LOCK_EXCLUDED_(mutex_);
  1032. // Returns the TestInfo object for the test that's currently running,
  1033. // or NULL if no test is running.
  1034. const TestInfo* current_test_info() const
  1035. GTEST_LOCK_EXCLUDED_(mutex_);
  1036. // Returns the random seed used at the start of the current test run.
  1037. int random_seed() const;
  1038. // Returns the ParameterizedTestCaseRegistry object used to keep track of
  1039. // value-parameterized tests and instantiate and register them.
  1040. //
  1041. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  1042. internal::ParameterizedTestCaseRegistry& parameterized_test_registry()
  1043. GTEST_LOCK_EXCLUDED_(mutex_);
  1044. // Gets the number of successful test cases.
  1045. int successful_test_case_count() const;
  1046. // Gets the number of failed test cases.
  1047. int failed_test_case_count() const;
  1048. // Gets the number of all test cases.
  1049. int total_test_case_count() const;
  1050. // Gets the number of all test cases that contain at least one test
  1051. // that should run.
  1052. int test_case_to_run_count() const;
  1053. // Gets the number of successful tests.
  1054. int successful_test_count() const;
  1055. // Gets the number of failed tests.
  1056. int failed_test_count() const;
  1057. // Gets the number of disabled tests that will be reported in the XML report.
  1058. int reportable_disabled_test_count() const;
  1059. // Gets the number of disabled tests.
  1060. int disabled_test_count() const;
  1061. // Gets the number of tests to be printed in the XML report.
  1062. int reportable_test_count() const;
  1063. // Gets the number of all tests.
  1064. int total_test_count() const;
  1065. // Gets the number of tests that should run.
  1066. int test_to_run_count() const;
  1067. // Gets the time of the test program start, in ms from the start of the
  1068. // UNIX epoch.
  1069. TimeInMillis start_timestamp() const;
  1070. // Gets the elapsed time, in milliseconds.
  1071. TimeInMillis elapsed_time() const;
  1072. // Returns true iff the unit test passed (i.e. all test cases passed).
  1073. bool Passed() const;
  1074. // Returns true iff the unit test failed (i.e. some test case failed
  1075. // or something outside of all tests failed).
  1076. bool Failed() const;
  1077. // Gets the i-th test case among all the test cases. i can range from 0 to
  1078. // total_test_case_count() - 1. If i is not in that range, returns NULL.
  1079. const TestCase* GetTestCase(int i) const;
  1080. // Returns the TestResult containing information on test failures and
  1081. // properties logged outside of individual test cases.
  1082. const TestResult& ad_hoc_test_result() const;
  1083. // Returns the list of event listeners that can be used to track events
  1084. // inside Google Test.
  1085. TestEventListeners& listeners();
  1086. private:
  1087. // Registers and returns a global test environment. When a test
  1088. // program is run, all global test environments will be set-up in
  1089. // the order they were registered. After all tests in the program
  1090. // have finished, all global test environments will be torn-down in
  1091. // the *reverse* order they were registered.
  1092. //
  1093. // The UnitTest object takes ownership of the given environment.
  1094. //
  1095. // This method can only be called from the main thread.
  1096. Environment* AddEnvironment(Environment* env);
  1097. // Adds a TestPartResult to the current TestResult object. All
  1098. // Google Test assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc)
  1099. // eventually call this to report their results. The user code
  1100. // should use the assertion macros instead of calling this directly.
  1101. void AddTestPartResult(TestPartResult::Type result_type,
  1102. const char* file_name,
  1103. int line_number,
  1104. const std::string& message,
  1105. const std::string& os_stack_trace)
  1106. GTEST_LOCK_EXCLUDED_(mutex_);
  1107. // Adds a TestProperty to the current TestResult object when invoked from
  1108. // inside a test, to current TestCase's ad_hoc_test_result_ when invoked
  1109. // from SetUpTestCase or TearDownTestCase, or to the global property set
  1110. // when invoked elsewhere. If the result already contains a property with
  1111. // the same key, the value will be updated.
  1112. void RecordProperty(const std::string& key, const std::string& value);
  1113. // Gets the i-th test case among all the test cases. i can range from 0 to
  1114. // total_test_case_count() - 1. If i is not in that range, returns NULL.
  1115. TestCase* GetMutableTestCase(int i);
  1116. // Accessors for the implementation object.
  1117. internal::UnitTestImpl* impl() { return impl_; }
  1118. const internal::UnitTestImpl* impl() const { return impl_; }
  1119. // These classes and functions are friends as they need to access private
  1120. // members of UnitTest.
  1121. friend class ScopedTrace;
  1122. friend class Test;
  1123. friend class internal::AssertHelper;
  1124. friend class internal::StreamingListenerTest;
  1125. friend class internal::UnitTestRecordPropertyTestHelper;
  1126. friend Environment* AddGlobalTestEnvironment(Environment* env);
  1127. friend internal::UnitTestImpl* internal::GetUnitTestImpl();
  1128. friend void internal::ReportFailureInUnknownLocation(
  1129. TestPartResult::Type result_type,
  1130. const std::string& message);
  1131. // Creates an empty UnitTest.
  1132. UnitTest();
  1133. // D'tor
  1134. virtual ~UnitTest();
  1135. // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
  1136. // Google Test trace stack.
  1137. void PushGTestTrace(const internal::TraceInfo& trace)
  1138. GTEST_LOCK_EXCLUDED_(mutex_);
  1139. // Pops a trace from the per-thread Google Test trace stack.
  1140. void PopGTestTrace()
  1141. GTEST_LOCK_EXCLUDED_(mutex_);
  1142. // Protects mutable state in *impl_. This is mutable as some const
  1143. // methods need to lock it too.
  1144. mutable internal::Mutex mutex_;
  1145. // Opaque implementation object. This field is never changed once
  1146. // the object is constructed. We don't mark it as const here, as
  1147. // doing so will cause a warning in the constructor of UnitTest.
  1148. // Mutable state in *impl_ is protected by mutex_.
  1149. internal::UnitTestImpl* impl_;
  1150. // We disallow copying UnitTest.
  1151. GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTest);
  1152. };
  1153. // A convenient wrapper for adding an environment for the test
  1154. // program.
  1155. //
  1156. // You should call this before RUN_ALL_TESTS() is called, probably in
  1157. // main(). If you use gtest_main, you need to call this before main()
  1158. // starts for it to take effect. For example, you can define a global
  1159. // variable like this:
  1160. //
  1161. // testing::Environment* const foo_env =
  1162. // testing::AddGlobalTestEnvironment(new FooEnvironment);
  1163. //
  1164. // However, we strongly recommend you to write your own main() and
  1165. // call AddGlobalTestEnvironment() there, as relying on initialization
  1166. // of global variables makes the code harder to read and may cause
  1167. // problems when you register multiple environments from different
  1168. // translation units and the environments have dependencies among them
  1169. // (remember that the compiler doesn't guarantee the order in which
  1170. // global variables from different translation units are initialized).
  1171. inline Environment* AddGlobalTestEnvironment(Environment* env) {
  1172. return UnitTest::GetInstance()->AddEnvironment(env);
  1173. }
  1174. // Initializes Google Test. This must be called before calling
  1175. // RUN_ALL_TESTS(). In particular, it parses a command line for the
  1176. // flags that Google Test recognizes. Whenever a Google Test flag is
  1177. // seen, it is removed from argv, and *argc is decremented.
  1178. //
  1179. // No value is returned. Instead, the Google Test flag variables are
  1180. // updated.
  1181. //
  1182. // Calling the function for the second time has no user-visible effect.
  1183. GTEST_API_ void InitGoogleTest(int* argc, char** argv);
  1184. // This overloaded version can be used in Windows programs compiled in
  1185. // UNICODE mode.
  1186. GTEST_API_ void InitGoogleTest(int* argc, wchar_t** argv);
  1187. namespace internal {
  1188. // Separate the error generating code from the code path to reduce the stack
  1189. // frame size of CmpHelperEQ. This helps reduce the overhead of some sanitizers
  1190. // when calling EXPECT_* in a tight loop.
  1191. template <typename T1, typename T2>
  1192. AssertionResult CmpHelperEQFailure(const char* lhs_expression,
  1193. const char* rhs_expression,
  1194. const T1& lhs, const T2& rhs) {
  1195. return EqFailure(lhs_expression,
  1196. rhs_expression,
  1197. FormatForComparisonFailureMessage(lhs, rhs),
  1198. FormatForComparisonFailureMessage(rhs, lhs),
  1199. false);
  1200. }
  1201. // The helper function for {ASSERT|EXPECT}_EQ.
  1202. template <typename T1, typename T2>
  1203. AssertionResult CmpHelperEQ(const char* lhs_expression,
  1204. const char* rhs_expression,
  1205. const T1& lhs,
  1206. const T2& rhs) {
  1207. if (lhs == rhs) {
  1208. return AssertionSuccess();
  1209. }
  1210. return CmpHelperEQFailure(lhs_expression, rhs_expression, lhs, rhs);
  1211. }
  1212. // With this overloaded version, we allow anonymous enums to be used
  1213. // in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous enums
  1214. // can be implicitly cast to BiggestInt.
  1215. GTEST_API_ AssertionResult CmpHelperEQ(const char* lhs_expression,
  1216. const char* rhs_expression,
  1217. BiggestInt lhs,
  1218. BiggestInt rhs);
  1219. // The helper class for {ASSERT|EXPECT}_EQ. The template argument
  1220. // lhs_is_null_literal is true iff the first argument to ASSERT_EQ()
  1221. // is a null pointer literal. The following default implementation is
  1222. // for lhs_is_null_literal being false.
  1223. template <bool lhs_is_null_literal>
  1224. class EqHelper {
  1225. public:
  1226. // This templatized version is for the general case.
  1227. template <typename T1, typename T2>
  1228. static AssertionResult Compare(const char* lhs_expression,
  1229. const char* rhs_expression,
  1230. const T1& lhs,
  1231. const T2& rhs) {
  1232. return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs);
  1233. }
  1234. // With this overloaded version, we allow anonymous enums to be used
  1235. // in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous
  1236. // enums can be implicitly cast to BiggestInt.
  1237. //
  1238. // Even though its body looks the same as the above version, we
  1239. // cannot merge the two, as it will make anonymous enums unhappy.
  1240. static AssertionResult Compare(const char* lhs_expression,
  1241. const char* rhs_expression,
  1242. BiggestInt lhs,
  1243. BiggestInt rhs) {
  1244. return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs);
  1245. }
  1246. };
  1247. // This specialization is used when the first argument to ASSERT_EQ()
  1248. // is a null pointer literal, like NULL, false, or 0.
  1249. template <>
  1250. class EqHelper<true> {
  1251. public:
  1252. // We define two overloaded versions of Compare(). The first
  1253. // version will be picked when the second argument to ASSERT_EQ() is
  1254. // NOT a pointer, e.g. ASSERT_EQ(0, AnIntFunction()) or
  1255. // EXPECT_EQ(false, a_bool).
  1256. template <typename T1, typename T2>
  1257. static AssertionResult Compare(
  1258. const char* lhs_expression,
  1259. const char* rhs_expression,
  1260. const T1& lhs,
  1261. const T2& rhs,
  1262. // The following line prevents this overload from being considered if T2
  1263. // is not a pointer type. We need this because ASSERT_EQ(NULL, my_ptr)
  1264. // expands to Compare("", "", NULL, my_ptr), which requires a conversion
  1265. // to match the Secret* in the other overload, which would otherwise make
  1266. // this template match better.
  1267. typename EnableIf<!is_pointer<T2>::value>::type* = 0) {
  1268. return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs);
  1269. }
  1270. // This version will be picked when the second argument to ASSERT_EQ() is a
  1271. // pointer, e.g. ASSERT_EQ(NULL, a_pointer).
  1272. template <typename T>
  1273. static AssertionResult Compare(
  1274. const char* lhs_expression,
  1275. const char* rhs_expression,
  1276. // We used to have a second template parameter instead of Secret*. That
  1277. // template parameter would deduce to 'long', making this a better match
  1278. // than the first overload even without the first overload's EnableIf.
  1279. // Unfortunately, gcc with -Wconversion-null warns when "passing NULL to
  1280. // non-pointer argument" (even a deduced integral argument), so the old
  1281. // implementation caused warnings in user code.
  1282. Secret* /* lhs (NULL) */,
  1283. T* rhs) {
  1284. // We already know that 'lhs' is a null pointer.
  1285. return CmpHelperEQ(lhs_expression, rhs_expression,
  1286. static_cast<T*>(NULL), rhs);
  1287. }
  1288. };
  1289. // Separate the error generating code from the code path to reduce the stack
  1290. // frame size of CmpHelperOP. This helps reduce the overhead of some sanitizers
  1291. // when calling EXPECT_OP in a tight loop.
  1292. template <typename T1, typename T2>
  1293. AssertionResult CmpHelperOpFailure(const char* expr1, const char* expr2,
  1294. const T1& val1, const T2& val2,
  1295. const char* op) {
  1296. return AssertionFailure()
  1297. << "Expected: (" << expr1 << ") " << op << " (" << expr2
  1298. << "), actual: " << FormatForComparisonFailureMessage(val1, val2)
  1299. << " vs " << FormatForComparisonFailureMessage(val2, val1);
  1300. }
  1301. // A macro for implementing the helper functions needed to implement
  1302. // ASSERT_?? and EXPECT_??. It is here just to avoid copy-and-paste
  1303. // of similar code.
  1304. //
  1305. // For each templatized helper function, we also define an overloaded
  1306. // version for BiggestInt in order to reduce code bloat and allow
  1307. // anonymous enums to be used with {ASSERT|EXPECT}_?? when compiled
  1308. // with gcc 4.
  1309. //
  1310. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  1311. #define GTEST_IMPL_CMP_HELPER_(op_name, op)\
  1312. template <typename T1, typename T2>\
  1313. AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
  1314. const T1& val1, const T2& val2) {\
  1315. if (val1 op val2) {\
  1316. return AssertionSuccess();\
  1317. } else {\
  1318. return CmpHelperOpFailure(expr1, expr2, val1, val2, #op);\
  1319. }\
  1320. }\
  1321. GTEST_API_ AssertionResult CmpHelper##op_name(\
  1322. const char* expr1, const char* expr2, BiggestInt val1, BiggestInt val2)
  1323. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  1324. // Implements the helper function for {ASSERT|EXPECT}_NE
  1325. GTEST_IMPL_CMP_HELPER_(NE, !=);
  1326. // Implements the helper function for {ASSERT|EXPECT}_LE
  1327. GTEST_IMPL_CMP_HELPER_(LE, <=);
  1328. // Implements the helper function for {ASSERT|EXPECT}_LT
  1329. GTEST_IMPL_CMP_HELPER_(LT, <);
  1330. // Implements the helper function for {ASSERT|EXPECT}_GE
  1331. GTEST_IMPL_CMP_HELPER_(GE, >=);
  1332. // Implements the helper function for {ASSERT|EXPECT}_GT
  1333. GTEST_IMPL_CMP_HELPER_(GT, >);
  1334. #undef GTEST_IMPL_CMP_HELPER_
  1335. // The helper function for {ASSERT|EXPECT}_STREQ.
  1336. //
  1337. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  1338. GTEST_API_ AssertionResult CmpHelperSTREQ(const char* s1_expression,
  1339. const char* s2_expression,
  1340. const char* s1,
  1341. const char* s2);
  1342. // The helper function for {ASSERT|EXPECT}_STRCASEEQ.
  1343. //
  1344. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  1345. GTEST_API_ AssertionResult CmpHelperSTRCASEEQ(const char* s1_expression,
  1346. const char* s2_expression,
  1347. const char* s1,
  1348. const char* s2);
  1349. // The helper function for {ASSERT|EXPECT}_STRNE.
  1350. //
  1351. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  1352. GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression,
  1353. const char* s2_expression,
  1354. const char* s1,
  1355. const char* s2);
  1356. // The helper function for {ASSERT|EXPECT}_STRCASENE.
  1357. //
  1358. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  1359. GTEST_API_ AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
  1360. const char* s2_expression,
  1361. const char* s1,
  1362. const char* s2);
  1363. // Helper function for *_STREQ on wide strings.
  1364. //
  1365. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  1366. GTEST_API_ AssertionResult CmpHelperSTREQ(const char* s1_expression,
  1367. const char* s2_expression,
  1368. const wchar_t* s1,
  1369. const wchar_t* s2);
  1370. // Helper function for *_STRNE on wide strings.
  1371. //
  1372. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  1373. GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression,
  1374. const char* s2_expression,
  1375. const wchar_t* s1,
  1376. const wchar_t* s2);
  1377. } // namespace internal
  1378. // IsSubstring() and IsNotSubstring() are intended to be used as the
  1379. // first argument to {EXPECT,ASSERT}_PRED_FORMAT2(), not by
  1380. // themselves. They check whether needle is a substring of haystack
  1381. // (NULL is considered a substring of itself only), and return an
  1382. // appropriate error message when they fail.
  1383. //
  1384. // The {needle,haystack}_expr arguments are the stringified
  1385. // expressions that generated the two real arguments.
  1386. GTEST_API_ AssertionResult IsSubstring(
  1387. const char* needle_expr, const char* haystack_expr,
  1388. const char* needle, const char* haystack);
  1389. GTEST_API_ AssertionResult IsSubstring(
  1390. const char* needle_expr, const char* haystack_expr,
  1391. const wchar_t* needle, const wchar_t* haystack);
  1392. GTEST_API_ AssertionResult IsNotSubstring(
  1393. const char* needle_expr, const char* haystack_expr,
  1394. const char* needle, const char* haystack);
  1395. GTEST_API_ AssertionResult IsNotSubstring(
  1396. const char* needle_expr, const char* haystack_expr,
  1397. const wchar_t* needle, const wchar_t* haystack);
  1398. GTEST_API_ AssertionResult IsSubstring(
  1399. const char* needle_expr, const char* haystack_expr,
  1400. const ::std::string& needle, const ::std::string& haystack);
  1401. GTEST_API_ AssertionResult IsNotSubstring(
  1402. const char* needle_expr, const char* haystack_expr,
  1403. const ::std::string& needle, const ::std::string& haystack);
  1404. #if GTEST_HAS_STD_WSTRING
  1405. GTEST_API_ AssertionResult IsSubstring(
  1406. const char* needle_expr, const char* haystack_expr,
  1407. const ::std::wstring& needle, const ::std::wstring& haystack);
  1408. GTEST_API_ AssertionResult IsNotSubstring(
  1409. const char* needle_expr, const char* haystack_expr,
  1410. const ::std::wstring& needle, const ::std::wstring& haystack);
  1411. #endif // GTEST_HAS_STD_WSTRING
  1412. namespace internal {
  1413. // Helper template function for comparing floating-points.
  1414. //
  1415. // Template parameter:
  1416. //
  1417. // RawType: the raw floating-point type (either float or double)
  1418. //
  1419. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  1420. template <typename RawType>
  1421. AssertionResult CmpHelperFloatingPointEQ(const char* lhs_expression,
  1422. const char* rhs_expression,
  1423. RawType lhs_value,
  1424. RawType rhs_value) {
  1425. const FloatingPoint<RawType> lhs(lhs_value), rhs(rhs_value);
  1426. if (lhs.AlmostEquals(rhs)) {
  1427. return AssertionSuccess();
  1428. }
  1429. ::std::stringstream lhs_ss;
  1430. lhs_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
  1431. << lhs_value;
  1432. ::std::stringstream rhs_ss;
  1433. rhs_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
  1434. << rhs_value;
  1435. return EqFailure(lhs_expression,
  1436. rhs_expression,
  1437. StringStreamToString(&lhs_ss),
  1438. StringStreamToString(&rhs_ss),
  1439. false);
  1440. }
  1441. // Helper function for implementing ASSERT_NEAR.
  1442. //
  1443. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  1444. GTEST_API_ AssertionResult DoubleNearPredFormat(const char* expr1,
  1445. const char* expr2,
  1446. const char* abs_error_expr,
  1447. double val1,
  1448. double val2,
  1449. double abs_error);
  1450. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
  1451. // A class that enables one to stream messages to assertion macros
  1452. class GTEST_API_ AssertHelper {
  1453. public:
  1454. // Constructor.
  1455. AssertHelper(TestPartResult::Type type,
  1456. const char* file,
  1457. int line,
  1458. const char* message);
  1459. ~AssertHelper();
  1460. // Message assignment is a semantic trick to enable assertion
  1461. // streaming; see the GTEST_MESSAGE_ macro below.
  1462. void operator=(const Message& message) const;
  1463. private:
  1464. // We put our data in a struct so that the size of the AssertHelper class can
  1465. // be as small as possible. This is important because gcc is incapable of
  1466. // re-using stack space even for temporary variables, so every EXPECT_EQ
  1467. // reserves stack space for another AssertHelper.
  1468. struct AssertHelperData {
  1469. AssertHelperData(TestPartResult::Type t,
  1470. const char* srcfile,
  1471. int line_num,
  1472. const char* msg)
  1473. : type(t), file(srcfile), line(line_num), message(msg) { }
  1474. TestPartResult::Type const type;
  1475. const char* const file;
  1476. int const line;
  1477. std::string const message;
  1478. private:
  1479. GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelperData);
  1480. };
  1481. AssertHelperData* const data_;
  1482. GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelper);
  1483. };
  1484. } // namespace internal
  1485. // The pure interface class that all value-parameterized tests inherit from.
  1486. // A value-parameterized class must inherit from both ::testing::Test and
  1487. // ::testing::WithParamInterface. In most cases that just means inheriting
  1488. // from ::testing::TestWithParam, but more complicated test hierarchies
  1489. // may need to inherit from Test and WithParamInterface at different levels.
  1490. //
  1491. // This interface has support for accessing the test parameter value via
  1492. // the GetParam() method.
  1493. //
  1494. // Use it with one of the parameter generator defining functions, like Range(),
  1495. // Values(), ValuesIn(), Bool(), and Combine().
  1496. //
  1497. // class FooTest : public ::testing::TestWithParam<int> {
  1498. // protected:
  1499. // FooTest() {
  1500. // // Can use GetParam() here.
  1501. // }
  1502. // virtual ~FooTest() {
  1503. // // Can use GetParam() here.
  1504. // }
  1505. // virtual void SetUp() {
  1506. // // Can use GetParam() here.
  1507. // }
  1508. // virtual void TearDown {
  1509. // // Can use GetParam() here.
  1510. // }
  1511. // };
  1512. // TEST_P(FooTest, DoesBar) {
  1513. // // Can use GetParam() method here.
  1514. // Foo foo;
  1515. // ASSERT_TRUE(foo.DoesBar(GetParam()));
  1516. // }
  1517. // INSTANTIATE_TEST_CASE_P(OneToTenRange, FooTest, ::testing::Range(1, 10));
  1518. template <typename T>
  1519. class WithParamInterface {
  1520. public:
  1521. typedef T ParamType;
  1522. virtual ~WithParamInterface() {}
  1523. // The current parameter value. Is also available in the test fixture's
  1524. // constructor. This member function is non-static, even though it only
  1525. // references static data, to reduce the opportunity for incorrect uses
  1526. // like writing 'WithParamInterface<bool>::GetParam()' for a test that
  1527. // uses a fixture whose parameter type is int.
  1528. const ParamType& GetParam() const {
  1529. GTEST_CHECK_(parameter_ != NULL)
  1530. << "GetParam() can only be called inside a value-parameterized test "
  1531. << "-- did you intend to write TEST_P instead of TEST_F?";
  1532. return *parameter_;
  1533. }
  1534. private:
  1535. // Sets parameter value. The caller is responsible for making sure the value
  1536. // remains alive and unchanged throughout the current test.
  1537. static void SetParam(const ParamType* parameter) {
  1538. parameter_ = parameter;
  1539. }
  1540. // Static value used for accessing parameter during a test lifetime.
  1541. static const ParamType* parameter_;
  1542. // TestClass must be a subclass of WithParamInterface<T> and Test.
  1543. template <class TestClass> friend class internal::ParameterizedTestFactory;
  1544. };
  1545. template <typename T>
  1546. const T* WithParamInterface<T>::parameter_ = NULL;
  1547. // Most value-parameterized classes can ignore the existence of
  1548. // WithParamInterface, and can just inherit from ::testing::TestWithParam.
  1549. template <typename T>
  1550. class TestWithParam : public Test, public WithParamInterface<T> {
  1551. };
  1552. // Macros for indicating success/failure in test code.
  1553. // ADD_FAILURE unconditionally adds a failure to the current test.
  1554. // SUCCEED generates a success - it doesn't automatically make the
  1555. // current test successful, as a test is only successful when it has
  1556. // no failure.
  1557. //
  1558. // EXPECT_* verifies that a certain condition is satisfied. If not,
  1559. // it behaves like ADD_FAILURE. In particular:
  1560. //
  1561. // EXPECT_TRUE verifies that a Boolean condition is true.
  1562. // EXPECT_FALSE verifies that a Boolean condition is false.
  1563. //
  1564. // FAIL and ASSERT_* are similar to ADD_FAILURE and EXPECT_*, except
  1565. // that they will also abort the current function on failure. People
  1566. // usually want the fail-fast behavior of FAIL and ASSERT_*, but those
  1567. // writing data-driven tests often find themselves using ADD_FAILURE
  1568. // and EXPECT_* more.
  1569. // Generates a nonfatal failure with a generic message.
  1570. #define ADD_FAILURE() GTEST_NONFATAL_FAILURE_("Failed")
  1571. // Generates a nonfatal failure at the given source file location with
  1572. // a generic message.
  1573. #define ADD_FAILURE_AT(file, line) \
  1574. GTEST_MESSAGE_AT_(file, line, "Failed", \
  1575. ::testing::TestPartResult::kNonFatalFailure)
  1576. // Generates a fatal failure with a generic message.
  1577. #define GTEST_FAIL() GTEST_FATAL_FAILURE_("Failed")
  1578. // Define this macro to 1 to omit the definition of FAIL(), which is a
  1579. // generic name and clashes with some other libraries.
  1580. #if !GTEST_DONT_DEFINE_FAIL
  1581. # define FAIL() GTEST_FAIL()
  1582. #endif
  1583. // Generates a success with a generic message.
  1584. #define GTEST_SUCCEED() GTEST_SUCCESS_("Succeeded")
  1585. // Define this macro to 1 to omit the definition of SUCCEED(), which
  1586. // is a generic name and clashes with some other libraries.
  1587. #if !GTEST_DONT_DEFINE_SUCCEED
  1588. # define SUCCEED() GTEST_SUCCEED()
  1589. #endif
  1590. // Macros for testing exceptions.
  1591. //
  1592. // * {ASSERT|EXPECT}_THROW(statement, expected_exception):
  1593. // Tests that the statement throws the expected exception.
  1594. // * {ASSERT|EXPECT}_NO_THROW(statement):
  1595. // Tests that the statement doesn't throw any exception.
  1596. // * {ASSERT|EXPECT}_ANY_THROW(statement):
  1597. // Tests that the statement throws an exception.
  1598. #define EXPECT_THROW(statement, expected_exception) \
  1599. GTEST_TEST_THROW_(statement, expected_exception, GTEST_NONFATAL_FAILURE_)
  1600. #define EXPECT_NO_THROW(statement) \
  1601. GTEST_TEST_NO_THROW_(statement, GTEST_NONFATAL_FAILURE_)
  1602. #define EXPECT_ANY_THROW(statement) \
  1603. GTEST_TEST_ANY_THROW_(statement, GTEST_NONFATAL_FAILURE_)
  1604. #define ASSERT_THROW(statement, expected_exception) \
  1605. GTEST_TEST_THROW_(statement, expected_exception, GTEST_FATAL_FAILURE_)
  1606. #define ASSERT_NO_THROW(statement) \
  1607. GTEST_TEST_NO_THROW_(statement, GTEST_FATAL_FAILURE_)
  1608. #define ASSERT_ANY_THROW(statement) \
  1609. GTEST_TEST_ANY_THROW_(statement, GTEST_FATAL_FAILURE_)
  1610. // Boolean assertions. Condition can be either a Boolean expression or an
  1611. // AssertionResult. For more information on how to use AssertionResult with
  1612. // these macros see comments on that class.
  1613. #define EXPECT_TRUE(condition) \
  1614. GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \
  1615. GTEST_NONFATAL_FAILURE_)
  1616. #define EXPECT_FALSE(condition) \
  1617. GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \
  1618. GTEST_NONFATAL_FAILURE_)
  1619. #define ASSERT_TRUE(condition) \
  1620. GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \
  1621. GTEST_FATAL_FAILURE_)
  1622. #define ASSERT_FALSE(condition) \
  1623. GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \
  1624. GTEST_FATAL_FAILURE_)
  1625. // Macros for testing equalities and inequalities.
  1626. //
  1627. // * {ASSERT|EXPECT}_EQ(v1, v2): Tests that v1 == v2
  1628. // * {ASSERT|EXPECT}_NE(v1, v2): Tests that v1 != v2
  1629. // * {ASSERT|EXPECT}_LT(v1, v2): Tests that v1 < v2
  1630. // * {ASSERT|EXPECT}_LE(v1, v2): Tests that v1 <= v2
  1631. // * {ASSERT|EXPECT}_GT(v1, v2): Tests that v1 > v2
  1632. // * {ASSERT|EXPECT}_GE(v1, v2): Tests that v1 >= v2
  1633. //
  1634. // When they are not, Google Test prints both the tested expressions and
  1635. // their actual values. The values must be compatible built-in types,
  1636. // or you will get a compiler error. By "compatible" we mean that the
  1637. // values can be compared by the respective operator.
  1638. //
  1639. // Note:
  1640. //
  1641. // 1. It is possible to make a user-defined type work with
  1642. // {ASSERT|EXPECT}_??(), but that requires overloading the
  1643. // comparison operators and is thus discouraged by the Google C++
  1644. // Usage Guide. Therefore, you are advised to use the
  1645. // {ASSERT|EXPECT}_TRUE() macro to assert that two objects are
  1646. // equal.
  1647. //
  1648. // 2. The {ASSERT|EXPECT}_??() macros do pointer comparisons on
  1649. // pointers (in particular, C strings). Therefore, if you use it
  1650. // with two C strings, you are testing how their locations in memory
  1651. // are related, not how their content is related. To compare two C
  1652. // strings by content, use {ASSERT|EXPECT}_STR*().
  1653. //
  1654. // 3. {ASSERT|EXPECT}_EQ(v1, v2) is preferred to
  1655. // {ASSERT|EXPECT}_TRUE(v1 == v2), as the former tells you
  1656. // what the actual value is when it fails, and similarly for the
  1657. // other comparisons.
  1658. //
  1659. // 4. Do not depend on the order in which {ASSERT|EXPECT}_??()
  1660. // evaluate their arguments, which is undefined.
  1661. //
  1662. // 5. These macros evaluate their arguments exactly once.
  1663. //
  1664. // Examples:
  1665. //
  1666. // EXPECT_NE(Foo(), 5);
  1667. // EXPECT_EQ(a_pointer, NULL);
  1668. // ASSERT_LT(i, array_size);
  1669. // ASSERT_GT(records.size(), 0) << "There is no record left.";
  1670. #define EXPECT_EQ(val1, val2) \
  1671. EXPECT_PRED_FORMAT2(::testing::internal:: \
  1672. EqHelper<GTEST_IS_NULL_LITERAL_(val1)>::Compare, \
  1673. val1, val2)
  1674. #define EXPECT_NE(val1, val2) \
  1675. EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2)
  1676. #define EXPECT_LE(val1, val2) \
  1677. EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2)
  1678. #define EXPECT_LT(val1, val2) \
  1679. EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2)
  1680. #define EXPECT_GE(val1, val2) \
  1681. EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2)
  1682. #define EXPECT_GT(val1, val2) \
  1683. EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2)
  1684. #define GTEST_ASSERT_EQ(val1, val2) \
  1685. ASSERT_PRED_FORMAT2(::testing::internal:: \
  1686. EqHelper<GTEST_IS_NULL_LITERAL_(val1)>::Compare, \
  1687. val1, val2)
  1688. #define GTEST_ASSERT_NE(val1, val2) \
  1689. ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2)
  1690. #define GTEST_ASSERT_LE(val1, val2) \
  1691. ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2)
  1692. #define GTEST_ASSERT_LT(val1, val2) \
  1693. ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2)
  1694. #define GTEST_ASSERT_GE(val1, val2) \
  1695. ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2)
  1696. #define GTEST_ASSERT_GT(val1, val2) \
  1697. ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2)
  1698. // Define macro GTEST_DONT_DEFINE_ASSERT_XY to 1 to omit the definition of
  1699. // ASSERT_XY(), which clashes with some users' own code.
  1700. #if !GTEST_DONT_DEFINE_ASSERT_EQ
  1701. # define ASSERT_EQ(val1, val2) GTEST_ASSERT_EQ(val1, val2)
  1702. #endif
  1703. #if !GTEST_DONT_DEFINE_ASSERT_NE
  1704. # define ASSERT_NE(val1, val2) GTEST_ASSERT_NE(val1, val2)
  1705. #endif
  1706. #if !GTEST_DONT_DEFINE_ASSERT_LE
  1707. # define ASSERT_LE(val1, val2) GTEST_ASSERT_LE(val1, val2)
  1708. #endif
  1709. #if !GTEST_DONT_DEFINE_ASSERT_LT
  1710. # define ASSERT_LT(val1, val2) GTEST_ASSERT_LT(val1, val2)
  1711. #endif
  1712. #if !GTEST_DONT_DEFINE_ASSERT_GE
  1713. # define ASSERT_GE(val1, val2) GTEST_ASSERT_GE(val1, val2)
  1714. #endif
  1715. #if !GTEST_DONT_DEFINE_ASSERT_GT
  1716. # define ASSERT_GT(val1, val2) GTEST_ASSERT_GT(val1, val2)
  1717. #endif
  1718. // C-string Comparisons. All tests treat NULL and any non-NULL string
  1719. // as different. Two NULLs are equal.
  1720. //
  1721. // * {ASSERT|EXPECT}_STREQ(s1, s2): Tests that s1 == s2
  1722. // * {ASSERT|EXPECT}_STRNE(s1, s2): Tests that s1 != s2
  1723. // * {ASSERT|EXPECT}_STRCASEEQ(s1, s2): Tests that s1 == s2, ignoring case
  1724. // * {ASSERT|EXPECT}_STRCASENE(s1, s2): Tests that s1 != s2, ignoring case
  1725. //
  1726. // For wide or narrow string objects, you can use the
  1727. // {ASSERT|EXPECT}_??() macros.
  1728. //
  1729. // Don't depend on the order in which the arguments are evaluated,
  1730. // which is undefined.
  1731. //
  1732. // These macros evaluate their arguments exactly once.
  1733. #define EXPECT_STREQ(s1, s2) \
  1734. EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, s1, s2)
  1735. #define EXPECT_STRNE(s1, s2) \
  1736. EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2)
  1737. #define EXPECT_STRCASEEQ(s1, s2) \
  1738. EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, s1, s2)
  1739. #define EXPECT_STRCASENE(s1, s2)\
  1740. EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2)
  1741. #define ASSERT_STREQ(s1, s2) \
  1742. ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, s1, s2)
  1743. #define ASSERT_STRNE(s1, s2) \
  1744. ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2)
  1745. #define ASSERT_STRCASEEQ(s1, s2) \
  1746. ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, s1, s2)
  1747. #define ASSERT_STRCASENE(s1, s2)\
  1748. ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2)
  1749. // Macros for comparing floating-point numbers.
  1750. //
  1751. // * {ASSERT|EXPECT}_FLOAT_EQ(val1, val2):
  1752. // Tests that two float values are almost equal.
  1753. // * {ASSERT|EXPECT}_DOUBLE_EQ(val1, val2):
  1754. // Tests that two double values are almost equal.
  1755. // * {ASSERT|EXPECT}_NEAR(v1, v2, abs_error):
  1756. // Tests that v1 and v2 are within the given distance to each other.
  1757. //
  1758. // Google Test uses ULP-based comparison to automatically pick a default
  1759. // error bound that is appropriate for the operands. See the
  1760. // FloatingPoint template class in gtest-internal.h if you are
  1761. // interested in the implementation details.
  1762. #define EXPECT_FLOAT_EQ(val1, val2)\
  1763. EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, \
  1764. val1, val2)
  1765. #define EXPECT_DOUBLE_EQ(val1, val2)\
  1766. EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<double>, \
  1767. val1, val2)
  1768. #define ASSERT_FLOAT_EQ(val1, val2)\
  1769. ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, \
  1770. val1, val2)
  1771. #define ASSERT_DOUBLE_EQ(val1, val2)\
  1772. ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<double>, \
  1773. val1, val2)
  1774. #define EXPECT_NEAR(val1, val2, abs_error)\
  1775. EXPECT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \
  1776. val1, val2, abs_error)
  1777. #define ASSERT_NEAR(val1, val2, abs_error)\
  1778. ASSERT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \
  1779. val1, val2, abs_error)
  1780. // These predicate format functions work on floating-point values, and
  1781. // can be used in {ASSERT|EXPECT}_PRED_FORMAT2*(), e.g.
  1782. //
  1783. // EXPECT_PRED_FORMAT2(testing::DoubleLE, Foo(), 5.0);
  1784. // Asserts that val1 is less than, or almost equal to, val2. Fails
  1785. // otherwise. In particular, it fails if either val1 or val2 is NaN.
  1786. GTEST_API_ AssertionResult FloatLE(const char* expr1, const char* expr2,
  1787. float val1, float val2);
  1788. GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2,
  1789. double val1, double val2);
  1790. #if GTEST_OS_WINDOWS
  1791. // Macros that test for HRESULT failure and success, these are only useful
  1792. // on Windows, and rely on Windows SDK macros and APIs to compile.
  1793. //
  1794. // * {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED}(expr)
  1795. //
  1796. // When expr unexpectedly fails or succeeds, Google Test prints the
  1797. // expected result and the actual result with both a human-readable
  1798. // string representation of the error, if available, as well as the
  1799. // hex result code.
  1800. # define EXPECT_HRESULT_SUCCEEDED(expr) \
  1801. EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr))
  1802. # define ASSERT_HRESULT_SUCCEEDED(expr) \
  1803. ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr))
  1804. # define EXPECT_HRESULT_FAILED(expr) \
  1805. EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr))
  1806. # define ASSERT_HRESULT_FAILED(expr) \
  1807. ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr))
  1808. #endif // GTEST_OS_WINDOWS
  1809. // Macros that execute statement and check that it doesn't generate new fatal
  1810. // failures in the current thread.
  1811. //
  1812. // * {ASSERT|EXPECT}_NO_FATAL_FAILURE(statement);
  1813. //
  1814. // Examples:
  1815. //
  1816. // EXPECT_NO_FATAL_FAILURE(Process());
  1817. // ASSERT_NO_FATAL_FAILURE(Process()) << "Process() failed";
  1818. //
  1819. #define ASSERT_NO_FATAL_FAILURE(statement) \
  1820. GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_FATAL_FAILURE_)
  1821. #define EXPECT_NO_FATAL_FAILURE(statement) \
  1822. GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_NONFATAL_FAILURE_)
  1823. // Causes a trace (including the given source file path and line number,
  1824. // and the given message) to be included in every test failure message generated
  1825. // by code in the scope of the lifetime of an instance of this class. The effect
  1826. // is undone with the destruction of the instance.
  1827. //
  1828. // The message argument can be anything streamable to std::ostream.
  1829. //
  1830. // Example:
  1831. // testing::ScopedTrace trace("file.cc", 123, "message");
  1832. //
  1833. class GTEST_API_ ScopedTrace {
  1834. public:
  1835. // The c'tor pushes the given source file location and message onto
  1836. // a trace stack maintained by Google Test.
  1837. // Template version. Uses Message() to convert the values into strings.
  1838. // Slow, but flexible.
  1839. template <typename T>
  1840. ScopedTrace(const char* file, int line, const T& message) {
  1841. PushTrace(file, line, (Message() << message).GetString());
  1842. }
  1843. // Optimize for some known types.
  1844. ScopedTrace(const char* file, int line, const char* message) {
  1845. PushTrace(file, line, message ? message : "(null)");
  1846. }
  1847. #if GTEST_HAS_GLOBAL_STRING
  1848. ScopedTrace(const char* file, int line, const ::string& message) {
  1849. PushTrace(file, line, message);
  1850. }
  1851. #endif
  1852. ScopedTrace(const char* file, int line, const std::string& message) {
  1853. PushTrace(file, line, message);
  1854. }
  1855. // The d'tor pops the info pushed by the c'tor.
  1856. //
  1857. // Note that the d'tor is not virtual in order to be efficient.
  1858. // Don't inherit from ScopedTrace!
  1859. ~ScopedTrace();
  1860. private:
  1861. void PushTrace(const char* file, int line, std::string message);
  1862. GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedTrace);
  1863. } GTEST_ATTRIBUTE_UNUSED_; // A ScopedTrace object does its job in its
  1864. // c'tor and d'tor. Therefore it doesn't
  1865. // need to be used otherwise.
  1866. // Causes a trace (including the source file path, the current line
  1867. // number, and the given message) to be included in every test failure
  1868. // message generated by code in the current scope. The effect is
  1869. // undone when the control leaves the current scope.
  1870. //
  1871. // The message argument can be anything streamable to std::ostream.
  1872. //
  1873. // In the implementation, we include the current line number as part
  1874. // of the dummy variable name, thus allowing multiple SCOPED_TRACE()s
  1875. // to appear in the same block - as long as they are on different
  1876. // lines.
  1877. //
  1878. // Assuming that each thread maintains its own stack of traces.
  1879. // Therefore, a SCOPED_TRACE() would (correctly) only affect the
  1880. // assertions in its own thread.
  1881. #define SCOPED_TRACE(message) \
  1882. ::testing::ScopedTrace GTEST_CONCAT_TOKEN_(gtest_trace_, __LINE__)(\
  1883. __FILE__, __LINE__, (message))
  1884. // Compile-time assertion for type equality.
  1885. // StaticAssertTypeEq<type1, type2>() compiles iff type1 and type2 are
  1886. // the same type. The value it returns is not interesting.
  1887. //
  1888. // Instead of making StaticAssertTypeEq a class template, we make it a
  1889. // function template that invokes a helper class template. This
  1890. // prevents a user from misusing StaticAssertTypeEq<T1, T2> by
  1891. // defining objects of that type.
  1892. //
  1893. // CAVEAT:
  1894. //
  1895. // When used inside a method of a class template,
  1896. // StaticAssertTypeEq<T1, T2>() is effective ONLY IF the method is
  1897. // instantiated. For example, given:
  1898. //
  1899. // template <typename T> class Foo {
  1900. // public:
  1901. // void Bar() { testing::StaticAssertTypeEq<int, T>(); }
  1902. // };
  1903. //
  1904. // the code:
  1905. //
  1906. // void Test1() { Foo<bool> foo; }
  1907. //
  1908. // will NOT generate a compiler error, as Foo<bool>::Bar() is never
  1909. // actually instantiated. Instead, you need:
  1910. //
  1911. // void Test2() { Foo<bool> foo; foo.Bar(); }
  1912. //
  1913. // to cause a compiler error.
  1914. template <typename T1, typename T2>
  1915. bool StaticAssertTypeEq() {
  1916. (void)internal::StaticAssertTypeEqHelper<T1, T2>();
  1917. return true;
  1918. }
  1919. // Defines a test.
  1920. //
  1921. // The first parameter is the name of the test case, and the second
  1922. // parameter is the name of the test within the test case.
  1923. //
  1924. // The convention is to end the test case name with "Test". For
  1925. // example, a test case for the Foo class can be named FooTest.
  1926. //
  1927. // Test code should appear between braces after an invocation of
  1928. // this macro. Example:
  1929. //
  1930. // TEST(FooTest, InitializesCorrectly) {
  1931. // Foo foo;
  1932. // EXPECT_TRUE(foo.StatusIsOK());
  1933. // }
  1934. // Note that we call GetTestTypeId() instead of GetTypeId<
  1935. // ::testing::Test>() here to get the type ID of testing::Test. This
  1936. // is to work around a suspected linker bug when using Google Test as
  1937. // a framework on Mac OS X. The bug causes GetTypeId<
  1938. // ::testing::Test>() to return different values depending on whether
  1939. // the call is from the Google Test framework itself or from user test
  1940. // code. GetTestTypeId() is guaranteed to always return the same
  1941. // value, as it always calls GetTypeId<>() from the Google Test
  1942. // framework.
  1943. #define GTEST_TEST(test_case_name, test_name)\
  1944. GTEST_TEST_(test_case_name, test_name, \
  1945. ::testing::Test, ::testing::internal::GetTestTypeId())
  1946. // Define this macro to 1 to omit the definition of TEST(), which
  1947. // is a generic name and clashes with some other libraries.
  1948. #if !GTEST_DONT_DEFINE_TEST
  1949. # define TEST(test_case_name, test_name) GTEST_TEST(test_case_name, test_name)
  1950. #endif
  1951. // Defines a test that uses a test fixture.
  1952. //
  1953. // The first parameter is the name of the test fixture class, which
  1954. // also doubles as the test case name. The second parameter is the
  1955. // name of the test within the test case.
  1956. //
  1957. // A test fixture class must be declared earlier. The user should put
  1958. // the test code between braces after using this macro. Example:
  1959. //
  1960. // class FooTest : public testing::Test {
  1961. // protected:
  1962. // virtual void SetUp() { b_.AddElement(3); }
  1963. //
  1964. // Foo a_;
  1965. // Foo b_;
  1966. // };
  1967. //
  1968. // TEST_F(FooTest, InitializesCorrectly) {
  1969. // EXPECT_TRUE(a_.StatusIsOK());
  1970. // }
  1971. //
  1972. // TEST_F(FooTest, ReturnsElementCountCorrectly) {
  1973. // EXPECT_EQ(a_.size(), 0);
  1974. // EXPECT_EQ(b_.size(), 1);
  1975. // }
  1976. #define TEST_F(test_fixture, test_name)\
  1977. GTEST_TEST_(test_fixture, test_name, test_fixture, \
  1978. ::testing::internal::GetTypeId<test_fixture>())
  1979. // Returns a path to temporary directory.
  1980. // Tries to determine an appropriate directory for the platform.
  1981. GTEST_API_ std::string TempDir();
  1982. #ifdef _MSC_VER
  1983. # pragma warning(pop)
  1984. #endif
  1985. } // namespace testing
  1986. // Use this function in main() to run all tests. It returns 0 if all
  1987. // tests are successful, or 1 otherwise.
  1988. //
  1989. // RUN_ALL_TESTS() should be invoked after the command line has been
  1990. // parsed by InitGoogleTest().
  1991. //
  1992. // This function was formerly a macro; thus, it is in the global
  1993. // namespace and has an all-caps name.
  1994. int RUN_ALL_TESTS() GTEST_MUST_USE_RESULT_;
  1995. inline int RUN_ALL_TESTS() {
  1996. return ::testing::UnitTest::GetInstance()->Run();
  1997. }
  1998. GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
  1999. #endif // GTEST_INCLUDE_GTEST_GTEST_H_