gtest.h 88 KB

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