gtest.h 89 KB

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