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