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.

2155 lines
80 KiB

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