You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2478 lines
92 KiB

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