?login_element?

Subversion Repositories NedoOS

Rev

Blame | Last modification | View Log | Download

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