PageRenderTime 58ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/Unittests/googletest/include/gtest/gtest.h

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