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