The source code and dockerfile for the GSW2024 AI Lab.
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.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

2495 lines
92 KiB

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