gtest.h 86 KB

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