PageRenderTime 822ms CodeModel.GetById 282ms app.highlight 344ms RepoModel.GetById 178ms app.codeStats 1ms

/Unittests/googletest/include/gtest/gtest.h

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

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