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