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