PageRenderTime 68ms CodeModel.GetById 16ms app.highlight 40ms RepoModel.GetById 1ms app.codeStats 1ms

/thirdparty/breakpad/third_party/protobuf/protobuf/gtest/include/gtest/gtest.h

http://github.com/tomahawk-player/tomahawk
C++ Header | 1733 lines | 651 code | 259 blank | 823 comment | 11 complexity | 792a3e23c62b16fed778b4980e4b4b85 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1// Copyright 2005, Google Inc.
   2// All rights reserved.
   3//
   4// Redistribution and use in source and binary forms, with or without
   5// modification, are permitted provided that the following conditions are
   6// met:
   7//
   8//     * Redistributions of source code must retain the above copyright
   9// notice, this list of conditions and the following disclaimer.
  10//     * Redistributions in binary form must reproduce the above
  11// copyright notice, this list of conditions and the following disclaimer
  12// in the documentation and/or other materials provided with the
  13// distribution.
  14//     * Neither the name of Google Inc. nor the names of its
  15// contributors may be used to endorse or promote products derived from
  16// this software without specific prior written permission.
  17//
  18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29//
  30// Author: wan@google.com (Zhanyong Wan)
  31//
  32// The Google C++ Testing Framework (Google Test)
  33//
  34// This header file defines the public API for Google Test.  It should be
  35// included by any test program that uses Google Test.
  36//
  37// IMPORTANT NOTE: Due to limitation of the C++ language, we have to
  38// leave some internal implementation details in this header file.
  39// They are clearly marked by comments like this:
  40//
  41//   // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  42//
  43// Such code is NOT meant to be used by a user directly, and is subject
  44// to CHANGE WITHOUT NOTICE.  Therefore DO NOT DEPEND ON IT in a user
  45// program!
  46//
  47// Acknowledgment: Google Test borrowed the idea of automatic test
  48// registration from Barthelemy Dagenais' (barthelemy@prologique.com)
  49// easyUnit framework.
  50
  51#ifndef GTEST_INCLUDE_GTEST_GTEST_H_
  52#define GTEST_INCLUDE_GTEST_GTEST_H_
  53
  54#include <limits>
  55#include <vector>
  56
  57#include <gtest/internal/gtest-internal.h>
  58#include <gtest/internal/gtest-string.h>
  59#include <gtest/gtest-death-test.h>
  60#include <gtest/gtest-message.h>
  61#include <gtest/gtest-param-test.h>
  62#include <gtest/gtest_prod.h>
  63#include <gtest/gtest-test-part.h>
  64#include <gtest/gtest-typed-test.h>
  65
  66// Depending on the platform, different string classes are available.
  67// On Linux, in addition to ::std::string, Google also makes use of
  68// class ::string, which has the same interface as ::std::string, but
  69// has a different implementation.
  70//
  71// The user can define GTEST_HAS_GLOBAL_STRING to 1 to indicate that
  72// ::string is available AND is a distinct type to ::std::string, or
  73// define it to 0 to indicate otherwise.
  74//
  75// If the user's ::std::string and ::string are the same class due to
  76// aliasing, he should define GTEST_HAS_GLOBAL_STRING to 0.
  77//
  78// If the user doesn't define GTEST_HAS_GLOBAL_STRING, it is defined
  79// heuristically.
  80
  81namespace testing {
  82
  83// Declares the flags.
  84
  85// This flag temporary enables the disabled tests.
  86GTEST_DECLARE_bool_(also_run_disabled_tests);
  87
  88// This flag brings the debugger on an assertion failure.
  89GTEST_DECLARE_bool_(break_on_failure);
  90
  91// This flag controls whether Google Test catches all test-thrown exceptions
  92// and logs them as failures.
  93GTEST_DECLARE_bool_(catch_exceptions);
  94
  95// This flag enables using colors in terminal output. Available values are
  96// "yes" to enable colors, "no" (disable colors), or "auto" (the default)
  97// to let Google Test decide.
  98GTEST_DECLARE_string_(color);
  99
 100// This flag sets up the filter to select by name using a glob pattern
 101// the tests to run. If the filter is not given all tests are executed.
 102GTEST_DECLARE_string_(filter);
 103
 104// This flag causes the Google Test to list tests. None of the tests listed
 105// are actually run if the flag is provided.
 106GTEST_DECLARE_bool_(list_tests);
 107
 108// This flag controls whether Google Test emits a detailed XML report to a file
 109// in addition to its normal textual output.
 110GTEST_DECLARE_string_(output);
 111
 112// This flags control whether Google Test prints the elapsed time for each
 113// test.
 114GTEST_DECLARE_bool_(print_time);
 115
 116// This flag specifies the random number seed.
 117GTEST_DECLARE_int32_(random_seed);
 118
 119// This flag sets how many times the tests are repeated. The default value
 120// is 1. If the value is -1 the tests are repeating forever.
 121GTEST_DECLARE_int32_(repeat);
 122
 123// This flag controls whether Google Test includes Google Test internal
 124// stack frames in failure stack traces.
 125GTEST_DECLARE_bool_(show_internal_stack_frames);
 126
 127// When this flag is specified, tests' order is randomized on every iteration.
 128GTEST_DECLARE_bool_(shuffle);
 129
 130// This flag specifies the maximum number of stack frames to be
 131// printed in a failure message.
 132GTEST_DECLARE_int32_(stack_trace_depth);
 133
 134// When this flag is specified, a failed assertion will throw an
 135// exception if exceptions are enabled, or exit the program with a
 136// non-zero code otherwise.
 137GTEST_DECLARE_bool_(throw_on_failure);
 138
 139// The upper limit for valid stack trace depths.
 140const int kMaxStackTraceDepth = 100;
 141
 142namespace internal {
 143
 144class AssertHelper;
 145class DefaultGlobalTestPartResultReporter;
 146class ExecDeathTest;
 147class NoExecDeathTest;
 148class FinalSuccessChecker;
 149class GTestFlagSaver;
 150class TestInfoImpl;
 151class TestResultAccessor;
 152class TestEventListenersAccessor;
 153class TestEventRepeater;
 154class WindowsDeathTest;
 155class UnitTestImpl* GetUnitTestImpl();
 156void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
 157                                    const String& message);
 158class PrettyUnitTestResultPrinter;
 159class XmlUnitTestResultPrinter;
 160
 161// Converts a streamable value to a String.  A NULL pointer is
 162// converted to "(null)".  When the input value is a ::string,
 163// ::std::string, ::wstring, or ::std::wstring object, each NUL
 164// character in it is replaced with "\\0".
 165// Declared in gtest-internal.h but defined here, so that it has access
 166// to the definition of the Message class, required by the ARM
 167// compiler.
 168template <typename T>
 169String StreamableToString(const T& streamable) {
 170  return (Message() << streamable).GetString();
 171}
 172
 173}  // namespace internal
 174
 175// A class for indicating whether an assertion was successful.  When
 176// the assertion wasn't successful, the AssertionResult object
 177// remembers a non-empty message that describes how it failed.
 178//
 179// To create an instance of this class, use one of the factory functions
 180// (AssertionSuccess() and AssertionFailure()).
 181//
 182// This class is useful for two purposes:
 183//   1. Defining predicate functions to be used with Boolean test assertions
 184//      EXPECT_TRUE/EXPECT_FALSE and their ASSERT_ counterparts
 185//   2. Defining predicate-format functions to be
 186//      used with predicate assertions (ASSERT_PRED_FORMAT*, etc).
 187//
 188// For example, if you define IsEven predicate:
 189//
 190//   testing::AssertionResult IsEven(int n) {
 191//     if ((n % 2) == 0)
 192//       return testing::AssertionSuccess();
 193//     else
 194//       return testing::AssertionFailure() << n << " is odd";
 195//   }
 196//
 197// Then the failed expectation EXPECT_TRUE(IsEven(Fib(5)))
 198// will print the message
 199//
 200//   Value of: IsEven(Fib(5))
 201//     Actual: false (5 is odd)
 202//   Expected: true
 203//
 204// instead of a more opaque
 205//
 206//   Value of: IsEven(Fib(5))
 207//     Actual: false
 208//   Expected: true
 209//
 210// in case IsEven is a simple Boolean predicate.
 211//
 212// If you expect your predicate to be reused and want to support informative
 213// messages in EXPECT_FALSE and ASSERT_FALSE (negative assertions show up
 214// about half as often as positive ones in our tests), supply messages for
 215// both success and failure cases:
 216//
 217//   testing::AssertionResult IsEven(int n) {
 218//     if ((n % 2) == 0)
 219//       return testing::AssertionSuccess() << n << " is even";
 220//     else
 221//       return testing::AssertionFailure() << n << " is odd";
 222//   }
 223//
 224// Then a statement EXPECT_FALSE(IsEven(Fib(6))) will print
 225//
 226//   Value of: IsEven(Fib(6))
 227//     Actual: true (8 is even)
 228//   Expected: false
 229//
 230// NB: Predicates that support negative Boolean assertions have reduced
 231// performance in positive ones so be careful not to use them in tests
 232// that have lots (tens of thousands) of positive Boolean assertions.
 233//
 234// To use this class with EXPECT_PRED_FORMAT assertions such as:
 235//
 236//   // Verifies that Foo() returns an even number.
 237//   EXPECT_PRED_FORMAT1(IsEven, Foo());
 238//
 239// you need to define:
 240//
 241//   testing::AssertionResult IsEven(const char* expr, int n) {
 242//     if ((n % 2) == 0)
 243//       return testing::AssertionSuccess();
 244//     else
 245//       return testing::AssertionFailure()
 246//         << "Expected: " << expr << " is even\n  Actual: it's " << n;
 247//   }
 248//
 249// If Foo() returns 5, you will see the following message:
 250//
 251//   Expected: Foo() is even
 252//     Actual: it's 5
 253//
 254class GTEST_API_ AssertionResult {
 255 public:
 256  // Copy constructor.
 257  // Used in EXPECT_TRUE/FALSE(assertion_result).
 258  AssertionResult(const AssertionResult& other);
 259  // Used in the EXPECT_TRUE/FALSE(bool_expression).
 260  explicit AssertionResult(bool success) : success_(success) {}
 261
 262  // Returns true iff the assertion succeeded.
 263  operator bool() const { return success_; }  // NOLINT
 264
 265  // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
 266  AssertionResult operator!() const;
 267
 268  // Returns the text streamed into this AssertionResult. Test assertions
 269  // use it when they fail (i.e., the predicate's outcome doesn't match the
 270  // assertion's expectation). When nothing has been streamed into the
 271  // object, returns an empty string.
 272  const char* message() const {
 273    return message_.get() != NULL && message_->c_str() != NULL ?
 274           message_->c_str() : "";
 275  }
 276  // TODO(vladl@google.com): Remove this after making sure no clients use it.
 277  // Deprecated; please use message() instead.
 278  const char* failure_message() const { return message(); }
 279
 280  // Streams a custom failure message into this object.
 281  template <typename T> AssertionResult& operator<<(const T& value);
 282
 283 private:
 284  // No implementation - we want AssertionResult to be
 285  // copy-constructible but not assignable.
 286  void operator=(const AssertionResult& other);
 287
 288  // Stores result of the assertion predicate.
 289  bool success_;
 290  // Stores the message describing the condition in case the expectation
 291  // construct is not satisfied with the predicate's outcome.
 292  // Referenced via a pointer to avoid taking too much stack frame space
 293  // with test assertions.
 294  internal::scoped_ptr<internal::String> message_;
 295};  // class AssertionResult
 296
 297// Streams a custom failure message into this object.
 298template <typename T>
 299AssertionResult& AssertionResult::operator<<(const T& value) {
 300  Message msg;
 301  if (message_.get() != NULL)
 302    msg << *message_;
 303  msg << value;
 304  message_.reset(new internal::String(msg.GetString()));
 305  return *this;
 306}
 307
 308// Makes a successful assertion result.
 309GTEST_API_ AssertionResult AssertionSuccess();
 310
 311// Makes a failed assertion result.
 312GTEST_API_ AssertionResult AssertionFailure();
 313
 314// Makes a failed assertion result with the given failure message.
 315// Deprecated; use AssertionFailure() << msg.
 316GTEST_API_ AssertionResult AssertionFailure(const Message& msg);
 317
 318// The abstract class that all tests inherit from.
 319//
 320// In Google Test, a unit test program contains one or many TestCases, and
 321// each TestCase contains one or many Tests.
 322//
 323// When you define a test using the TEST macro, you don't need to
 324// explicitly derive from Test - the TEST macro automatically does
 325// this for you.
 326//
 327// The only time you derive from Test is when defining a test fixture
 328// to be used a TEST_F.  For example:
 329//
 330//   class FooTest : public testing::Test {
 331//    protected:
 332//     virtual void SetUp() { ... }
 333//     virtual void TearDown() { ... }
 334//     ...
 335//   };
 336//
 337//   TEST_F(FooTest, Bar) { ... }
 338//   TEST_F(FooTest, Baz) { ... }
 339//
 340// Test is not copyable.
 341class GTEST_API_ Test {
 342 public:
 343  friend class internal::TestInfoImpl;
 344
 345  // Defines types for pointers to functions that set up and tear down
 346  // a test case.
 347  typedef internal::SetUpTestCaseFunc SetUpTestCaseFunc;
 348  typedef internal::TearDownTestCaseFunc TearDownTestCaseFunc;
 349
 350  // The d'tor is virtual as we intend to inherit from Test.
 351  virtual ~Test();
 352
 353  // Sets up the stuff shared by all tests in this test case.
 354  //
 355  // Google Test will call Foo::SetUpTestCase() before running the first
 356  // test in test case Foo.  Hence a sub-class can define its own
 357  // SetUpTestCase() method to shadow the one defined in the super
 358  // class.
 359  static void SetUpTestCase() {}
 360
 361  // Tears down the stuff shared by all tests in this test case.
 362  //
 363  // Google Test will call Foo::TearDownTestCase() after running the last
 364  // test in test case Foo.  Hence a sub-class can define its own
 365  // TearDownTestCase() method to shadow the one defined in the super
 366  // class.
 367  static void TearDownTestCase() {}
 368
 369  // Returns true iff the current test has a fatal failure.
 370  static bool HasFatalFailure();
 371
 372  // Returns true iff the current test has a non-fatal failure.
 373  static bool HasNonfatalFailure();
 374
 375  // Returns true iff the current test has a (either fatal or
 376  // non-fatal) failure.
 377  static bool HasFailure() { return HasFatalFailure() || HasNonfatalFailure(); }
 378
 379  // Logs a property for the current test.  Only the last value for a given
 380  // key is remembered.
 381  // These are public static so they can be called from utility functions
 382  // that are not members of the test fixture.
 383  // The arguments are const char* instead strings, as Google Test is used
 384  // on platforms where string doesn't compile.
 385  //
 386  // Note that a driving consideration for these RecordProperty methods
 387  // was to produce xml output suited to the Greenspan charting utility,
 388  // which at present will only chart values that fit in a 32-bit int. It
 389  // is the user's responsibility to restrict their values to 32-bit ints
 390  // if they intend them to be used with Greenspan.
 391  static void RecordProperty(const char* key, const char* value);
 392  static void RecordProperty(const char* key, int value);
 393
 394 protected:
 395  // Creates a Test object.
 396  Test();
 397
 398  // Sets up the test fixture.
 399  virtual void SetUp();
 400
 401  // Tears down the test fixture.
 402  virtual void TearDown();
 403
 404 private:
 405  // Returns true iff the current test has the same fixture class as
 406  // the first test in the current test case.
 407  static bool HasSameFixtureClass();
 408
 409  // Runs the test after the test fixture has been set up.
 410  //
 411  // A sub-class must implement this to define the test logic.
 412  //
 413  // DO NOT OVERRIDE THIS FUNCTION DIRECTLY IN A USER PROGRAM.
 414  // Instead, use the TEST or TEST_F macro.
 415  virtual void TestBody() = 0;
 416
 417  // Sets up, executes, and tears down the test.
 418  void Run();
 419
 420  // Uses a GTestFlagSaver to save and restore all Google Test flags.
 421  const internal::GTestFlagSaver* const gtest_flag_saver_;
 422
 423  // Often a user mis-spells SetUp() as Setup() and spends a long time
 424  // wondering why it is never called by Google Test.  The declaration of
 425  // the following method is solely for catching such an error at
 426  // compile time:
 427  //
 428  //   - The return type is deliberately chosen to be not void, so it
 429  //   will be a conflict if a user declares void Setup() in his test
 430  //   fixture.
 431  //
 432  //   - This method is private, so it will be another compiler error
 433  //   if a user calls it from his test fixture.
 434  //
 435  // DO NOT OVERRIDE THIS FUNCTION.
 436  //
 437  // If you see an error about overriding the following function or
 438  // about it being private, you have mis-spelled SetUp() as Setup().
 439  struct Setup_should_be_spelled_SetUp {};
 440  virtual Setup_should_be_spelled_SetUp* Setup() { return NULL; }
 441
 442  // We disallow copying Tests.
 443  GTEST_DISALLOW_COPY_AND_ASSIGN_(Test);
 444};
 445
 446typedef internal::TimeInMillis TimeInMillis;
 447
 448// A copyable object representing a user specified test property which can be
 449// output as a key/value string pair.
 450//
 451// Don't inherit from TestProperty as its destructor is not virtual.
 452class TestProperty {
 453 public:
 454  // C'tor.  TestProperty does NOT have a default constructor.
 455  // Always use this constructor (with parameters) to create a
 456  // TestProperty object.
 457  TestProperty(const char* a_key, const char* a_value) :
 458    key_(a_key), value_(a_value) {
 459  }
 460
 461  // Gets the user supplied key.
 462  const char* key() const {
 463    return key_.c_str();
 464  }
 465
 466  // Gets the user supplied value.
 467  const char* value() const {
 468    return value_.c_str();
 469  }
 470
 471  // Sets a new value, overriding the one supplied in the constructor.
 472  void SetValue(const char* new_value) {
 473    value_ = new_value;
 474  }
 475
 476 private:
 477  // The key supplied by the user.
 478  internal::String key_;
 479  // The value supplied by the user.
 480  internal::String value_;
 481};
 482
 483// The result of a single Test.  This includes a list of
 484// TestPartResults, a list of TestProperties, a count of how many
 485// death tests there are in the Test, and how much time it took to run
 486// the Test.
 487//
 488// TestResult is not copyable.
 489class GTEST_API_ TestResult {
 490 public:
 491  // Creates an empty TestResult.
 492  TestResult();
 493
 494  // D'tor.  Do not inherit from TestResult.
 495  ~TestResult();
 496
 497  // Gets the number of all test parts.  This is the sum of the number
 498  // of successful test parts and the number of failed test parts.
 499  int total_part_count() const;
 500
 501  // Returns the number of the test properties.
 502  int test_property_count() const;
 503
 504  // Returns true iff the test passed (i.e. no test part failed).
 505  bool Passed() const { return !Failed(); }
 506
 507  // Returns true iff the test failed.
 508  bool Failed() const;
 509
 510  // Returns true iff the test fatally failed.
 511  bool HasFatalFailure() const;
 512
 513  // Returns true iff the test has a non-fatal failure.
 514  bool HasNonfatalFailure() const;
 515
 516  // Returns the elapsed time, in milliseconds.
 517  TimeInMillis elapsed_time() const { return elapsed_time_; }
 518
 519  // Returns the i-th test part result among all the results. i can range
 520  // from 0 to test_property_count() - 1. If i is not in that range, aborts
 521  // the program.
 522  const TestPartResult& GetTestPartResult(int i) const;
 523
 524  // Returns the i-th test property. i can range from 0 to
 525  // test_property_count() - 1. If i is not in that range, aborts the
 526  // program.
 527  const TestProperty& GetTestProperty(int i) const;
 528
 529 private:
 530  friend class TestInfo;
 531  friend class UnitTest;
 532  friend class internal::DefaultGlobalTestPartResultReporter;
 533  friend class internal::ExecDeathTest;
 534  friend class internal::TestInfoImpl;
 535  friend class internal::TestResultAccessor;
 536  friend class internal::UnitTestImpl;
 537  friend class internal::WindowsDeathTest;
 538
 539  // Gets the vector of TestPartResults.
 540  const std::vector<TestPartResult>& test_part_results() const {
 541    return test_part_results_;
 542  }
 543
 544  // Gets the vector of TestProperties.
 545  const std::vector<TestProperty>& test_properties() const {
 546    return test_properties_;
 547  }
 548
 549  // Sets the elapsed time.
 550  void set_elapsed_time(TimeInMillis elapsed) { elapsed_time_ = elapsed; }
 551
 552  // Adds a test property to the list. The property is validated and may add
 553  // a non-fatal failure if invalid (e.g., if it conflicts with reserved
 554  // key names). If a property is already recorded for the same key, the
 555  // value will be updated, rather than storing multiple values for the same
 556  // key.
 557  void RecordProperty(const TestProperty& test_property);
 558
 559  // Adds a failure if the key is a reserved attribute of Google Test
 560  // testcase tags.  Returns true if the property is valid.
 561  // TODO(russr): Validate attribute names are legal and human readable.
 562  static bool ValidateTestProperty(const TestProperty& test_property);
 563
 564  // Adds a test part result to the list.
 565  void AddTestPartResult(const TestPartResult& test_part_result);
 566
 567  // Returns the death test count.
 568  int death_test_count() const { return death_test_count_; }
 569
 570  // Increments the death test count, returning the new count.
 571  int increment_death_test_count() { return ++death_test_count_; }
 572
 573  // Clears the test part results.
 574  void ClearTestPartResults();
 575
 576  // Clears the object.
 577  void Clear();
 578
 579  // Protects mutable state of the property vector and of owned
 580  // properties, whose values may be updated.
 581  internal::Mutex test_properites_mutex_;
 582
 583  // The vector of TestPartResults
 584  std::vector<TestPartResult> test_part_results_;
 585  // The vector of TestProperties
 586  std::vector<TestProperty> test_properties_;
 587  // Running count of death tests.
 588  int death_test_count_;
 589  // The elapsed time, in milliseconds.
 590  TimeInMillis elapsed_time_;
 591
 592  // We disallow copying TestResult.
 593  GTEST_DISALLOW_COPY_AND_ASSIGN_(TestResult);
 594};  // class TestResult
 595
 596// A TestInfo object stores the following information about a test:
 597//
 598//   Test case name
 599//   Test name
 600//   Whether the test should be run
 601//   A function pointer that creates the test object when invoked
 602//   Test result
 603//
 604// The constructor of TestInfo registers itself with the UnitTest
 605// singleton such that the RUN_ALL_TESTS() macro knows which tests to
 606// run.
 607class GTEST_API_ TestInfo {
 608 public:
 609  // Destructs a TestInfo object.  This function is not virtual, so
 610  // don't inherit from TestInfo.
 611  ~TestInfo();
 612
 613  // Returns the test case name.
 614  const char* test_case_name() const;
 615
 616  // Returns the test name.
 617  const char* name() const;
 618
 619  // Returns the test case comment.
 620  const char* test_case_comment() const;
 621
 622  // Returns the test comment.
 623  const char* comment() const;
 624
 625  // Returns true if this test should run, that is if the test is not disabled
 626  // (or it is disabled but the also_run_disabled_tests flag has been specified)
 627  // and its full name matches the user-specified filter.
 628  //
 629  // Google Test allows the user to filter the tests by their full names.
 630  // The full name of a test Bar in test case Foo is defined as
 631  // "Foo.Bar".  Only the tests that match the filter will run.
 632  //
 633  // A filter is a colon-separated list of glob (not regex) patterns,
 634  // optionally followed by a '-' and a colon-separated list of
 635  // negative patterns (tests to exclude).  A test is run if it
 636  // matches one of the positive patterns and does not match any of
 637  // the negative patterns.
 638  //
 639  // For example, *A*:Foo.* is a filter that matches any string that
 640  // contains the character 'A' or starts with "Foo.".
 641  bool should_run() const;
 642
 643  // Returns the result of the test.
 644  const TestResult* result() const;
 645
 646 private:
 647#if GTEST_HAS_DEATH_TEST
 648  friend class internal::DefaultDeathTestFactory;
 649#endif  // GTEST_HAS_DEATH_TEST
 650  friend class Test;
 651  friend class TestCase;
 652  friend class internal::TestInfoImpl;
 653  friend class internal::UnitTestImpl;
 654  friend TestInfo* internal::MakeAndRegisterTestInfo(
 655      const char* test_case_name, const char* name,
 656      const char* test_case_comment, const char* comment,
 657      internal::TypeId fixture_class_id,
 658      Test::SetUpTestCaseFunc set_up_tc,
 659      Test::TearDownTestCaseFunc tear_down_tc,
 660      internal::TestFactoryBase* factory);
 661
 662  // Returns true if this test matches the user-specified filter.
 663  bool matches_filter() const;
 664
 665  // Increments the number of death tests encountered in this test so
 666  // far.
 667  int increment_death_test_count();
 668
 669  // Accessors for the implementation object.
 670  internal::TestInfoImpl* impl() { return impl_; }
 671  const internal::TestInfoImpl* impl() const { return impl_; }
 672
 673  // Constructs a TestInfo object. The newly constructed instance assumes
 674  // ownership of the factory object.
 675  TestInfo(const char* test_case_name, const char* name,
 676           const char* test_case_comment, const char* comment,
 677           internal::TypeId fixture_class_id,
 678           internal::TestFactoryBase* factory);
 679
 680  // An opaque implementation object.
 681  internal::TestInfoImpl* impl_;
 682
 683  GTEST_DISALLOW_COPY_AND_ASSIGN_(TestInfo);
 684};
 685
 686// A test case, which consists of a vector of TestInfos.
 687//
 688// TestCase is not copyable.
 689class GTEST_API_ TestCase {
 690 public:
 691  // Creates a TestCase with the given name.
 692  //
 693  // TestCase does NOT have a default constructor.  Always use this
 694  // constructor to create a TestCase object.
 695  //
 696  // Arguments:
 697  //
 698  //   name:         name of the test case
 699  //   set_up_tc:    pointer to the function that sets up the test case
 700  //   tear_down_tc: pointer to the function that tears down the test case
 701  TestCase(const char* name, const char* comment,
 702           Test::SetUpTestCaseFunc set_up_tc,
 703           Test::TearDownTestCaseFunc tear_down_tc);
 704
 705  // Destructor of TestCase.
 706  virtual ~TestCase();
 707
 708  // Gets the name of the TestCase.
 709  const char* name() const { return name_.c_str(); }
 710
 711  // Returns the test case comment.
 712  const char* comment() const { return comment_.c_str(); }
 713
 714  // Returns true if any test in this test case should run.
 715  bool should_run() const { return should_run_; }
 716
 717  // Gets the number of successful tests in this test case.
 718  int successful_test_count() const;
 719
 720  // Gets the number of failed tests in this test case.
 721  int failed_test_count() const;
 722
 723  // Gets the number of disabled tests in this test case.
 724  int disabled_test_count() const;
 725
 726  // Get the number of tests in this test case that should run.
 727  int test_to_run_count() const;
 728
 729  // Gets the number of all tests in this test case.
 730  int total_test_count() const;
 731
 732  // Returns true iff the test case passed.
 733  bool Passed() const { return !Failed(); }
 734
 735  // Returns true iff the test case failed.
 736  bool Failed() const { return failed_test_count() > 0; }
 737
 738  // Returns the elapsed time, in milliseconds.
 739  TimeInMillis elapsed_time() const { return elapsed_time_; }
 740
 741  // Returns the i-th test among all the tests. i can range from 0 to
 742  // total_test_count() - 1. If i is not in that range, returns NULL.
 743  const TestInfo* GetTestInfo(int i) const;
 744
 745 private:
 746  friend class Test;
 747  friend class internal::UnitTestImpl;
 748
 749  // Gets the (mutable) vector of TestInfos in this TestCase.
 750  std::vector<TestInfo*>& test_info_list() { return test_info_list_; }
 751
 752  // Gets the (immutable) vector of TestInfos in this TestCase.
 753  const std::vector<TestInfo*>& test_info_list() const {
 754    return test_info_list_;
 755  }
 756
 757  // Returns the i-th test among all the tests. i can range from 0 to
 758  // total_test_count() - 1. If i is not in that range, returns NULL.
 759  TestInfo* GetMutableTestInfo(int i);
 760
 761  // Sets the should_run member.
 762  void set_should_run(bool should) { should_run_ = should; }
 763
 764  // Adds a TestInfo to this test case.  Will delete the TestInfo upon
 765  // destruction of the TestCase object.
 766  void AddTestInfo(TestInfo * test_info);
 767
 768  // Clears the results of all tests in this test case.
 769  void ClearResult();
 770
 771  // Clears the results of all tests in the given test case.
 772  static void ClearTestCaseResult(TestCase* test_case) {
 773    test_case->ClearResult();
 774  }
 775
 776  // Runs every test in this TestCase.
 777  void Run();
 778
 779  // Returns true iff test passed.
 780  static bool TestPassed(const TestInfo * test_info);
 781
 782  // Returns true iff test failed.
 783  static bool TestFailed(const TestInfo * test_info);
 784
 785  // Returns true iff test is disabled.
 786  static bool TestDisabled(const TestInfo * test_info);
 787
 788  // Returns true if the given test should run.
 789  static bool ShouldRunTest(const TestInfo *test_info);
 790
 791  // Shuffles the tests in this test case.
 792  void ShuffleTests(internal::Random* random);
 793
 794  // Restores the test order to before the first shuffle.
 795  void UnshuffleTests();
 796
 797  // Name of the test case.
 798  internal::String name_;
 799  // Comment on the test case.
 800  internal::String comment_;
 801  // The vector of TestInfos in their original order.  It owns the
 802  // elements in the vector.
 803  std::vector<TestInfo*> test_info_list_;
 804  // Provides a level of indirection for the test list to allow easy
 805  // shuffling and restoring the test order.  The i-th element in this
 806  // vector is the index of the i-th test in the shuffled test list.
 807  std::vector<int> test_indices_;
 808  // Pointer to the function that sets up the test case.
 809  Test::SetUpTestCaseFunc set_up_tc_;
 810  // Pointer to the function that tears down the test case.
 811  Test::TearDownTestCaseFunc tear_down_tc_;
 812  // True iff any test in this test case should run.
 813  bool should_run_;
 814  // Elapsed time, in milliseconds.
 815  TimeInMillis elapsed_time_;
 816
 817  // We disallow copying TestCases.
 818  GTEST_DISALLOW_COPY_AND_ASSIGN_(TestCase);
 819};
 820
 821// An Environment object is capable of setting up and tearing down an
 822// environment.  The user should subclass this to define his own
 823// environment(s).
 824//
 825// An Environment object does the set-up and tear-down in virtual
 826// methods SetUp() and TearDown() instead of the constructor and the
 827// destructor, as:
 828//
 829//   1. You cannot safely throw from a destructor.  This is a problem
 830//      as in some cases Google Test is used where exceptions are enabled, and
 831//      we may want to implement ASSERT_* using exceptions where they are
 832//      available.
 833//   2. You cannot use ASSERT_* directly in a constructor or
 834//      destructor.
 835class Environment {
 836 public:
 837  // The d'tor is virtual as we need to subclass Environment.
 838  virtual ~Environment() {}
 839
 840  // Override this to define how to set up the environment.
 841  virtual void SetUp() {}
 842
 843  // Override this to define how to tear down the environment.
 844  virtual void TearDown() {}
 845 private:
 846  // If you see an error about overriding the following function or
 847  // about it being private, you have mis-spelled SetUp() as Setup().
 848  struct Setup_should_be_spelled_SetUp {};
 849  virtual Setup_should_be_spelled_SetUp* Setup() { return NULL; }
 850};
 851
 852// The interface for tracing execution of tests. The methods are organized in
 853// the order the corresponding events are fired.
 854class TestEventListener {
 855 public:
 856  virtual ~TestEventListener() {}
 857
 858  // Fired before any test activity starts.
 859  virtual void OnTestProgramStart(const UnitTest& unit_test) = 0;
 860
 861  // Fired before each iteration of tests starts.  There may be more than
 862  // one iteration if GTEST_FLAG(repeat) is set. iteration is the iteration
 863  // index, starting from 0.
 864  virtual void OnTestIterationStart(const UnitTest& unit_test,
 865                                    int iteration) = 0;
 866
 867  // Fired before environment set-up for each iteration of tests starts.
 868  virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test) = 0;
 869
 870  // Fired after environment set-up for each iteration of tests ends.
 871  virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test) = 0;
 872
 873  // Fired before the test case starts.
 874  virtual void OnTestCaseStart(const TestCase& test_case) = 0;
 875
 876  // Fired before the test starts.
 877  virtual void OnTestStart(const TestInfo& test_info) = 0;
 878
 879  // Fired after a failed assertion or a SUCCESS().
 880  virtual void OnTestPartResult(const TestPartResult& test_part_result) = 0;
 881
 882  // Fired after the test ends.
 883  virtual void OnTestEnd(const TestInfo& test_info) = 0;
 884
 885  // Fired after the test case ends.
 886  virtual void OnTestCaseEnd(const TestCase& test_case) = 0;
 887
 888  // Fired before environment tear-down for each iteration of tests starts.
 889  virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test) = 0;
 890
 891  // Fired after environment tear-down for each iteration of tests ends.
 892  virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) = 0;
 893
 894  // Fired after each iteration of tests finishes.
 895  virtual void OnTestIterationEnd(const UnitTest& unit_test,
 896                                  int iteration) = 0;
 897
 898  // Fired after all test activities have ended.
 899  virtual void OnTestProgramEnd(const UnitTest& unit_test) = 0;
 900};
 901
 902// The convenience class for users who need to override just one or two
 903// methods and are not concerned that a possible change to a signature of
 904// the methods they override will not be caught during the build.  For
 905// comments about each method please see the definition of TestEventListener
 906// above.
 907class EmptyTestEventListener : public TestEventListener {
 908 public:
 909  virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {}
 910  virtual void OnTestIterationStart(const UnitTest& /*unit_test*/,
 911                                    int /*iteration*/) {}
 912  virtual void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) {}
 913  virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {}
 914  virtual void OnTestCaseStart(const TestCase& /*test_case*/) {}
 915  virtual void OnTestStart(const TestInfo& /*test_info*/) {}
 916  virtual void OnTestPartResult(const TestPartResult& /*test_part_result*/) {}
 917  virtual void OnTestEnd(const TestInfo& /*test_info*/) {}
 918  virtual void OnTestCaseEnd(const TestCase& /*test_case*/) {}
 919  virtual void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) {}
 920  virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {}
 921  virtual void OnTestIterationEnd(const UnitTest& /*unit_test*/,
 922                                  int /*iteration*/) {}
 923  virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {}
 924};
 925
 926// TestEventListeners lets users add listeners to track events in Google Test.
 927class GTEST_API_ TestEventListeners {
 928 public:
 929  TestEventListeners();
 930  ~TestEventListeners();
 931
 932  // Appends an event listener to the end of the list. Google Test assumes
 933  // the ownership of the listener (i.e. it will delete the listener when
 934  // the test program finishes).
 935  void Append(TestEventListener* listener);
 936
 937  // Removes the given event listener from the list and returns it.  It then
 938  // becomes the caller's responsibility to delete the listener. Returns
 939  // NULL if the listener is not found in the list.
 940  TestEventListener* Release(TestEventListener* listener);
 941
 942  // Returns the standard listener responsible for the default console
 943  // output.  Can be removed from the listeners list to shut down default
 944  // console output.  Note that removing this object from the listener list
 945  // with Release transfers its ownership to the caller and makes this
 946  // function return NULL the next time.
 947  TestEventListener* default_result_printer() const {
 948    return default_result_printer_;
 949  }
 950
 951  // Returns the standard listener responsible for the default XML output
 952  // controlled by the --gtest_output=xml flag.  Can be removed from the
 953  // listeners list by users who want to shut down the default XML output
 954  // controlled by this flag and substitute it with custom one.  Note that
 955  // removing this object from the listener list with Release transfers its
 956  // ownership to the caller and makes this function return NULL the next
 957  // time.
 958  TestEventListener* default_xml_generator() const {
 959    return default_xml_generator_;
 960  }
 961
 962 private:
 963  friend class TestCase;
 964  friend class internal::DefaultGlobalTestPartResultReporter;
 965  friend class internal::NoExecDeathTest;
 966  friend class internal::TestEventListenersAccessor;
 967  friend class internal::TestInfoImpl;
 968  friend class internal::UnitTestImpl;
 969
 970  // Returns repeater that broadcasts the TestEventListener events to all
 971  // subscribers.
 972  TestEventListener* repeater();
 973
 974  // Sets the default_result_printer attribute to the provided listener.
 975  // The listener is also added to the listener list and previous
 976  // default_result_printer is removed from it and deleted. The listener can
 977  // also be NULL in which case it will not be added to the list. Does
 978  // nothing if the previous and the current listener objects are the same.
 979  void SetDefaultResultPrinter(TestEventListener* listener);
 980
 981  // Sets the default_xml_generator attribute to the provided listener.  The
 982  // listener is also added to the listener list and previous
 983  // default_xml_generator is removed from it and deleted. The listener can
 984  // also be NULL in which case it will not be added to the list. Does
 985  // nothing if the previous and the current listener objects are the same.
 986  void SetDefaultXmlGenerator(TestEventListener* listener);
 987
 988  // Controls whether events will be forwarded by the repeater to the
 989  // listeners in the list.
 990  bool EventForwardingEnabled() const;
 991  void SuppressEventForwarding();
 992
 993  // The actual list of listeners.
 994  internal::TestEventRepeater* repeater_;
 995  // Listener responsible for the standard result output.
 996  TestEventListener* default_result_printer_;
 997  // Listener responsible for the creation of the XML output file.
 998  TestEventListener* default_xml_generator_;
 999
1000  // We disallow copying TestEventListeners.
1001  GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventListeners);
1002};
1003
1004// A UnitTest consists of a vector of TestCases.
1005//
1006// This is a singleton class.  The only instance of UnitTest is
1007// created when UnitTest::GetInstance() is first called.  This
1008// instance is never deleted.
1009//
1010// UnitTest is not copyable.
1011//
1012// This class is thread-safe as long as the methods are called
1013// according to their specification.
1014class GTEST_API_ UnitTest {
1015 public:
1016  // Gets the singleton UnitTest object.  The first time this method
1017  // is called, a UnitTest object is constructed and returned.
1018  // Consecutive calls will return the same object.
1019  static UnitTest* GetInstance();
1020
1021  // Runs all tests in this UnitTest object and prints the result.
1022  // Returns 0 if successful, or 1 otherwise.
1023  //
1024  // This method can only be called from the main thread.
1025  //
1026  // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1027  int Run() GTEST_MUST_USE_RESULT_;
1028
1029  // Returns the working directory when the first TEST() or TEST_F()
1030  // was executed.  The UnitTest object owns the string.
1031  const char* original_working_dir() const;
1032
1033  // Returns the TestCase object for the test that's currently running,
1034  // or NULL if no test is running.
1035  const TestCase* current_test_case() const;
1036
1037  // Returns the TestInfo object for the test that's currently running,
1038  // or NULL if no test is running.
1039  const TestInfo* current_test_info() const;
1040
1041  // Returns the random seed used at the start of the current test run.
1042  int random_seed() const;
1043
1044#if GTEST_HAS_PARAM_TEST
1045  // Returns the ParameterizedTestCaseRegistry object used to keep track of
1046  // value-parameterized tests and instantiate and register them.
1047  //
1048  // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1049  internal::ParameterizedTestCaseRegistry& parameterized_test_registry();
1050#endif  // GTEST_HAS_PARAM_TEST
1051
1052  // Gets the number of successful test cases.
1053  int successful_test_case_count() const;
1054
1055  // Gets the number of failed test cases.
1056  int failed_test_case_count() const;
1057
1058  // Gets the number of all test cases.
1059  int total_test_case_count() const;
1060
1061  // Gets the number of all test cases that contain at least one test
1062  // that should run.
1063  int test_case_to_run_count() const;
1064
1065  // Gets the number of successful tests.
1066  int successful_test_count() const;
1067
1068  // Gets the number of failed tests.
1069  int failed_test_count() const;
1070
1071  // Gets the number of disabled tests.
1072  int disabled_test_count() const;
1073
1074  // Gets the number of all tests.
1075  int total_test_count() const;
1076
1077  // Gets the number of tests that should run.
1078  int test_to_run_count() const;
1079
1080  // Gets the elapsed time, in milliseconds.
1081  TimeInMillis elapsed_time() const;
1082
1083  // Returns true iff the unit test passed (i.e. all test cases passed).
1084  bool Passed() const;
1085
1086  // Returns true iff the unit test failed (i.e. some test case failed
1087  // or something outside of all tests failed).
1088  bool Failed() const;
1089
1090  // Gets the i-th test case among all the test cases. i can range from 0 to
1091  // total_test_case_count() - 1. If i is not in that range, returns NULL.
1092  const TestCase* GetTestCase(int i) const;
1093
1094  // Returns the list of event listeners that can be used to track events
1095  // inside Google Test.
1096  TestEventListeners& listeners();
1097
1098 private:
1099  // Registers and returns a global test environment.  When a test
1100  // program is run, all global test environments will be set-up in
1101  // the order they were registered.  After all tests in the program
1102  // have finished, all global test environments will be torn-down in
1103  // the *reverse* order they were registered.
1104  //
1105  // The UnitTest object takes ownership of the given environment.
1106  //
1107  // This method can only be called from the main thread.
1108  Environment* AddEnvironment(Environment* env);
1109
1110  // Adds a TestPartResult to the current TestResult object.  All
1111  // Google Test assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc)
1112  // eventually call this to report their results.  The user code
1113  // should use the assertion macros instead of calling this directly.
1114  void AddTestPartResult(TestPartResult::Type result_type,
1115                         const char* file_name,
1116                         int line_number,
1117                         const internal::String& message,
1118                         const internal::String& os_stack_trace);
1119
1120  // Adds a TestProperty to the current TestResult object. If the result already
1121  // contains a property with the same key, the value will be updated.
1122  void RecordPropertyForCurrentTest(const char* key, const char* value);
1123
1124  // Gets the i-th test case among all the test cases. i can range from 0 to
1125  // total_test_case_count() - 1. If i is not in that range, returns NULL.
1126  TestCase* GetMutableTestCase(int i);
1127
1128  // Accessors for the implementation object.
1129  internal::UnitTestImpl* impl() { return impl_; }
1130  const internal::UnitTestImpl* impl() const { return impl_; }
1131
1132  // These classes and funcions are friends as they need to access private
1133  // members of UnitTest.
1134  friend class Test;
1135  friend class internal::AssertHelper;
1136  friend class internal::ScopedTrace;
1137  friend Environment* AddGlobalTestEnvironment(Environment* env);
1138  friend internal::UnitTestImpl* internal::GetUnitTestImpl();
1139  friend void internal::ReportFailureInUnknownLocation(
1140      TestPartResult::Type result_type,
1141      const internal::String& message);
1142
1143  // Creates an empty UnitTest.
1144  UnitTest();
1145
1146  // D'tor
1147  virtual ~UnitTest();
1148
1149  // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
1150  // Google Test trace stack.
1151  void PushGTestTrace(const internal::TraceInfo& trace);
1152
1153  // Pops a trace from the per-thread Google Test trace stack.
1154  void PopGTestTrace();
1155
1156  // Protects mutable state in *impl_.  This is mutable as some const
1157  // methods need to lock it too.
1158  mutable internal::Mutex mutex_;
1159
1160  // Opaque implementation object.  This field is never changed once
1161  // the object is constructed.  We don't mark it as const here, as
1162  // doing so will cause a warning in the constructor of UnitTest.
1163  // Mutable state in *impl_ is protected by mutex_.
1164  internal::UnitTestImpl* impl_;
1165
1166  // We disallow copying UnitTest.
1167  GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTest);
1168};
1169
1170// A convenient wrapper for adding an environment for the test
1171// program.
1172//
1173// You should call this before RUN_ALL_TESTS() is called, probably in
1174// main().  If you use gtest_main, you need to call this before main()
1175// starts for it to take effect.  For example, you can define a global
1176// variable like this:
1177//
1178//   testing::Environment* const foo_env =
1179//       testing::AddGlobalTestEnvironment(new FooEnvironment);
1180//
1181// However, we strongly recommend you to write your own main() and
1182// call AddGlobalTestEnvironment() there, as relying on initialization
1183// of global variables makes the code harder to read and may cause
1184// problems when you register multiple environments from different
1185// translation units and the environments have dependencies among them
1186// (remember that the compiler doesn't guarantee the order in which
1187// global variables from different translation units are initialized).
1188inline Environment* AddGlobalTestEnvironment(Environment* env) {
1189  return UnitTest::GetInstance()->AddEnvironment(env);
1190}
1191
1192// Initializes Google Test.  This must be called before calling
1193// RUN_ALL_TESTS().  In particular, it parses a command line for the
1194// flags that Google Test recognizes.  Whenever a Google Test flag is
1195// seen, it is removed from argv, and *argc is decremented.
1196//
1197// No value is returned.  Instead, the Google Test flag variables are
1198// updated.
1199//
1200// Calling the function for the second time has no user-visible effect.
1201GTEST_API_ void InitGoogleTest(int* argc, char** argv);
1202
1203// This overloaded version can be used in Windows programs compiled in
1204// UNICODE mode.
1205GTEST_API_ void InitGoogleTest(int* argc, wchar_t** argv);
1206
1207namespace internal {
1208
1209// These overloaded versions handle ::std::string and ::std::wstring.
1210GTEST_API_ inline String FormatForFailureMessage(const ::std::string& str) {
1211  return (Message() << '"' << str << '"').GetString();
1212}
1213
1214#if GTEST_HAS_STD_WSTRING
1215GTEST_API_ inline String FormatForFailureMessage(const ::std::wstring& wstr) {
1216  return (Message() << "L\"" << wstr << '"').GetString();
1217}
1218#endif  // GTEST_HAS_STD_WSTRING
1219
1220// These overloaded versions handle ::string and ::wstring.
1221#if GTEST_HAS_GLOBAL_STRING
1222GTEST_API_ inline String FormatForFailureMessage(const ::string& str) {
1223  return (Message() << '"' << str << '"').GetString();
1224}
1225#endif  // GTEST_HAS_GLOBAL_STRING
1226
1227#if GTEST_HAS_GLOBAL_WSTRING
1228GTEST_API_ inline String FormatForFailureMessage(const ::wstring& wstr) {
1229  return (Message() << "L\"" << wstr << '"').GetString();
1230}
1231#endif  // GTEST_HAS_GLOBAL_WSTRING
1232
1233// Formats a comparison assertion (e.g. ASSERT_EQ, EXPECT_LT, and etc)
1234// operand to be used in a failure message.  The type (but not value)
1235// of the other operand may affect the format.  This allows us to
1236// print a char* as a raw pointer when it is compared against another
1237// char*, and print it as a C string when it is compared against an
1238// std::string object, for example.
1239//
1240// The default implementation ignores the type of the other operand.
1241// Some specialized versions are used to handle formatting wide or
1242// narrow C strings.
1243//
1244// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1245template <typename T1, typename T2>
1246String FormatForComparisonFailureMessage(const T1& value,
1247                                         const T2& /* other_operand */) {
1248  return FormatForFailureMessage(value);
1249}
1250
1251// The helper function for {ASSERT|EXPECT}_EQ.
1252template <typename T1, typename T2>
1253AssertionResult CmpHelperEQ(const char* expected_expression,
1254                            const char* actual_expression,
1255                            const T1& expected,
1256                            const T2& actual) {
1257#ifdef _MSC_VER
1258#pragma warning(push)          // Saves the current warning state.
1259#pragma warning(disable:4389)  // Temporarily disables warning on
1260                               // signed/unsigned mismatch.
1261#endif
1262
1263  if (expected == actual) {
1264    return AssertionSuccess();
1265  }
1266
1267#ifdef _MSC_VER
1268#pragma warning(pop)          // Restores the warning state.
1269#endif
1270
1271  return EqFailure(expected_expression,
1272                   actual_expression,
1273                   FormatForComparisonFailureMessage(expected, actual),
1274                   FormatForComparisonFailureMessage(actual, expected),
1275                   false);
1276}
1277
1278// With this overloaded version, we allow anonymous enums to be used
1279// in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous enums
1280// can be implicitly cast to BiggestInt.
1281GTEST_API_ AssertionResult CmpHelperEQ(const char* expected_expression,
1282                                       const char* actual_expression,
1283                                       BiggestInt expected,
1284                                       BiggestInt actual);
1285
1286// The helper class for {ASSERT|EXPECT}_EQ.  The template argument
1287// lhs_is_null_literal is true iff the first argument to ASSERT_EQ()
1288// is a null pointer literal.  The following default implementation is
1289// for lhs_is_null_literal being false.
1290template <bool lhs_is_null_literal>
1291class EqHelper {
1292 public:
1293  // This templatized version is for the general case.
1294  template <typename T1, typename T2>
1295  static AssertionResult Compare(const char* expected_expression,
1296                                 const char* actual_expression,
1297                                 const T1& expected,
1298                                 const T2& actual) {
1299    return CmpHelperEQ(expected_expression, actual_expression, expected,
1300                       actual);
1301  }
1302
1303  // With this overloaded version, we allow anonymous enums to be used
1304  // in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous
1305  // enums can be implicitly cast to BiggestInt.
1306  //
1307  // Even though its body looks the same as the above version, we
1308  // cannot merge the two, as it will make anonymous enums unhappy.
1309  static AssertionResult Compare(const char* expected_expression,
1310                                 const char* actual_expression,
1311                                 BiggestInt expected,
1312                                 BiggestInt actual) {
1313    return CmpHelperEQ(expected_expression, actual_expression, expected,
1314                       actual);
1315  }
1316};
1317
1318// This specialization is used when the first argument to ASSERT_EQ()
1319// is a null pointer literal.
1320template <>
1321class EqHelper<true> {
1322 public:
1323  // We define two overloaded versions of Compare().  The first
1324  // version will be picked when the second argument to ASSERT_EQ() is
1325  // NOT a pointer, e.g. ASSERT_EQ(0, AnIntFunction()) or
1326  // EXPECT_EQ(false, a_bool).
1327  template <typename T1, typename T2>
1328  static AssertionResult Compare(const char* expected_expression,
1329                                 const char* actual_expression,
1330                                 const T1& expected,
1331                                 const T2& actual) {
1332    return CmpHelperEQ(expected_expression, actual_expression, expected,
1333                       actual);
1334  }
1335
1336  // This version will be picked when the second argument to
1337  // ASSERT_EQ() is a pointer, e.g. ASSERT_EQ(NULL, a_pointer).
1338  template <typename T1, typename T2>

Large files files are truncated, but you can click here to view the full file