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