PageRenderTime 64ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/thirdparty/breakpad/third_party/protobuf/protobuf/gtest/include/gtest/gtest.h

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