PageRenderTime 134ms CodeModel.GetById 49ms app.highlight 72ms RepoModel.GetById 1ms app.codeStats 1ms

/thirdparty/breakpad/third_party/protobuf/protobuf/gtest/src/gtest.cc

http://github.com/tomahawk-player/tomahawk
C++ | 1800 lines | 1098 code | 259 blank | 443 comment | 191 complexity | 8de68a35c745eae12a68802b12569879 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#include <gtest/gtest.h>
  35#include <gtest/gtest-spi.h>
  36
  37#include <ctype.h>
  38#include <math.h>
  39#include <stdarg.h>
  40#include <stdio.h>
  41#include <stdlib.h>
  42#include <wchar.h>
  43#include <wctype.h>
  44
  45#include <algorithm>
  46#include <ostream>
  47#include <sstream>
  48#include <vector>
  49
  50#if GTEST_OS_LINUX
  51
  52// TODO(kenton@google.com): Use autoconf to detect availability of
  53// gettimeofday().
  54#define GTEST_HAS_GETTIMEOFDAY_ 1
  55
  56#include <fcntl.h>
  57#include <limits.h>
  58#include <sched.h>
  59// Declares vsnprintf().  This header is not available on Windows.
  60#include <strings.h>
  61#include <sys/mman.h>
  62#include <sys/time.h>
  63#include <unistd.h>
  64#include <string>
  65#include <vector>
  66
  67#elif GTEST_OS_SYMBIAN
  68#define GTEST_HAS_GETTIMEOFDAY_ 1
  69#include <sys/time.h>  // NOLINT
  70
  71#elif GTEST_OS_ZOS
  72#define GTEST_HAS_GETTIMEOFDAY_ 1
  73#include <sys/time.h>  // NOLINT
  74
  75// On z/OS we additionally need strings.h for strcasecmp.
  76#include <strings.h>  // NOLINT
  77
  78#elif GTEST_OS_WINDOWS_MOBILE  // We are on Windows CE.
  79
  80#include <windows.h>  // NOLINT
  81
  82#elif GTEST_OS_WINDOWS  // We are on Windows proper.
  83
  84#include <io.h>  // NOLINT
  85#include <sys/timeb.h>  // NOLINT
  86#include <sys/types.h>  // NOLINT
  87#include <sys/stat.h>  // NOLINT
  88
  89#if GTEST_OS_WINDOWS_MINGW
  90// MinGW has gettimeofday() but not _ftime64().
  91// TODO(kenton@google.com): Use autoconf to detect availability of
  92//   gettimeofday().
  93// TODO(kenton@google.com): There are other ways to get the time on
  94//   Windows, like GetTickCount() or GetSystemTimeAsFileTime().  MinGW
  95//   supports these.  consider using them instead.
  96#define GTEST_HAS_GETTIMEOFDAY_ 1
  97#include <sys/time.h>  // NOLINT
  98#endif  // GTEST_OS_WINDOWS_MINGW
  99
 100// cpplint thinks that the header is already included, so we want to
 101// silence it.
 102#include <windows.h>  // NOLINT
 103
 104#else
 105
 106// Assume other platforms have gettimeofday().
 107// TODO(kenton@google.com): Use autoconf to detect availability of
 108//   gettimeofday().
 109#define GTEST_HAS_GETTIMEOFDAY_ 1
 110
 111// cpplint thinks that the header is already included, so we want to
 112// silence it.
 113#include <sys/time.h>  // NOLINT
 114#include <unistd.h>  // NOLINT
 115
 116#endif  // GTEST_OS_LINUX
 117
 118#if GTEST_HAS_EXCEPTIONS
 119#include <stdexcept>
 120#endif
 121
 122// Indicates that this translation unit is part of Google Test's
 123// implementation.  It must come before gtest-internal-inl.h is
 124// included, or there will be a compiler error.  This trick is to
 125// prevent a user from accidentally including gtest-internal-inl.h in
 126// his code.
 127#define GTEST_IMPLEMENTATION_ 1
 128#include "src/gtest-internal-inl.h"
 129#undef GTEST_IMPLEMENTATION_
 130
 131#if GTEST_OS_WINDOWS
 132#define vsnprintf _vsnprintf
 133#endif  // GTEST_OS_WINDOWS
 134
 135namespace testing {
 136
 137using internal::CountIf;
 138using internal::ForEach;
 139using internal::GetElementOr;
 140using internal::Shuffle;
 141
 142// Constants.
 143
 144// A test whose test case name or test name matches this filter is
 145// disabled and not run.
 146static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
 147
 148// A test case whose name matches this filter is considered a death
 149// test case and will be run before test cases whose name doesn't
 150// match this filter.
 151static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*";
 152
 153// A test filter that matches everything.
 154static const char kUniversalFilter[] = "*";
 155
 156// The default output file for XML output.
 157static const char kDefaultOutputFile[] = "test_detail.xml";
 158
 159// The environment variable name for the test shard index.
 160static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
 161// The environment variable name for the total number of test shards.
 162static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
 163// The environment variable name for the test shard status file.
 164static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
 165
 166namespace internal {
 167
 168// The text used in failure messages to indicate the start of the
 169// stack trace.
 170const char kStackTraceMarker[] = "\nStack trace:\n";
 171
 172// g_help_flag is true iff the --help flag or an equivalent form is
 173// specified on the command line.
 174bool g_help_flag = false;
 175
 176}  // namespace internal
 177
 178GTEST_DEFINE_bool_(
 179    also_run_disabled_tests,
 180    internal::BoolFromGTestEnv("also_run_disabled_tests", false),
 181    "Run disabled tests too, in addition to the tests normally being run.");
 182
 183GTEST_DEFINE_bool_(
 184    break_on_failure,
 185    internal::BoolFromGTestEnv("break_on_failure", false),
 186    "True iff a failed assertion should be a debugger break-point.");
 187
 188GTEST_DEFINE_bool_(
 189    catch_exceptions,
 190    internal::BoolFromGTestEnv("catch_exceptions", false),
 191    "True iff " GTEST_NAME_
 192    " should catch exceptions and treat them as test failures.");
 193
 194GTEST_DEFINE_string_(
 195    color,
 196    internal::StringFromGTestEnv("color", "auto"),
 197    "Whether to use colors in the output.  Valid values: yes, no, "
 198    "and auto.  'auto' means to use colors if the output is "
 199    "being sent to a terminal and the TERM environment variable "
 200    "is set to xterm, xterm-color, xterm-256color, linux or cygwin.");
 201
 202GTEST_DEFINE_string_(
 203    filter,
 204    internal::StringFromGTestEnv("filter", kUniversalFilter),
 205    "A colon-separated list of glob (not regex) patterns "
 206    "for filtering the tests to run, optionally followed by a "
 207    "'-' and a : separated list of negative patterns (tests to "
 208    "exclude).  A test is run if it matches one of the positive "
 209    "patterns and does not match any of the negative patterns.");
 210
 211GTEST_DEFINE_bool_(list_tests, false,
 212                   "List all tests without running them.");
 213
 214GTEST_DEFINE_string_(
 215    output,
 216    internal::StringFromGTestEnv("output", ""),
 217    "A format (currently must be \"xml\"), optionally followed "
 218    "by a colon and an output file name or directory. A directory "
 219    "is indicated by a trailing pathname separator. "
 220    "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
 221    "If a directory is specified, output files will be created "
 222    "within that directory, with file-names based on the test "
 223    "executable's name and, if necessary, made unique by adding "
 224    "digits.");
 225
 226GTEST_DEFINE_bool_(
 227    print_time,
 228    internal::BoolFromGTestEnv("print_time", true),
 229    "True iff " GTEST_NAME_
 230    " should display elapsed time in text output.");
 231
 232GTEST_DEFINE_int32_(
 233    random_seed,
 234    internal::Int32FromGTestEnv("random_seed", 0),
 235    "Random number seed to use when shuffling test orders.  Must be in range "
 236    "[1, 99999], or 0 to use a seed based on the current time.");
 237
 238GTEST_DEFINE_int32_(
 239    repeat,
 240    internal::Int32FromGTestEnv("repeat", 1),
 241    "How many times to repeat each test.  Specify a negative number "
 242    "for repeating forever.  Useful for shaking out flaky tests.");
 243
 244GTEST_DEFINE_bool_(
 245    show_internal_stack_frames, false,
 246    "True iff " GTEST_NAME_ " should include internal stack frames when "
 247    "printing test failure stack traces.");
 248
 249GTEST_DEFINE_bool_(
 250    shuffle,
 251    internal::BoolFromGTestEnv("shuffle", false),
 252    "True iff " GTEST_NAME_
 253    " should randomize tests' order on every run.");
 254
 255GTEST_DEFINE_int32_(
 256    stack_trace_depth,
 257    internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
 258    "The maximum number of stack frames to print when an "
 259    "assertion fails.  The valid range is 0 through 100, inclusive.");
 260
 261GTEST_DEFINE_bool_(
 262    throw_on_failure,
 263    internal::BoolFromGTestEnv("throw_on_failure", false),
 264    "When this flag is specified, a failed assertion will throw an exception "
 265    "if exceptions are enabled or exit the program with a non-zero code "
 266    "otherwise.");
 267
 268namespace internal {
 269
 270// Generates a random number from [0, range), using a Linear
 271// Congruential Generator (LCG).  Crashes if 'range' is 0 or greater
 272// than kMaxRange.
 273UInt32 Random::Generate(UInt32 range) {
 274  // These constants are the same as are used in glibc's rand(3).
 275  state_ = (1103515245U*state_ + 12345U) % kMaxRange;
 276
 277  GTEST_CHECK_(range > 0)
 278      << "Cannot generate a number in the range [0, 0).";
 279  GTEST_CHECK_(range <= kMaxRange)
 280      << "Generation of a number in [0, " << range << ") was requested, "
 281      << "but this can only generate numbers in [0, " << kMaxRange << ").";
 282
 283  // Converting via modulus introduces a bit of downward bias, but
 284  // it's simple, and a linear congruential generator isn't too good
 285  // to begin with.
 286  return state_ % range;
 287}
 288
 289// GTestIsInitialized() returns true iff the user has initialized
 290// Google Test.  Useful for catching the user mistake of not initializing
 291// Google Test before calling RUN_ALL_TESTS().
 292//
 293// A user must call testing::InitGoogleTest() to initialize Google
 294// Test.  g_init_gtest_count is set to the number of times
 295// InitGoogleTest() has been called.  We don't protect this variable
 296// under a mutex as it is only accessed in the main thread.
 297int g_init_gtest_count = 0;
 298static bool GTestIsInitialized() { return g_init_gtest_count != 0; }
 299
 300// Iterates over a vector of TestCases, keeping a running sum of the
 301// results of calling a given int-returning method on each.
 302// Returns the sum.
 303static int SumOverTestCaseList(const std::vector<TestCase*>& case_list,
 304                               int (TestCase::*method)() const) {
 305  int sum = 0;
 306  for (size_t i = 0; i < case_list.size(); i++) {
 307    sum += (case_list[i]->*method)();
 308  }
 309  return sum;
 310}
 311
 312// Returns true iff the test case passed.
 313static bool TestCasePassed(const TestCase* test_case) {
 314  return test_case->should_run() && test_case->Passed();
 315}
 316
 317// Returns true iff the test case failed.
 318static bool TestCaseFailed(const TestCase* test_case) {
 319  return test_case->should_run() && test_case->Failed();
 320}
 321
 322// Returns true iff test_case contains at least one test that should
 323// run.
 324static bool ShouldRunTestCase(const TestCase* test_case) {
 325  return test_case->should_run();
 326}
 327
 328// AssertHelper constructor.
 329AssertHelper::AssertHelper(TestPartResult::Type type,
 330                           const char* file,
 331                           int line,
 332                           const char* message)
 333    : data_(new AssertHelperData(type, file, line, message)) {
 334}
 335
 336AssertHelper::~AssertHelper() {
 337  delete data_;
 338}
 339
 340// Message assignment, for assertion streaming support.
 341void AssertHelper::operator=(const Message& message) const {
 342  UnitTest::GetInstance()->
 343    AddTestPartResult(data_->type, data_->file, data_->line,
 344                      AppendUserMessage(data_->message, message),
 345                      UnitTest::GetInstance()->impl()
 346                      ->CurrentOsStackTraceExceptTop(1)
 347                      // Skips the stack frame for this function itself.
 348                      );  // NOLINT
 349}
 350
 351// Mutex for linked pointers.
 352GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex);
 353
 354// Application pathname gotten in InitGoogleTest.
 355String g_executable_path;
 356
 357// Returns the current application's name, removing directory path if that
 358// is present.
 359FilePath GetCurrentExecutableName() {
 360  FilePath result;
 361
 362#if GTEST_OS_WINDOWS
 363  result.Set(FilePath(g_executable_path).RemoveExtension("exe"));
 364#else
 365  result.Set(FilePath(g_executable_path));
 366#endif  // GTEST_OS_WINDOWS
 367
 368  return result.RemoveDirectoryName();
 369}
 370
 371// Functions for processing the gtest_output flag.
 372
 373// Returns the output format, or "" for normal printed output.
 374String UnitTestOptions::GetOutputFormat() {
 375  const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
 376  if (gtest_output_flag == NULL) return String("");
 377
 378  const char* const colon = strchr(gtest_output_flag, ':');
 379  return (colon == NULL) ?
 380      String(gtest_output_flag) :
 381      String(gtest_output_flag, colon - gtest_output_flag);
 382}
 383
 384// Returns the name of the requested output file, or the default if none
 385// was explicitly specified.
 386String UnitTestOptions::GetAbsolutePathToOutputFile() {
 387  const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
 388  if (gtest_output_flag == NULL)
 389    return String("");
 390
 391  const char* const colon = strchr(gtest_output_flag, ':');
 392  if (colon == NULL)
 393    return String(internal::FilePath::ConcatPaths(
 394               internal::FilePath(
 395                   UnitTest::GetInstance()->original_working_dir()),
 396               internal::FilePath(kDefaultOutputFile)).ToString() );
 397
 398  internal::FilePath output_name(colon + 1);
 399  if (!output_name.IsAbsolutePath())
 400    // TODO(wan@google.com): on Windows \some\path is not an absolute
 401    // path (as its meaning depends on the current drive), yet the
 402    // following logic for turning it into an absolute path is wrong.
 403    // Fix it.
 404    output_name = internal::FilePath::ConcatPaths(
 405        internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
 406        internal::FilePath(colon + 1));
 407
 408  if (!output_name.IsDirectory())
 409    return output_name.ToString();
 410
 411  internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
 412      output_name, internal::GetCurrentExecutableName(),
 413      GetOutputFormat().c_str()));
 414  return result.ToString();
 415}
 416
 417// Returns true iff the wildcard pattern matches the string.  The
 418// first ':' or '\0' character in pattern marks the end of it.
 419//
 420// This recursive algorithm isn't very efficient, but is clear and
 421// works well enough for matching test names, which are short.
 422bool UnitTestOptions::PatternMatchesString(const char *pattern,
 423                                           const char *str) {
 424  switch (*pattern) {
 425    case '\0':
 426    case ':':  // Either ':' or '\0' marks the end of the pattern.
 427      return *str == '\0';
 428    case '?':  // Matches any single character.
 429      return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);
 430    case '*':  // Matches any string (possibly empty) of characters.
 431      return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||
 432          PatternMatchesString(pattern + 1, str);
 433    default:  // Non-special character.  Matches itself.
 434      return *pattern == *str &&
 435          PatternMatchesString(pattern + 1, str + 1);
 436  }
 437}
 438
 439bool UnitTestOptions::MatchesFilter(const String& name, const char* filter) {
 440  const char *cur_pattern = filter;
 441  for (;;) {
 442    if (PatternMatchesString(cur_pattern, name.c_str())) {
 443      return true;
 444    }
 445
 446    // Finds the next pattern in the filter.
 447    cur_pattern = strchr(cur_pattern, ':');
 448
 449    // Returns if no more pattern can be found.
 450    if (cur_pattern == NULL) {
 451      return false;
 452    }
 453
 454    // Skips the pattern separater (the ':' character).
 455    cur_pattern++;
 456  }
 457}
 458
 459// TODO(keithray): move String function implementations to gtest-string.cc.
 460
 461// Returns true iff the user-specified filter matches the test case
 462// name and the test name.
 463bool UnitTestOptions::FilterMatchesTest(const String &test_case_name,
 464                                        const String &test_name) {
 465  const String& full_name = String::Format("%s.%s",
 466                                           test_case_name.c_str(),
 467                                           test_name.c_str());
 468
 469  // Split --gtest_filter at '-', if there is one, to separate into
 470  // positive filter and negative filter portions
 471  const char* const p = GTEST_FLAG(filter).c_str();
 472  const char* const dash = strchr(p, '-');
 473  String positive;
 474  String negative;
 475  if (dash == NULL) {
 476    positive = GTEST_FLAG(filter).c_str();  // Whole string is a positive filter
 477    negative = String("");
 478  } else {
 479    positive = String(p, dash - p);  // Everything up to the dash
 480    negative = String(dash+1);       // Everything after the dash
 481    if (positive.empty()) {
 482      // Treat '-test1' as the same as '*-test1'
 483      positive = kUniversalFilter;
 484    }
 485  }
 486
 487  // A filter is a colon-separated list of patterns.  It matches a
 488  // test if any pattern in it matches the test.
 489  return (MatchesFilter(full_name, positive.c_str()) &&
 490          !MatchesFilter(full_name, negative.c_str()));
 491}
 492
 493#if GTEST_OS_WINDOWS
 494// Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
 495// given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
 496// This function is useful as an __except condition.
 497int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
 498  // Google Test should handle an exception if:
 499  //   1. the user wants it to, AND
 500  //   2. this is not a breakpoint exception.
 501  return (GTEST_FLAG(catch_exceptions) &&
 502          exception_code != EXCEPTION_BREAKPOINT) ?
 503      EXCEPTION_EXECUTE_HANDLER :
 504      EXCEPTION_CONTINUE_SEARCH;
 505}
 506#endif  // GTEST_OS_WINDOWS
 507
 508}  // namespace internal
 509
 510// The c'tor sets this object as the test part result reporter used by
 511// Google Test.  The 'result' parameter specifies where to report the
 512// results. Intercepts only failures from the current thread.
 513ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
 514    TestPartResultArray* result)
 515    : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
 516      result_(result) {
 517  Init();
 518}
 519
 520// The c'tor sets this object as the test part result reporter used by
 521// Google Test.  The 'result' parameter specifies where to report the
 522// results.
 523ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
 524    InterceptMode intercept_mode, TestPartResultArray* result)
 525    : intercept_mode_(intercept_mode),
 526      result_(result) {
 527  Init();
 528}
 529
 530void ScopedFakeTestPartResultReporter::Init() {
 531  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
 532  if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
 533    old_reporter_ = impl->GetGlobalTestPartResultReporter();
 534    impl->SetGlobalTestPartResultReporter(this);
 535  } else {
 536    old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
 537    impl->SetTestPartResultReporterForCurrentThread(this);
 538  }
 539}
 540
 541// The d'tor restores the test part result reporter used by Google Test
 542// before.
 543ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
 544  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
 545  if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
 546    impl->SetGlobalTestPartResultReporter(old_reporter_);
 547  } else {
 548    impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
 549  }
 550}
 551
 552// Increments the test part result count and remembers the result.
 553// This method is from the TestPartResultReporterInterface interface.
 554void ScopedFakeTestPartResultReporter::ReportTestPartResult(
 555    const TestPartResult& result) {
 556  result_->Append(result);
 557}
 558
 559namespace internal {
 560
 561// Returns the type ID of ::testing::Test.  We should always call this
 562// instead of GetTypeId< ::testing::Test>() to get the type ID of
 563// testing::Test.  This is to work around a suspected linker bug when
 564// using Google Test as a framework on Mac OS X.  The bug causes
 565// GetTypeId< ::testing::Test>() to return different values depending
 566// on whether the call is from the Google Test framework itself or
 567// from user test code.  GetTestTypeId() is guaranteed to always
 568// return the same value, as it always calls GetTypeId<>() from the
 569// gtest.cc, which is within the Google Test framework.
 570TypeId GetTestTypeId() {
 571  return GetTypeId<Test>();
 572}
 573
 574// The value of GetTestTypeId() as seen from within the Google Test
 575// library.  This is solely for testing GetTestTypeId().
 576extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
 577
 578// This predicate-formatter checks that 'results' contains a test part
 579// failure of the given type and that the failure message contains the
 580// given substring.
 581AssertionResult HasOneFailure(const char* /* results_expr */,
 582                              const char* /* type_expr */,
 583                              const char* /* substr_expr */,
 584                              const TestPartResultArray& results,
 585                              TestPartResult::Type type,
 586                              const char* substr) {
 587  const String expected(type == TestPartResult::kFatalFailure ?
 588                        "1 fatal failure" :
 589                        "1 non-fatal failure");
 590  Message msg;
 591  if (results.size() != 1) {
 592    msg << "Expected: " << expected << "\n"
 593        << "  Actual: " << results.size() << " failures";
 594    for (int i = 0; i < results.size(); i++) {
 595      msg << "\n" << results.GetTestPartResult(i);
 596    }
 597    return AssertionFailure(msg);
 598  }
 599
 600  const TestPartResult& r = results.GetTestPartResult(0);
 601  if (r.type() != type) {
 602    msg << "Expected: " << expected << "\n"
 603        << "  Actual:\n"
 604        << r;
 605    return AssertionFailure(msg);
 606  }
 607
 608  if (strstr(r.message(), substr) == NULL) {
 609    msg << "Expected: " << expected << " containing \""
 610        << substr << "\"\n"
 611        << "  Actual:\n"
 612        << r;
 613    return AssertionFailure(msg);
 614  }
 615
 616  return AssertionSuccess();
 617}
 618
 619// The constructor of SingleFailureChecker remembers where to look up
 620// test part results, what type of failure we expect, and what
 621// substring the failure message should contain.
 622SingleFailureChecker:: SingleFailureChecker(
 623    const TestPartResultArray* results,
 624    TestPartResult::Type type,
 625    const char* substr)
 626    : results_(results),
 627      type_(type),
 628      substr_(substr) {}
 629
 630// The destructor of SingleFailureChecker verifies that the given
 631// TestPartResultArray contains exactly one failure that has the given
 632// type and contains the given substring.  If that's not the case, a
 633// non-fatal failure will be generated.
 634SingleFailureChecker::~SingleFailureChecker() {
 635  EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_.c_str());
 636}
 637
 638DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
 639    UnitTestImpl* unit_test) : unit_test_(unit_test) {}
 640
 641void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
 642    const TestPartResult& result) {
 643  unit_test_->current_test_result()->AddTestPartResult(result);
 644  unit_test_->listeners()->repeater()->OnTestPartResult(result);
 645}
 646
 647DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
 648    UnitTestImpl* unit_test) : unit_test_(unit_test) {}
 649
 650void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
 651    const TestPartResult& result) {
 652  unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
 653}
 654
 655// Returns the global test part result reporter.
 656TestPartResultReporterInterface*
 657UnitTestImpl::GetGlobalTestPartResultReporter() {
 658  internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
 659  return global_test_part_result_repoter_;
 660}
 661
 662// Sets the global test part result reporter.
 663void UnitTestImpl::SetGlobalTestPartResultReporter(
 664    TestPartResultReporterInterface* reporter) {
 665  internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
 666  global_test_part_result_repoter_ = reporter;
 667}
 668
 669// Returns the test part result reporter for the current thread.
 670TestPartResultReporterInterface*
 671UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
 672  return per_thread_test_part_result_reporter_.get();
 673}
 674
 675// Sets the test part result reporter for the current thread.
 676void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
 677    TestPartResultReporterInterface* reporter) {
 678  per_thread_test_part_result_reporter_.set(reporter);
 679}
 680
 681// Gets the number of successful test cases.
 682int UnitTestImpl::successful_test_case_count() const {
 683  return CountIf(test_cases_, TestCasePassed);
 684}
 685
 686// Gets the number of failed test cases.
 687int UnitTestImpl::failed_test_case_count() const {
 688  return CountIf(test_cases_, TestCaseFailed);
 689}
 690
 691// Gets the number of all test cases.
 692int UnitTestImpl::total_test_case_count() const {
 693  return static_cast<int>(test_cases_.size());
 694}
 695
 696// Gets the number of all test cases that contain at least one test
 697// that should run.
 698int UnitTestImpl::test_case_to_run_count() const {
 699  return CountIf(test_cases_, ShouldRunTestCase);
 700}
 701
 702// Gets the number of successful tests.
 703int UnitTestImpl::successful_test_count() const {
 704  return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count);
 705}
 706
 707// Gets the number of failed tests.
 708int UnitTestImpl::failed_test_count() const {
 709  return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count);
 710}
 711
 712// Gets the number of disabled tests.
 713int UnitTestImpl::disabled_test_count() const {
 714  return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count);
 715}
 716
 717// Gets the number of all tests.
 718int UnitTestImpl::total_test_count() const {
 719  return SumOverTestCaseList(test_cases_, &TestCase::total_test_count);
 720}
 721
 722// Gets the number of tests that should run.
 723int UnitTestImpl::test_to_run_count() const {
 724  return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count);
 725}
 726
 727// Returns the current OS stack trace as a String.
 728//
 729// The maximum number of stack frames to be included is specified by
 730// the gtest_stack_trace_depth flag.  The skip_count parameter
 731// specifies the number of top frames to be skipped, which doesn't
 732// count against the number of frames to be included.
 733//
 734// For example, if Foo() calls Bar(), which in turn calls
 735// CurrentOsStackTraceExceptTop(1), Foo() will be included in the
 736// trace but Bar() and CurrentOsStackTraceExceptTop() won't.
 737String UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
 738  (void)skip_count;
 739  return String("");
 740}
 741
 742// Returns the current time in milliseconds.
 743TimeInMillis GetTimeInMillis() {
 744#if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__)
 745  // Difference between 1970-01-01 and 1601-01-01 in milliseconds.
 746  // http://analogous.blogspot.com/2005/04/epoch.html
 747  const TimeInMillis kJavaEpochToWinFileTimeDelta =
 748    static_cast<TimeInMillis>(116444736UL) * 100000UL;
 749  const DWORD kTenthMicrosInMilliSecond = 10000;
 750
 751  SYSTEMTIME now_systime;
 752  FILETIME now_filetime;
 753  ULARGE_INTEGER now_int64;
 754  // TODO(kenton@google.com): Shouldn't this just use
 755  //   GetSystemTimeAsFileTime()?
 756  GetSystemTime(&now_systime);
 757  if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
 758    now_int64.LowPart = now_filetime.dwLowDateTime;
 759    now_int64.HighPart = now_filetime.dwHighDateTime;
 760    now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
 761      kJavaEpochToWinFileTimeDelta;
 762    return now_int64.QuadPart;
 763  }
 764  return 0;
 765#elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_
 766  __timeb64 now;
 767#ifdef _MSC_VER
 768  // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996
 769  // (deprecated function) there.
 770  // TODO(kenton@google.com): Use GetTickCount()?  Or use
 771  //   SystemTimeToFileTime()
 772#pragma warning(push)          // Saves the current warning state.
 773#pragma warning(disable:4996)  // Temporarily disables warning 4996.
 774  _ftime64(&now);
 775#pragma warning(pop)           // Restores the warning state.
 776#else
 777  _ftime64(&now);
 778#endif  // _MSC_VER
 779  return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
 780#elif GTEST_HAS_GETTIMEOFDAY_
 781  struct timeval now;
 782  gettimeofday(&now, NULL);
 783  return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
 784#else
 785#error "Don't know how to get the current time on your system."
 786#endif
 787}
 788
 789// Utilities
 790
 791// class String
 792
 793// Returns the input enclosed in double quotes if it's not NULL;
 794// otherwise returns "(null)".  For example, "\"Hello\"" is returned
 795// for input "Hello".
 796//
 797// This is useful for printing a C string in the syntax of a literal.
 798//
 799// Known issue: escape sequences are not handled yet.
 800String String::ShowCStringQuoted(const char* c_str) {
 801  return c_str ? String::Format("\"%s\"", c_str) : String("(null)");
 802}
 803
 804// Copies at most length characters from str into a newly-allocated
 805// piece of memory of size length+1.  The memory is allocated with new[].
 806// A terminating null byte is written to the memory, and a pointer to it
 807// is returned.  If str is NULL, NULL is returned.
 808static char* CloneString(const char* str, size_t length) {
 809  if (str == NULL) {
 810    return NULL;
 811  } else {
 812    char* const clone = new char[length + 1];
 813    posix::StrNCpy(clone, str, length);
 814    clone[length] = '\0';
 815    return clone;
 816  }
 817}
 818
 819// Clones a 0-terminated C string, allocating memory using new.  The
 820// caller is responsible for deleting[] the return value.  Returns the
 821// cloned string, or NULL if the input is NULL.
 822const char * String::CloneCString(const char* c_str) {
 823  return (c_str == NULL) ?
 824                    NULL : CloneString(c_str, strlen(c_str));
 825}
 826
 827#if GTEST_OS_WINDOWS_MOBILE
 828// Creates a UTF-16 wide string from the given ANSI string, allocating
 829// memory using new. The caller is responsible for deleting the return
 830// value using delete[]. Returns the wide string, or NULL if the
 831// input is NULL.
 832LPCWSTR String::AnsiToUtf16(const char* ansi) {
 833  if (!ansi) return NULL;
 834  const int length = strlen(ansi);
 835  const int unicode_length =
 836      MultiByteToWideChar(CP_ACP, 0, ansi, length,
 837                          NULL, 0);
 838  WCHAR* unicode = new WCHAR[unicode_length + 1];
 839  MultiByteToWideChar(CP_ACP, 0, ansi, length,
 840                      unicode, unicode_length);
 841  unicode[unicode_length] = 0;
 842  return unicode;
 843}
 844
 845// Creates an ANSI string from the given wide string, allocating
 846// memory using new. The caller is responsible for deleting the return
 847// value using delete[]. Returns the ANSI string, or NULL if the
 848// input is NULL.
 849const char* String::Utf16ToAnsi(LPCWSTR utf16_str)  {
 850  if (!utf16_str) return NULL;
 851  const int ansi_length =
 852      WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
 853                          NULL, 0, NULL, NULL);
 854  char* ansi = new char[ansi_length + 1];
 855  WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
 856                      ansi, ansi_length, NULL, NULL);
 857  ansi[ansi_length] = 0;
 858  return ansi;
 859}
 860
 861#endif  // GTEST_OS_WINDOWS_MOBILE
 862
 863// Compares two C strings.  Returns true iff they have the same content.
 864//
 865// Unlike strcmp(), this function can handle NULL argument(s).  A NULL
 866// C string is considered different to any non-NULL C string,
 867// including the empty string.
 868bool String::CStringEquals(const char * lhs, const char * rhs) {
 869  if ( lhs == NULL ) return rhs == NULL;
 870
 871  if ( rhs == NULL ) return false;
 872
 873  return strcmp(lhs, rhs) == 0;
 874}
 875
 876#if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
 877
 878// Converts an array of wide chars to a narrow string using the UTF-8
 879// encoding, and streams the result to the given Message object.
 880static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
 881                                     Message* msg) {
 882  // TODO(wan): consider allowing a testing::String object to
 883  // contain '\0'.  This will make it behave more like std::string,
 884  // and will allow ToUtf8String() to return the correct encoding
 885  // for '\0' s.t. we can get rid of the conditional here (and in
 886  // several other places).
 887  for (size_t i = 0; i != length; ) {  // NOLINT
 888    if (wstr[i] != L'\0') {
 889      *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
 890      while (i != length && wstr[i] != L'\0')
 891        i++;
 892    } else {
 893      *msg << '\0';
 894      i++;
 895    }
 896  }
 897}
 898
 899#endif  // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
 900
 901}  // namespace internal
 902
 903#if GTEST_HAS_STD_WSTRING
 904// Converts the given wide string to a narrow string using the UTF-8
 905// encoding, and streams the result to this Message object.
 906Message& Message::operator <<(const ::std::wstring& wstr) {
 907  internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
 908  return *this;
 909}
 910#endif  // GTEST_HAS_STD_WSTRING
 911
 912#if GTEST_HAS_GLOBAL_WSTRING
 913// Converts the given wide string to a narrow string using the UTF-8
 914// encoding, and streams the result to this Message object.
 915Message& Message::operator <<(const ::wstring& wstr) {
 916  internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
 917  return *this;
 918}
 919#endif  // GTEST_HAS_GLOBAL_WSTRING
 920
 921namespace internal {
 922
 923// Formats a value to be used in a failure message.
 924
 925// For a char value, we print it as a C++ char literal and as an
 926// unsigned integer (both in decimal and in hexadecimal).
 927String FormatForFailureMessage(char ch) {
 928  const unsigned int ch_as_uint = ch;
 929  // A String object cannot contain '\0', so we print "\\0" when ch is
 930  // '\0'.
 931  return String::Format("'%s' (%u, 0x%X)",
 932                        ch ? String::Format("%c", ch).c_str() : "\\0",
 933                        ch_as_uint, ch_as_uint);
 934}
 935
 936// For a wchar_t value, we print it as a C++ wchar_t literal and as an
 937// unsigned integer (both in decimal and in hexidecimal).
 938String FormatForFailureMessage(wchar_t wchar) {
 939  // The C++ standard doesn't specify the exact size of the wchar_t
 940  // type.  It just says that it shall have the same size as another
 941  // integral type, called its underlying type.
 942  //
 943  // Therefore, in order to print a wchar_t value in the numeric form,
 944  // we first convert it to the largest integral type (UInt64) and
 945  // then print the converted value.
 946  //
 947  // We use streaming to print the value as "%llu" doesn't work
 948  // correctly with MSVC 7.1.
 949  const UInt64 wchar_as_uint64 = wchar;
 950  Message msg;
 951  // A String object cannot contain '\0', so we print "\\0" when wchar is
 952  // L'\0'.
 953  char buffer[32];  // CodePointToUtf8 requires a buffer that big.
 954  msg << "L'"
 955      << (wchar ? CodePointToUtf8(static_cast<UInt32>(wchar), buffer) : "\\0")
 956      << "' (" << wchar_as_uint64 << ", 0x" << ::std::setbase(16)
 957      << wchar_as_uint64 << ")";
 958  return msg.GetString();
 959}
 960
 961}  // namespace internal
 962
 963// AssertionResult constructors.
 964// Used in EXPECT_TRUE/FALSE(assertion_result).
 965AssertionResult::AssertionResult(const AssertionResult& other)
 966    : success_(other.success_),
 967      message_(other.message_.get() != NULL ?
 968               new internal::String(*other.message_) :
 969               static_cast<internal::String*>(NULL)) {
 970}
 971
 972// Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
 973AssertionResult AssertionResult::operator!() const {
 974  AssertionResult negation(!success_);
 975  if (message_.get() != NULL)
 976    negation << *message_;
 977  return negation;
 978}
 979
 980// Makes a successful assertion result.
 981AssertionResult AssertionSuccess() {
 982  return AssertionResult(true);
 983}
 984
 985// Makes a failed assertion result.
 986AssertionResult AssertionFailure() {
 987  return AssertionResult(false);
 988}
 989
 990// Makes a failed assertion result with the given failure message.
 991// Deprecated; use AssertionFailure() << message.
 992AssertionResult AssertionFailure(const Message& message) {
 993  return AssertionFailure() << message;
 994}
 995
 996namespace internal {
 997
 998// Constructs and returns the message for an equality assertion
 999// (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
1000//
1001// The first four parameters are the expressions used in the assertion
1002// and their values, as strings.  For example, for ASSERT_EQ(foo, bar)
1003// where foo is 5 and bar is 6, we have:
1004//
1005//   expected_expression: "foo"
1006//   actual_expression:   "bar"
1007//   expected_value:      "5"
1008//   actual_value:        "6"
1009//
1010// The ignoring_case parameter is true iff the assertion is a
1011// *_STRCASEEQ*.  When it's true, the string " (ignoring case)" will
1012// be inserted into the message.
1013AssertionResult EqFailure(const char* expected_expression,
1014                          const char* actual_expression,
1015                          const String& expected_value,
1016                          const String& actual_value,
1017                          bool ignoring_case) {
1018  Message msg;
1019  msg << "Value of: " << actual_expression;
1020  if (actual_value != actual_expression) {
1021    msg << "\n  Actual: " << actual_value;
1022  }
1023
1024  msg << "\nExpected: " << expected_expression;
1025  if (ignoring_case) {
1026    msg << " (ignoring case)";
1027  }
1028  if (expected_value != expected_expression) {
1029    msg << "\nWhich is: " << expected_value;
1030  }
1031
1032  return AssertionFailure(msg);
1033}
1034
1035// Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
1036String GetBoolAssertionFailureMessage(const AssertionResult& assertion_result,
1037                                      const char* expression_text,
1038                                      const char* actual_predicate_value,
1039                                      const char* expected_predicate_value) {
1040  const char* actual_message = assertion_result.message();
1041  Message msg;
1042  msg << "Value of: " << expression_text
1043      << "\n  Actual: " << actual_predicate_value;
1044  if (actual_message[0] != '\0')
1045    msg << " (" << actual_message << ")";
1046  msg << "\nExpected: " << expected_predicate_value;
1047  return msg.GetString();
1048}
1049
1050// Helper function for implementing ASSERT_NEAR.
1051AssertionResult DoubleNearPredFormat(const char* expr1,
1052                                     const char* expr2,
1053                                     const char* abs_error_expr,
1054                                     double val1,
1055                                     double val2,
1056                                     double abs_error) {
1057  const double diff = fabs(val1 - val2);
1058  if (diff <= abs_error) return AssertionSuccess();
1059
1060  // TODO(wan): do not print the value of an expression if it's
1061  // already a literal.
1062  Message msg;
1063  msg << "The difference between " << expr1 << " and " << expr2
1064      << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"
1065      << expr1 << " evaluates to " << val1 << ",\n"
1066      << expr2 << " evaluates to " << val2 << ", and\n"
1067      << abs_error_expr << " evaluates to " << abs_error << ".";
1068  return AssertionFailure(msg);
1069}
1070
1071
1072// Helper template for implementing FloatLE() and DoubleLE().
1073template <typename RawType>
1074AssertionResult FloatingPointLE(const char* expr1,
1075                                const char* expr2,
1076                                RawType val1,
1077                                RawType val2) {
1078  // Returns success if val1 is less than val2,
1079  if (val1 < val2) {
1080    return AssertionSuccess();
1081  }
1082
1083  // or if val1 is almost equal to val2.
1084  const FloatingPoint<RawType> lhs(val1), rhs(val2);
1085  if (lhs.AlmostEquals(rhs)) {
1086    return AssertionSuccess();
1087  }
1088
1089  // Note that the above two checks will both fail if either val1 or
1090  // val2 is NaN, as the IEEE floating-point standard requires that
1091  // any predicate involving a NaN must return false.
1092
1093  StrStream val1_ss;
1094  val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
1095          << val1;
1096
1097  StrStream val2_ss;
1098  val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
1099          << val2;
1100
1101  Message msg;
1102  msg << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
1103      << "  Actual: " << StrStreamToString(&val1_ss) << " vs "
1104      << StrStreamToString(&val2_ss);
1105
1106  return AssertionFailure(msg);
1107}
1108
1109}  // namespace internal
1110
1111// Asserts that val1 is less than, or almost equal to, val2.  Fails
1112// otherwise.  In particular, it fails if either val1 or val2 is NaN.
1113AssertionResult FloatLE(const char* expr1, const char* expr2,
1114                        float val1, float val2) {
1115  return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
1116}
1117
1118// Asserts that val1 is less than, or almost equal to, val2.  Fails
1119// otherwise.  In particular, it fails if either val1 or val2 is NaN.
1120AssertionResult DoubleLE(const char* expr1, const char* expr2,
1121                         double val1, double val2) {
1122  return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
1123}
1124
1125namespace internal {
1126
1127// The helper function for {ASSERT|EXPECT}_EQ with int or enum
1128// arguments.
1129AssertionResult CmpHelperEQ(const char* expected_expression,
1130                            const char* actual_expression,
1131                            BiggestInt expected,
1132                            BiggestInt actual) {
1133  if (expected == actual) {
1134    return AssertionSuccess();
1135  }
1136
1137  return EqFailure(expected_expression,
1138                   actual_expression,
1139                   FormatForComparisonFailureMessage(expected, actual),
1140                   FormatForComparisonFailureMessage(actual, expected),
1141                   false);
1142}
1143
1144// A macro for implementing the helper functions needed to implement
1145// ASSERT_?? and EXPECT_?? with integer or enum arguments.  It is here
1146// just to avoid copy-and-paste of similar code.
1147#define GTEST_IMPL_CMP_HELPER_(op_name, op)\
1148AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
1149                                   BiggestInt val1, BiggestInt val2) {\
1150  if (val1 op val2) {\
1151    return AssertionSuccess();\
1152  } else {\
1153    Message msg;\
1154    msg << "Expected: (" << expr1 << ") " #op " (" << expr2\
1155        << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
1156        << " vs " << FormatForComparisonFailureMessage(val2, val1);\
1157    return AssertionFailure(msg);\
1158  }\
1159}
1160
1161// Implements the helper function for {ASSERT|EXPECT}_NE with int or
1162// enum arguments.
1163GTEST_IMPL_CMP_HELPER_(NE, !=)
1164// Implements the helper function for {ASSERT|EXPECT}_LE with int or
1165// enum arguments.
1166GTEST_IMPL_CMP_HELPER_(LE, <=)
1167// Implements the helper function for {ASSERT|EXPECT}_LT with int or
1168// enum arguments.
1169GTEST_IMPL_CMP_HELPER_(LT, < )
1170// Implements the helper function for {ASSERT|EXPECT}_GE with int or
1171// enum arguments.
1172GTEST_IMPL_CMP_HELPER_(GE, >=)
1173// Implements the helper function for {ASSERT|EXPECT}_GT with int or
1174// enum arguments.
1175GTEST_IMPL_CMP_HELPER_(GT, > )
1176
1177#undef GTEST_IMPL_CMP_HELPER_
1178
1179// The helper function for {ASSERT|EXPECT}_STREQ.
1180AssertionResult CmpHelperSTREQ(const char* expected_expression,
1181                               const char* actual_expression,
1182                               const char* expected,
1183                               const char* actual) {
1184  if (String::CStringEquals(expected, actual)) {
1185    return AssertionSuccess();
1186  }
1187
1188  return EqFailure(expected_expression,
1189                   actual_expression,
1190                   String::ShowCStringQuoted(expected),
1191                   String::ShowCStringQuoted(actual),
1192                   false);
1193}
1194
1195// The helper function for {ASSERT|EXPECT}_STRCASEEQ.
1196AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression,
1197                                   const char* actual_expression,
1198                                   const char* expected,
1199                                   const char* actual) {
1200  if (String::CaseInsensitiveCStringEquals(expected, actual)) {
1201    return AssertionSuccess();
1202  }
1203
1204  return EqFailure(expected_expression,
1205                   actual_expression,
1206                   String::ShowCStringQuoted(expected),
1207                   String::ShowCStringQuoted(actual),
1208                   true);
1209}
1210
1211// The helper function for {ASSERT|EXPECT}_STRNE.
1212AssertionResult CmpHelperSTRNE(const char* s1_expression,
1213                               const char* s2_expression,
1214                               const char* s1,
1215                               const char* s2) {
1216  if (!String::CStringEquals(s1, s2)) {
1217    return AssertionSuccess();
1218  } else {
1219    Message msg;
1220    msg << "Expected: (" << s1_expression << ") != ("
1221        << s2_expression << "), actual: \""
1222        << s1 << "\" vs \"" << s2 << "\"";
1223    return AssertionFailure(msg);
1224  }
1225}
1226
1227// The helper function for {ASSERT|EXPECT}_STRCASENE.
1228AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
1229                                   const char* s2_expression,
1230                                   const char* s1,
1231                                   const char* s2) {
1232  if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
1233    return AssertionSuccess();
1234  } else {
1235    Message msg;
1236    msg << "Expected: (" << s1_expression << ") != ("
1237        << s2_expression << ") (ignoring case), actual: \""
1238        << s1 << "\" vs \"" << s2 << "\"";
1239    return AssertionFailure(msg);
1240  }
1241}
1242
1243}  // namespace internal
1244
1245namespace {
1246
1247// Helper functions for implementing IsSubString() and IsNotSubstring().
1248
1249// This group of overloaded functions return true iff needle is a
1250// substring of haystack.  NULL is considered a substring of itself
1251// only.
1252
1253bool IsSubstringPred(const char* needle, const char* haystack) {
1254  if (needle == NULL || haystack == NULL)
1255    return needle == haystack;
1256
1257  return strstr(haystack, needle) != NULL;
1258}
1259
1260bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
1261  if (needle == NULL || haystack == NULL)
1262    return needle == haystack;
1263
1264  return wcsstr(haystack, needle) != NULL;
1265}
1266
1267// StringType here can be either ::std::string or ::std::wstring.
1268template <typename StringType>
1269bool IsSubstringPred(const StringType& needle,
1270                     const StringType& haystack) {
1271  return haystack.find(needle) != StringType::npos;
1272}
1273
1274// This function implements either IsSubstring() or IsNotSubstring(),
1275// depending on the value of the expected_to_be_substring parameter.
1276// StringType here can be const char*, const wchar_t*, ::std::string,
1277// or ::std::wstring.
1278template <typename StringType>
1279AssertionResult IsSubstringImpl(
1280    bool expected_to_be_substring,
1281    const char* needle_expr, const char* haystack_expr,
1282    const StringType& needle, const StringType& haystack) {
1283  if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
1284    return AssertionSuccess();
1285
1286  const bool is_wide_string = sizeof(needle[0]) > 1;
1287  const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
1288  return AssertionFailure(
1289      Message()
1290      << "Value of: " << needle_expr << "\n"
1291      << "  Actual: " << begin_string_quote << needle << "\"\n"
1292      << "Expected: " << (expected_to_be_substring ? "" : "not ")
1293      << "a substring of " << haystack_expr << "\n"
1294      << "Which is: " << begin_string_quote << haystack << "\"");
1295}
1296
1297}  // namespace
1298
1299// IsSubstring() and IsNotSubstring() check whether needle is a
1300// substring of haystack (NULL is considered a substring of itself
1301// only), and return an appropriate error message when they fail.
1302
1303AssertionResult IsSubstring(
1304    const char* needle_expr, const char* haystack_expr,
1305    const char* needle, const char* haystack) {
1306  return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1307}
1308
1309AssertionResult IsSubstring(
1310    const char* needle_expr, const char* haystack_expr,
1311    const wchar_t* needle, const wchar_t* haystack) {
1312  return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1313}
1314
1315AssertionResult IsNotSubstring(
1316    const char* needle_expr, const char* haystack_expr,
1317    const char* needle, const char* haystack) {
1318  return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1319}
1320
1321AssertionResult IsNotSubstring(
1322    const char* needle_expr, const char* haystack_expr,
1323    const wchar_t* needle, const wchar_t* haystack) {
1324  return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1325}
1326
1327AssertionResult IsSubstring(
1328    const char* needle_expr, const char* haystack_expr,
1329    const ::std::string& needle, const ::std::string& haystack) {
1330  return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1331}
1332
1333AssertionResult IsNotSubstring(
1334    const char* needle_expr, const char* haystack_expr,
1335    const ::std::string& needle, const ::std::string& haystack) {
1336  return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1337}
1338
1339#if GTEST_HAS_STD_WSTRING
1340AssertionResult IsSubstring(
1341    const char* needle_expr, const char* haystack_expr,
1342    const ::std::wstring& needle, const ::std::wstring& haystack) {
1343  return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1344}
1345
1346AssertionResult IsNotSubstring(
1347    const char* needle_expr, const char* haystack_expr,
1348    const ::std::wstring& needle, const ::std::wstring& haystack) {
1349  return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1350}
1351#endif  // GTEST_HAS_STD_WSTRING
1352
1353namespace internal {
1354
1355#if GTEST_OS_WINDOWS
1356
1357namespace {
1358
1359// Helper function for IsHRESULT{SuccessFailure} predicates
1360AssertionResult HRESULTFailureHelper(const char* expr,
1361                                     const char* expected,
1362                                     long hr) {  // NOLINT
1363#if GTEST_OS_WINDOWS_MOBILE
1364  // Windows CE doesn't support FormatMessage.
1365  const char error_text[] = "";
1366#else
1367  // Looks up the human-readable system message for the HRESULT code
1368  // and since we're not passing any params to FormatMessage, we don't
1369  // want inserts expanded.
1370  const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
1371                       FORMAT_MESSAGE_IGNORE_INSERTS;
1372  const DWORD kBufSize = 4096;  // String::Format can't exceed this length.
1373  // Gets the system's human readable message string for this HRESULT.
1374  char error_text[kBufSize] = { '\0' };
1375  DWORD message_length = ::FormatMessageA(kFlags,
1376                                          0,  // no source, we're asking system
1377                                          hr,  // the error
1378                                          0,  // no line width restrictions
1379                                          error_text,  // output buffer
1380                                          kBufSize,  // buf size
1381        

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