gtest.h 88 KB

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