gtest.h 83 KB

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