gtest.h 90 KB

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