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