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