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