media/webrtc/trunk/testing/gtest/src/gtest.cc

changeset 0
6474c204b198
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/media/webrtc/trunk/testing/gtest/src/gtest.cc	Wed Dec 31 06:09:35 2014 +0100
     1.3 @@ -0,0 +1,4947 @@
     1.4 +// Copyright 2005, Google Inc.
     1.5 +// All rights reserved.
     1.6 +//
     1.7 +// Redistribution and use in source and binary forms, with or without
     1.8 +// modification, are permitted provided that the following conditions are
     1.9 +// met:
    1.10 +//
    1.11 +//     * Redistributions of source code must retain the above copyright
    1.12 +// notice, this list of conditions and the following disclaimer.
    1.13 +//     * Redistributions in binary form must reproduce the above
    1.14 +// copyright notice, this list of conditions and the following disclaimer
    1.15 +// in the documentation and/or other materials provided with the
    1.16 +// distribution.
    1.17 +//     * Neither the name of Google Inc. nor the names of its
    1.18 +// contributors may be used to endorse or promote products derived from
    1.19 +// this software without specific prior written permission.
    1.20 +//
    1.21 +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
    1.22 +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
    1.23 +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
    1.24 +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
    1.25 +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
    1.26 +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
    1.27 +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
    1.28 +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
    1.29 +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    1.30 +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
    1.31 +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    1.32 +//
    1.33 +// Author: wan@google.com (Zhanyong Wan)
    1.34 +//
    1.35 +// The Google C++ Testing Framework (Google Test)
    1.36 +
    1.37 +#include "gtest/gtest.h"
    1.38 +#include "gtest/gtest-spi.h"
    1.39 +
    1.40 +#include <ctype.h>
    1.41 +#include <math.h>
    1.42 +#include <stdarg.h>
    1.43 +#include <stdio.h>
    1.44 +#include <stdlib.h>
    1.45 +#include <time.h>
    1.46 +#include <wchar.h>
    1.47 +#include <wctype.h>
    1.48 +
    1.49 +#include <algorithm>
    1.50 +#include <ostream>  // NOLINT
    1.51 +#include <sstream>
    1.52 +#include <vector>
    1.53 +
    1.54 +#if GTEST_OS_LINUX
    1.55 +
    1.56 +// TODO(kenton@google.com): Use autoconf to detect availability of
    1.57 +// gettimeofday().
    1.58 +# define GTEST_HAS_GETTIMEOFDAY_ 1
    1.59 +
    1.60 +# include <fcntl.h>  // NOLINT
    1.61 +# include <limits.h>  // NOLINT
    1.62 +# include <sched.h>  // NOLINT
    1.63 +// Declares vsnprintf().  This header is not available on Windows.
    1.64 +# include <strings.h>  // NOLINT
    1.65 +# include <sys/mman.h>  // NOLINT
    1.66 +# include <sys/time.h>  // NOLINT
    1.67 +# include <unistd.h>  // NOLINT
    1.68 +# include <string>
    1.69 +
    1.70 +#elif GTEST_OS_SYMBIAN
    1.71 +# define GTEST_HAS_GETTIMEOFDAY_ 1
    1.72 +# include <sys/time.h>  // NOLINT
    1.73 +
    1.74 +#elif GTEST_OS_ZOS
    1.75 +# define GTEST_HAS_GETTIMEOFDAY_ 1
    1.76 +# include <sys/time.h>  // NOLINT
    1.77 +
    1.78 +// On z/OS we additionally need strings.h for strcasecmp.
    1.79 +# include <strings.h>  // NOLINT
    1.80 +
    1.81 +#elif GTEST_OS_WINDOWS_MOBILE  // We are on Windows CE.
    1.82 +
    1.83 +# include <windows.h>  // NOLINT
    1.84 +
    1.85 +#elif GTEST_OS_WINDOWS  // We are on Windows proper.
    1.86 +
    1.87 +# include <io.h>  // NOLINT
    1.88 +# include <sys/timeb.h>  // NOLINT
    1.89 +# include <sys/types.h>  // NOLINT
    1.90 +# include <sys/stat.h>  // NOLINT
    1.91 +
    1.92 +# if GTEST_OS_WINDOWS_MINGW
    1.93 +// MinGW has gettimeofday() but not _ftime64().
    1.94 +// TODO(kenton@google.com): Use autoconf to detect availability of
    1.95 +//   gettimeofday().
    1.96 +// TODO(kenton@google.com): There are other ways to get the time on
    1.97 +//   Windows, like GetTickCount() or GetSystemTimeAsFileTime().  MinGW
    1.98 +//   supports these.  consider using them instead.
    1.99 +#  define GTEST_HAS_GETTIMEOFDAY_ 1
   1.100 +#  include <sys/time.h>  // NOLINT
   1.101 +# endif  // GTEST_OS_WINDOWS_MINGW
   1.102 +
   1.103 +// cpplint thinks that the header is already included, so we want to
   1.104 +// silence it.
   1.105 +# include <windows.h>  // NOLINT
   1.106 +
   1.107 +#else
   1.108 +
   1.109 +// Assume other platforms have gettimeofday().
   1.110 +// TODO(kenton@google.com): Use autoconf to detect availability of
   1.111 +//   gettimeofday().
   1.112 +# define GTEST_HAS_GETTIMEOFDAY_ 1
   1.113 +
   1.114 +// cpplint thinks that the header is already included, so we want to
   1.115 +// silence it.
   1.116 +# include <sys/time.h>  // NOLINT
   1.117 +# include <unistd.h>  // NOLINT
   1.118 +
   1.119 +#endif  // GTEST_OS_LINUX
   1.120 +
   1.121 +#if GTEST_HAS_EXCEPTIONS
   1.122 +# include <stdexcept>
   1.123 +#endif
   1.124 +
   1.125 +#if GTEST_CAN_STREAM_RESULTS_
   1.126 +# include <arpa/inet.h>  // NOLINT
   1.127 +# include <netdb.h>  // NOLINT
   1.128 +#endif
   1.129 +
   1.130 +// Indicates that this translation unit is part of Google Test's
   1.131 +// implementation.  It must come before gtest-internal-inl.h is
   1.132 +// included, or there will be a compiler error.  This trick is to
   1.133 +// prevent a user from accidentally including gtest-internal-inl.h in
   1.134 +// his code.
   1.135 +#define GTEST_IMPLEMENTATION_ 1
   1.136 +#include "src/gtest-internal-inl.h"
   1.137 +#undef GTEST_IMPLEMENTATION_
   1.138 +
   1.139 +#if GTEST_OS_WINDOWS
   1.140 +# define vsnprintf _vsnprintf
   1.141 +#endif  // GTEST_OS_WINDOWS
   1.142 +
   1.143 +namespace testing {
   1.144 +
   1.145 +using internal::CountIf;
   1.146 +using internal::ForEach;
   1.147 +using internal::GetElementOr;
   1.148 +using internal::Shuffle;
   1.149 +
   1.150 +// Constants.
   1.151 +
   1.152 +// A test whose test case name or test name matches this filter is
   1.153 +// disabled and not run.
   1.154 +static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
   1.155 +
   1.156 +// A test case whose name matches this filter is considered a death
   1.157 +// test case and will be run before test cases whose name doesn't
   1.158 +// match this filter.
   1.159 +static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*";
   1.160 +
   1.161 +// A test filter that matches everything.
   1.162 +static const char kUniversalFilter[] = "*";
   1.163 +
   1.164 +// The default output file for XML output.
   1.165 +static const char kDefaultOutputFile[] = "test_detail.xml";
   1.166 +
   1.167 +// The environment variable name for the test shard index.
   1.168 +static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
   1.169 +// The environment variable name for the total number of test shards.
   1.170 +static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
   1.171 +// The environment variable name for the test shard status file.
   1.172 +static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
   1.173 +
   1.174 +namespace internal {
   1.175 +
   1.176 +// The text used in failure messages to indicate the start of the
   1.177 +// stack trace.
   1.178 +const char kStackTraceMarker[] = "\nStack trace:\n";
   1.179 +
   1.180 +// g_help_flag is true iff the --help flag or an equivalent form is
   1.181 +// specified on the command line.
   1.182 +bool g_help_flag = false;
   1.183 +
   1.184 +}  // namespace internal
   1.185 +
   1.186 +GTEST_DEFINE_bool_(
   1.187 +    also_run_disabled_tests,
   1.188 +    internal::BoolFromGTestEnv("also_run_disabled_tests", false),
   1.189 +    "Run disabled tests too, in addition to the tests normally being run.");
   1.190 +
   1.191 +GTEST_DEFINE_bool_(
   1.192 +    break_on_failure,
   1.193 +    internal::BoolFromGTestEnv("break_on_failure", false),
   1.194 +    "True iff a failed assertion should be a debugger break-point.");
   1.195 +
   1.196 +GTEST_DEFINE_bool_(
   1.197 +    catch_exceptions,
   1.198 +    internal::BoolFromGTestEnv("catch_exceptions", true),
   1.199 +    "True iff " GTEST_NAME_
   1.200 +    " should catch exceptions and treat them as test failures.");
   1.201 +
   1.202 +GTEST_DEFINE_string_(
   1.203 +    color,
   1.204 +    internal::StringFromGTestEnv("color", "auto"),
   1.205 +    "Whether to use colors in the output.  Valid values: yes, no, "
   1.206 +    "and auto.  'auto' means to use colors if the output is "
   1.207 +    "being sent to a terminal and the TERM environment variable "
   1.208 +    "is set to xterm, xterm-color, xterm-256color, linux or cygwin.");
   1.209 +
   1.210 +GTEST_DEFINE_string_(
   1.211 +    filter,
   1.212 +    internal::StringFromGTestEnv("filter", kUniversalFilter),
   1.213 +    "A colon-separated list of glob (not regex) patterns "
   1.214 +    "for filtering the tests to run, optionally followed by a "
   1.215 +    "'-' and a : separated list of negative patterns (tests to "
   1.216 +    "exclude).  A test is run if it matches one of the positive "
   1.217 +    "patterns and does not match any of the negative patterns.");
   1.218 +
   1.219 +GTEST_DEFINE_bool_(list_tests, false,
   1.220 +                   "List all tests without running them.");
   1.221 +
   1.222 +GTEST_DEFINE_string_(
   1.223 +    output,
   1.224 +    internal::StringFromGTestEnv("output", ""),
   1.225 +    "A format (currently must be \"xml\"), optionally followed "
   1.226 +    "by a colon and an output file name or directory. A directory "
   1.227 +    "is indicated by a trailing pathname separator. "
   1.228 +    "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
   1.229 +    "If a directory is specified, output files will be created "
   1.230 +    "within that directory, with file-names based on the test "
   1.231 +    "executable's name and, if necessary, made unique by adding "
   1.232 +    "digits.");
   1.233 +
   1.234 +GTEST_DEFINE_bool_(
   1.235 +    print_time,
   1.236 +    internal::BoolFromGTestEnv("print_time", true),
   1.237 +    "True iff " GTEST_NAME_
   1.238 +    " should display elapsed time in text output.");
   1.239 +
   1.240 +GTEST_DEFINE_int32_(
   1.241 +    random_seed,
   1.242 +    internal::Int32FromGTestEnv("random_seed", 0),
   1.243 +    "Random number seed to use when shuffling test orders.  Must be in range "
   1.244 +    "[1, 99999], or 0 to use a seed based on the current time.");
   1.245 +
   1.246 +GTEST_DEFINE_int32_(
   1.247 +    repeat,
   1.248 +    internal::Int32FromGTestEnv("repeat", 1),
   1.249 +    "How many times to repeat each test.  Specify a negative number "
   1.250 +    "for repeating forever.  Useful for shaking out flaky tests.");
   1.251 +
   1.252 +GTEST_DEFINE_bool_(
   1.253 +    show_internal_stack_frames, false,
   1.254 +    "True iff " GTEST_NAME_ " should include internal stack frames when "
   1.255 +    "printing test failure stack traces.");
   1.256 +
   1.257 +GTEST_DEFINE_bool_(
   1.258 +    shuffle,
   1.259 +    internal::BoolFromGTestEnv("shuffle", false),
   1.260 +    "True iff " GTEST_NAME_
   1.261 +    " should randomize tests' order on every run.");
   1.262 +
   1.263 +GTEST_DEFINE_int32_(
   1.264 +    stack_trace_depth,
   1.265 +    internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
   1.266 +    "The maximum number of stack frames to print when an "
   1.267 +    "assertion fails.  The valid range is 0 through 100, inclusive.");
   1.268 +
   1.269 +GTEST_DEFINE_string_(
   1.270 +    stream_result_to,
   1.271 +    internal::StringFromGTestEnv("stream_result_to", ""),
   1.272 +    "This flag specifies the host name and the port number on which to stream "
   1.273 +    "test results. Example: \"localhost:555\". The flag is effective only on "
   1.274 +    "Linux.");
   1.275 +
   1.276 +GTEST_DEFINE_bool_(
   1.277 +    throw_on_failure,
   1.278 +    internal::BoolFromGTestEnv("throw_on_failure", false),
   1.279 +    "When this flag is specified, a failed assertion will throw an exception "
   1.280 +    "if exceptions are enabled or exit the program with a non-zero code "
   1.281 +    "otherwise.");
   1.282 +
   1.283 +namespace internal {
   1.284 +
   1.285 +// Generates a random number from [0, range), using a Linear
   1.286 +// Congruential Generator (LCG).  Crashes if 'range' is 0 or greater
   1.287 +// than kMaxRange.
   1.288 +UInt32 Random::Generate(UInt32 range) {
   1.289 +  // These constants are the same as are used in glibc's rand(3).
   1.290 +  state_ = (1103515245U*state_ + 12345U) % kMaxRange;
   1.291 +
   1.292 +  GTEST_CHECK_(range > 0)
   1.293 +      << "Cannot generate a number in the range [0, 0).";
   1.294 +  GTEST_CHECK_(range <= kMaxRange)
   1.295 +      << "Generation of a number in [0, " << range << ") was requested, "
   1.296 +      << "but this can only generate numbers in [0, " << kMaxRange << ").";
   1.297 +
   1.298 +  // Converting via modulus introduces a bit of downward bias, but
   1.299 +  // it's simple, and a linear congruential generator isn't too good
   1.300 +  // to begin with.
   1.301 +  return state_ % range;
   1.302 +}
   1.303 +
   1.304 +// GTestIsInitialized() returns true iff the user has initialized
   1.305 +// Google Test.  Useful for catching the user mistake of not initializing
   1.306 +// Google Test before calling RUN_ALL_TESTS().
   1.307 +//
   1.308 +// A user must call testing::InitGoogleTest() to initialize Google
   1.309 +// Test.  g_init_gtest_count is set to the number of times
   1.310 +// InitGoogleTest() has been called.  We don't protect this variable
   1.311 +// under a mutex as it is only accessed in the main thread.
   1.312 +GTEST_API_ int g_init_gtest_count = 0;
   1.313 +static bool GTestIsInitialized() { return g_init_gtest_count != 0; }
   1.314 +
   1.315 +// Iterates over a vector of TestCases, keeping a running sum of the
   1.316 +// results of calling a given int-returning method on each.
   1.317 +// Returns the sum.
   1.318 +static int SumOverTestCaseList(const std::vector<TestCase*>& case_list,
   1.319 +                               int (TestCase::*method)() const) {
   1.320 +  int sum = 0;
   1.321 +  for (size_t i = 0; i < case_list.size(); i++) {
   1.322 +    sum += (case_list[i]->*method)();
   1.323 +  }
   1.324 +  return sum;
   1.325 +}
   1.326 +
   1.327 +// Returns true iff the test case passed.
   1.328 +static bool TestCasePassed(const TestCase* test_case) {
   1.329 +  return test_case->should_run() && test_case->Passed();
   1.330 +}
   1.331 +
   1.332 +// Returns true iff the test case failed.
   1.333 +static bool TestCaseFailed(const TestCase* test_case) {
   1.334 +  return test_case->should_run() && test_case->Failed();
   1.335 +}
   1.336 +
   1.337 +// Returns true iff test_case contains at least one test that should
   1.338 +// run.
   1.339 +static bool ShouldRunTestCase(const TestCase* test_case) {
   1.340 +  return test_case->should_run();
   1.341 +}
   1.342 +
   1.343 +// AssertHelper constructor.
   1.344 +AssertHelper::AssertHelper(TestPartResult::Type type,
   1.345 +                           const char* file,
   1.346 +                           int line,
   1.347 +                           const char* message)
   1.348 +    : data_(new AssertHelperData(type, file, line, message)) {
   1.349 +}
   1.350 +
   1.351 +AssertHelper::~AssertHelper() {
   1.352 +  delete data_;
   1.353 +}
   1.354 +
   1.355 +// Message assignment, for assertion streaming support.
   1.356 +void AssertHelper::operator=(const Message& message) const {
   1.357 +  UnitTest::GetInstance()->
   1.358 +    AddTestPartResult(data_->type, data_->file, data_->line,
   1.359 +                      AppendUserMessage(data_->message, message),
   1.360 +                      UnitTest::GetInstance()->impl()
   1.361 +                      ->CurrentOsStackTraceExceptTop(1)
   1.362 +                      // Skips the stack frame for this function itself.
   1.363 +                      );  // NOLINT
   1.364 +}
   1.365 +
   1.366 +// Mutex for linked pointers.
   1.367 +GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex);
   1.368 +
   1.369 +// Application pathname gotten in InitGoogleTest.
   1.370 +String g_executable_path;
   1.371 +
   1.372 +// Returns the current application's name, removing directory path if that
   1.373 +// is present.
   1.374 +FilePath GetCurrentExecutableName() {
   1.375 +  FilePath result;
   1.376 +
   1.377 +#if GTEST_OS_WINDOWS
   1.378 +  result.Set(FilePath(g_executable_path).RemoveExtension("exe"));
   1.379 +#else
   1.380 +  result.Set(FilePath(g_executable_path));
   1.381 +#endif  // GTEST_OS_WINDOWS
   1.382 +
   1.383 +  return result.RemoveDirectoryName();
   1.384 +}
   1.385 +
   1.386 +// Functions for processing the gtest_output flag.
   1.387 +
   1.388 +// Returns the output format, or "" for normal printed output.
   1.389 +String UnitTestOptions::GetOutputFormat() {
   1.390 +  const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
   1.391 +  if (gtest_output_flag == NULL) return String("");
   1.392 +
   1.393 +  const char* const colon = strchr(gtest_output_flag, ':');
   1.394 +  return (colon == NULL) ?
   1.395 +      String(gtest_output_flag) :
   1.396 +      String(gtest_output_flag, colon - gtest_output_flag);
   1.397 +}
   1.398 +
   1.399 +// Returns the name of the requested output file, or the default if none
   1.400 +// was explicitly specified.
   1.401 +String UnitTestOptions::GetAbsolutePathToOutputFile() {
   1.402 +  const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
   1.403 +  if (gtest_output_flag == NULL)
   1.404 +    return String("");
   1.405 +
   1.406 +  const char* const colon = strchr(gtest_output_flag, ':');
   1.407 +  if (colon == NULL)
   1.408 +    return String(internal::FilePath::ConcatPaths(
   1.409 +               internal::FilePath(
   1.410 +                   UnitTest::GetInstance()->original_working_dir()),
   1.411 +               internal::FilePath(kDefaultOutputFile)).ToString() );
   1.412 +
   1.413 +  internal::FilePath output_name(colon + 1);
   1.414 +  if (!output_name.IsAbsolutePath())
   1.415 +    // TODO(wan@google.com): on Windows \some\path is not an absolute
   1.416 +    // path (as its meaning depends on the current drive), yet the
   1.417 +    // following logic for turning it into an absolute path is wrong.
   1.418 +    // Fix it.
   1.419 +    output_name = internal::FilePath::ConcatPaths(
   1.420 +        internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
   1.421 +        internal::FilePath(colon + 1));
   1.422 +
   1.423 +  if (!output_name.IsDirectory())
   1.424 +    return output_name.ToString();
   1.425 +
   1.426 +  internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
   1.427 +      output_name, internal::GetCurrentExecutableName(),
   1.428 +      GetOutputFormat().c_str()));
   1.429 +  return result.ToString();
   1.430 +}
   1.431 +
   1.432 +// Returns true iff the wildcard pattern matches the string.  The
   1.433 +// first ':' or '\0' character in pattern marks the end of it.
   1.434 +//
   1.435 +// This recursive algorithm isn't very efficient, but is clear and
   1.436 +// works well enough for matching test names, which are short.
   1.437 +bool UnitTestOptions::PatternMatchesString(const char *pattern,
   1.438 +                                           const char *str) {
   1.439 +  switch (*pattern) {
   1.440 +    case '\0':
   1.441 +    case ':':  // Either ':' or '\0' marks the end of the pattern.
   1.442 +      return *str == '\0';
   1.443 +    case '?':  // Matches any single character.
   1.444 +      return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);
   1.445 +    case '*':  // Matches any string (possibly empty) of characters.
   1.446 +      return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||
   1.447 +          PatternMatchesString(pattern + 1, str);
   1.448 +    default:  // Non-special character.  Matches itself.
   1.449 +      return *pattern == *str &&
   1.450 +          PatternMatchesString(pattern + 1, str + 1);
   1.451 +  }
   1.452 +}
   1.453 +
   1.454 +bool UnitTestOptions::MatchesFilter(const String& name, const char* filter) {
   1.455 +  const char *cur_pattern = filter;
   1.456 +  for (;;) {
   1.457 +    if (PatternMatchesString(cur_pattern, name.c_str())) {
   1.458 +      return true;
   1.459 +    }
   1.460 +
   1.461 +    // Finds the next pattern in the filter.
   1.462 +    cur_pattern = strchr(cur_pattern, ':');
   1.463 +
   1.464 +    // Returns if no more pattern can be found.
   1.465 +    if (cur_pattern == NULL) {
   1.466 +      return false;
   1.467 +    }
   1.468 +
   1.469 +    // Skips the pattern separater (the ':' character).
   1.470 +    cur_pattern++;
   1.471 +  }
   1.472 +}
   1.473 +
   1.474 +// TODO(keithray): move String function implementations to gtest-string.cc.
   1.475 +
   1.476 +// Returns true iff the user-specified filter matches the test case
   1.477 +// name and the test name.
   1.478 +bool UnitTestOptions::FilterMatchesTest(const String &test_case_name,
   1.479 +                                        const String &test_name) {
   1.480 +  const String& full_name = String::Format("%s.%s",
   1.481 +                                           test_case_name.c_str(),
   1.482 +                                           test_name.c_str());
   1.483 +
   1.484 +  // Split --gtest_filter at '-', if there is one, to separate into
   1.485 +  // positive filter and negative filter portions
   1.486 +  const char* const p = GTEST_FLAG(filter).c_str();
   1.487 +  const char* const dash = strchr(p, '-');
   1.488 +  String positive;
   1.489 +  String negative;
   1.490 +  if (dash == NULL) {
   1.491 +    positive = GTEST_FLAG(filter).c_str();  // Whole string is a positive filter
   1.492 +    negative = String("");
   1.493 +  } else {
   1.494 +    positive = String(p, dash - p);  // Everything up to the dash
   1.495 +    negative = String(dash+1);       // Everything after the dash
   1.496 +    if (positive.empty()) {
   1.497 +      // Treat '-test1' as the same as '*-test1'
   1.498 +      positive = kUniversalFilter;
   1.499 +    }
   1.500 +  }
   1.501 +
   1.502 +  // A filter is a colon-separated list of patterns.  It matches a
   1.503 +  // test if any pattern in it matches the test.
   1.504 +  return (MatchesFilter(full_name, positive.c_str()) &&
   1.505 +          !MatchesFilter(full_name, negative.c_str()));
   1.506 +}
   1.507 +
   1.508 +#if GTEST_HAS_SEH
   1.509 +// Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
   1.510 +// given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
   1.511 +// This function is useful as an __except condition.
   1.512 +int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
   1.513 +  // Google Test should handle a SEH exception if:
   1.514 +  //   1. the user wants it to, AND
   1.515 +  //   2. this is not a breakpoint exception, AND
   1.516 +  //   3. this is not a C++ exception (VC++ implements them via SEH,
   1.517 +  //      apparently).
   1.518 +  //
   1.519 +  // SEH exception code for C++ exceptions.
   1.520 +  // (see http://support.microsoft.com/kb/185294 for more information).
   1.521 +  const DWORD kCxxExceptionCode = 0xe06d7363;
   1.522 +
   1.523 +  bool should_handle = true;
   1.524 +
   1.525 +  if (!GTEST_FLAG(catch_exceptions))
   1.526 +    should_handle = false;
   1.527 +  else if (exception_code == EXCEPTION_BREAKPOINT)
   1.528 +    should_handle = false;
   1.529 +  else if (exception_code == kCxxExceptionCode)
   1.530 +    should_handle = false;
   1.531 +
   1.532 +  return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
   1.533 +}
   1.534 +#endif  // GTEST_HAS_SEH
   1.535 +
   1.536 +}  // namespace internal
   1.537 +
   1.538 +// The c'tor sets this object as the test part result reporter used by
   1.539 +// Google Test.  The 'result' parameter specifies where to report the
   1.540 +// results. Intercepts only failures from the current thread.
   1.541 +ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
   1.542 +    TestPartResultArray* result)
   1.543 +    : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
   1.544 +      result_(result) {
   1.545 +  Init();
   1.546 +}
   1.547 +
   1.548 +// The c'tor sets this object as the test part result reporter used by
   1.549 +// Google Test.  The 'result' parameter specifies where to report the
   1.550 +// results.
   1.551 +ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
   1.552 +    InterceptMode intercept_mode, TestPartResultArray* result)
   1.553 +    : intercept_mode_(intercept_mode),
   1.554 +      result_(result) {
   1.555 +  Init();
   1.556 +}
   1.557 +
   1.558 +void ScopedFakeTestPartResultReporter::Init() {
   1.559 +  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
   1.560 +  if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
   1.561 +    old_reporter_ = impl->GetGlobalTestPartResultReporter();
   1.562 +    impl->SetGlobalTestPartResultReporter(this);
   1.563 +  } else {
   1.564 +    old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
   1.565 +    impl->SetTestPartResultReporterForCurrentThread(this);
   1.566 +  }
   1.567 +}
   1.568 +
   1.569 +// The d'tor restores the test part result reporter used by Google Test
   1.570 +// before.
   1.571 +ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
   1.572 +  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
   1.573 +  if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
   1.574 +    impl->SetGlobalTestPartResultReporter(old_reporter_);
   1.575 +  } else {
   1.576 +    impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
   1.577 +  }
   1.578 +}
   1.579 +
   1.580 +// Increments the test part result count and remembers the result.
   1.581 +// This method is from the TestPartResultReporterInterface interface.
   1.582 +void ScopedFakeTestPartResultReporter::ReportTestPartResult(
   1.583 +    const TestPartResult& result) {
   1.584 +  result_->Append(result);
   1.585 +}
   1.586 +
   1.587 +namespace internal {
   1.588 +
   1.589 +// Returns the type ID of ::testing::Test.  We should always call this
   1.590 +// instead of GetTypeId< ::testing::Test>() to get the type ID of
   1.591 +// testing::Test.  This is to work around a suspected linker bug when
   1.592 +// using Google Test as a framework on Mac OS X.  The bug causes
   1.593 +// GetTypeId< ::testing::Test>() to return different values depending
   1.594 +// on whether the call is from the Google Test framework itself or
   1.595 +// from user test code.  GetTestTypeId() is guaranteed to always
   1.596 +// return the same value, as it always calls GetTypeId<>() from the
   1.597 +// gtest.cc, which is within the Google Test framework.
   1.598 +TypeId GetTestTypeId() {
   1.599 +  return GetTypeId<Test>();
   1.600 +}
   1.601 +
   1.602 +// The value of GetTestTypeId() as seen from within the Google Test
   1.603 +// library.  This is solely for testing GetTestTypeId().
   1.604 +extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
   1.605 +
   1.606 +// This predicate-formatter checks that 'results' contains a test part
   1.607 +// failure of the given type and that the failure message contains the
   1.608 +// given substring.
   1.609 +AssertionResult HasOneFailure(const char* /* results_expr */,
   1.610 +                              const char* /* type_expr */,
   1.611 +                              const char* /* substr_expr */,
   1.612 +                              const TestPartResultArray& results,
   1.613 +                              TestPartResult::Type type,
   1.614 +                              const string& substr) {
   1.615 +  const String expected(type == TestPartResult::kFatalFailure ?
   1.616 +                        "1 fatal failure" :
   1.617 +                        "1 non-fatal failure");
   1.618 +  Message msg;
   1.619 +  if (results.size() != 1) {
   1.620 +    msg << "Expected: " << expected << "\n"
   1.621 +        << "  Actual: " << results.size() << " failures";
   1.622 +    for (int i = 0; i < results.size(); i++) {
   1.623 +      msg << "\n" << results.GetTestPartResult(i);
   1.624 +    }
   1.625 +    return AssertionFailure() << msg;
   1.626 +  }
   1.627 +
   1.628 +  const TestPartResult& r = results.GetTestPartResult(0);
   1.629 +  if (r.type() != type) {
   1.630 +    return AssertionFailure() << "Expected: " << expected << "\n"
   1.631 +                              << "  Actual:\n"
   1.632 +                              << r;
   1.633 +  }
   1.634 +
   1.635 +  if (strstr(r.message(), substr.c_str()) == NULL) {
   1.636 +    return AssertionFailure() << "Expected: " << expected << " containing \""
   1.637 +                              << substr << "\"\n"
   1.638 +                              << "  Actual:\n"
   1.639 +                              << r;
   1.640 +  }
   1.641 +
   1.642 +  return AssertionSuccess();
   1.643 +}
   1.644 +
   1.645 +// The constructor of SingleFailureChecker remembers where to look up
   1.646 +// test part results, what type of failure we expect, and what
   1.647 +// substring the failure message should contain.
   1.648 +SingleFailureChecker:: SingleFailureChecker(
   1.649 +    const TestPartResultArray* results,
   1.650 +    TestPartResult::Type type,
   1.651 +    const string& substr)
   1.652 +    : results_(results),
   1.653 +      type_(type),
   1.654 +      substr_(substr) {}
   1.655 +
   1.656 +// The destructor of SingleFailureChecker verifies that the given
   1.657 +// TestPartResultArray contains exactly one failure that has the given
   1.658 +// type and contains the given substring.  If that's not the case, a
   1.659 +// non-fatal failure will be generated.
   1.660 +SingleFailureChecker::~SingleFailureChecker() {
   1.661 +  EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_);
   1.662 +}
   1.663 +
   1.664 +DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
   1.665 +    UnitTestImpl* unit_test) : unit_test_(unit_test) {}
   1.666 +
   1.667 +void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
   1.668 +    const TestPartResult& result) {
   1.669 +  unit_test_->current_test_result()->AddTestPartResult(result);
   1.670 +  unit_test_->listeners()->repeater()->OnTestPartResult(result);
   1.671 +}
   1.672 +
   1.673 +DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
   1.674 +    UnitTestImpl* unit_test) : unit_test_(unit_test) {}
   1.675 +
   1.676 +void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
   1.677 +    const TestPartResult& result) {
   1.678 +  unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
   1.679 +}
   1.680 +
   1.681 +// Returns the global test part result reporter.
   1.682 +TestPartResultReporterInterface*
   1.683 +UnitTestImpl::GetGlobalTestPartResultReporter() {
   1.684 +  internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
   1.685 +  return global_test_part_result_repoter_;
   1.686 +}
   1.687 +
   1.688 +// Sets the global test part result reporter.
   1.689 +void UnitTestImpl::SetGlobalTestPartResultReporter(
   1.690 +    TestPartResultReporterInterface* reporter) {
   1.691 +  internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
   1.692 +  global_test_part_result_repoter_ = reporter;
   1.693 +}
   1.694 +
   1.695 +// Returns the test part result reporter for the current thread.
   1.696 +TestPartResultReporterInterface*
   1.697 +UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
   1.698 +  return per_thread_test_part_result_reporter_.get();
   1.699 +}
   1.700 +
   1.701 +// Sets the test part result reporter for the current thread.
   1.702 +void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
   1.703 +    TestPartResultReporterInterface* reporter) {
   1.704 +  per_thread_test_part_result_reporter_.set(reporter);
   1.705 +}
   1.706 +
   1.707 +// Gets the number of successful test cases.
   1.708 +int UnitTestImpl::successful_test_case_count() const {
   1.709 +  return CountIf(test_cases_, TestCasePassed);
   1.710 +}
   1.711 +
   1.712 +// Gets the number of failed test cases.
   1.713 +int UnitTestImpl::failed_test_case_count() const {
   1.714 +  return CountIf(test_cases_, TestCaseFailed);
   1.715 +}
   1.716 +
   1.717 +// Gets the number of all test cases.
   1.718 +int UnitTestImpl::total_test_case_count() const {
   1.719 +  return static_cast<int>(test_cases_.size());
   1.720 +}
   1.721 +
   1.722 +// Gets the number of all test cases that contain at least one test
   1.723 +// that should run.
   1.724 +int UnitTestImpl::test_case_to_run_count() const {
   1.725 +  return CountIf(test_cases_, ShouldRunTestCase);
   1.726 +}
   1.727 +
   1.728 +// Gets the number of successful tests.
   1.729 +int UnitTestImpl::successful_test_count() const {
   1.730 +  return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count);
   1.731 +}
   1.732 +
   1.733 +// Gets the number of failed tests.
   1.734 +int UnitTestImpl::failed_test_count() const {
   1.735 +  return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count);
   1.736 +}
   1.737 +
   1.738 +// Gets the number of disabled tests.
   1.739 +int UnitTestImpl::disabled_test_count() const {
   1.740 +  return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count);
   1.741 +}
   1.742 +
   1.743 +// Gets the number of all tests.
   1.744 +int UnitTestImpl::total_test_count() const {
   1.745 +  return SumOverTestCaseList(test_cases_, &TestCase::total_test_count);
   1.746 +}
   1.747 +
   1.748 +// Gets the number of tests that should run.
   1.749 +int UnitTestImpl::test_to_run_count() const {
   1.750 +  return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count);
   1.751 +}
   1.752 +
   1.753 +// Returns the current OS stack trace as a String.
   1.754 +//
   1.755 +// The maximum number of stack frames to be included is specified by
   1.756 +// the gtest_stack_trace_depth flag.  The skip_count parameter
   1.757 +// specifies the number of top frames to be skipped, which doesn't
   1.758 +// count against the number of frames to be included.
   1.759 +//
   1.760 +// For example, if Foo() calls Bar(), which in turn calls
   1.761 +// CurrentOsStackTraceExceptTop(1), Foo() will be included in the
   1.762 +// trace but Bar() and CurrentOsStackTraceExceptTop() won't.
   1.763 +String UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
   1.764 +  (void)skip_count;
   1.765 +  return String("");
   1.766 +}
   1.767 +
   1.768 +// Returns the current time in milliseconds.
   1.769 +TimeInMillis GetTimeInMillis() {
   1.770 +#if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__)
   1.771 +  // Difference between 1970-01-01 and 1601-01-01 in milliseconds.
   1.772 +  // http://analogous.blogspot.com/2005/04/epoch.html
   1.773 +  const TimeInMillis kJavaEpochToWinFileTimeDelta =
   1.774 +    static_cast<TimeInMillis>(116444736UL) * 100000UL;
   1.775 +  const DWORD kTenthMicrosInMilliSecond = 10000;
   1.776 +
   1.777 +  SYSTEMTIME now_systime;
   1.778 +  FILETIME now_filetime;
   1.779 +  ULARGE_INTEGER now_int64;
   1.780 +  // TODO(kenton@google.com): Shouldn't this just use
   1.781 +  //   GetSystemTimeAsFileTime()?
   1.782 +  GetSystemTime(&now_systime);
   1.783 +  if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
   1.784 +    now_int64.LowPart = now_filetime.dwLowDateTime;
   1.785 +    now_int64.HighPart = now_filetime.dwHighDateTime;
   1.786 +    now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
   1.787 +      kJavaEpochToWinFileTimeDelta;
   1.788 +    return now_int64.QuadPart;
   1.789 +  }
   1.790 +  return 0;
   1.791 +#elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_
   1.792 +  __timeb64 now;
   1.793 +
   1.794 +# ifdef _MSC_VER
   1.795 +
   1.796 +  // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996
   1.797 +  // (deprecated function) there.
   1.798 +  // TODO(kenton@google.com): Use GetTickCount()?  Or use
   1.799 +  //   SystemTimeToFileTime()
   1.800 +#  pragma warning(push)          // Saves the current warning state.
   1.801 +#  pragma warning(disable:4996)  // Temporarily disables warning 4996.
   1.802 +  _ftime64(&now);
   1.803 +#  pragma warning(pop)           // Restores the warning state.
   1.804 +# else
   1.805 +
   1.806 +  _ftime64(&now);
   1.807 +
   1.808 +# endif  // _MSC_VER
   1.809 +
   1.810 +  return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
   1.811 +#elif GTEST_HAS_GETTIMEOFDAY_
   1.812 +  struct timeval now;
   1.813 +  gettimeofday(&now, NULL);
   1.814 +  return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
   1.815 +#else
   1.816 +# error "Don't know how to get the current time on your system."
   1.817 +#endif
   1.818 +}
   1.819 +
   1.820 +// Utilities
   1.821 +
   1.822 +// class String
   1.823 +
   1.824 +// Copies at most length characters from str into a newly-allocated
   1.825 +// piece of memory of size length+1.  The memory is allocated with new[].
   1.826 +// A terminating null byte is written to the memory, and a pointer to it
   1.827 +// is returned.  If str is NULL, NULL is returned.
   1.828 +static char* CloneString(const char* str, size_t length) {
   1.829 +  if (str == NULL) {
   1.830 +    return NULL;
   1.831 +  } else {
   1.832 +    char* const clone = new char[length + 1];
   1.833 +    posix::StrNCpy(clone, str, length);
   1.834 +    clone[length] = '\0';
   1.835 +    return clone;
   1.836 +  }
   1.837 +}
   1.838 +
   1.839 +// Clones a 0-terminated C string, allocating memory using new.  The
   1.840 +// caller is responsible for deleting[] the return value.  Returns the
   1.841 +// cloned string, or NULL if the input is NULL.
   1.842 +const char * String::CloneCString(const char* c_str) {
   1.843 +  return (c_str == NULL) ?
   1.844 +                    NULL : CloneString(c_str, strlen(c_str));
   1.845 +}
   1.846 +
   1.847 +#if GTEST_OS_WINDOWS_MOBILE
   1.848 +// Creates a UTF-16 wide string from the given ANSI string, allocating
   1.849 +// memory using new. The caller is responsible for deleting the return
   1.850 +// value using delete[]. Returns the wide string, or NULL if the
   1.851 +// input is NULL.
   1.852 +LPCWSTR String::AnsiToUtf16(const char* ansi) {
   1.853 +  if (!ansi) return NULL;
   1.854 +  const int length = strlen(ansi);
   1.855 +  const int unicode_length =
   1.856 +      MultiByteToWideChar(CP_ACP, 0, ansi, length,
   1.857 +                          NULL, 0);
   1.858 +  WCHAR* unicode = new WCHAR[unicode_length + 1];
   1.859 +  MultiByteToWideChar(CP_ACP, 0, ansi, length,
   1.860 +                      unicode, unicode_length);
   1.861 +  unicode[unicode_length] = 0;
   1.862 +  return unicode;
   1.863 +}
   1.864 +
   1.865 +// Creates an ANSI string from the given wide string, allocating
   1.866 +// memory using new. The caller is responsible for deleting the return
   1.867 +// value using delete[]. Returns the ANSI string, or NULL if the
   1.868 +// input is NULL.
   1.869 +const char* String::Utf16ToAnsi(LPCWSTR utf16_str)  {
   1.870 +  if (!utf16_str) return NULL;
   1.871 +  const int ansi_length =
   1.872 +      WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
   1.873 +                          NULL, 0, NULL, NULL);
   1.874 +  char* ansi = new char[ansi_length + 1];
   1.875 +  WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
   1.876 +                      ansi, ansi_length, NULL, NULL);
   1.877 +  ansi[ansi_length] = 0;
   1.878 +  return ansi;
   1.879 +}
   1.880 +
   1.881 +#endif  // GTEST_OS_WINDOWS_MOBILE
   1.882 +
   1.883 +// Compares two C strings.  Returns true iff they have the same content.
   1.884 +//
   1.885 +// Unlike strcmp(), this function can handle NULL argument(s).  A NULL
   1.886 +// C string is considered different to any non-NULL C string,
   1.887 +// including the empty string.
   1.888 +bool String::CStringEquals(const char * lhs, const char * rhs) {
   1.889 +  if ( lhs == NULL ) return rhs == NULL;
   1.890 +
   1.891 +  if ( rhs == NULL ) return false;
   1.892 +
   1.893 +  return strcmp(lhs, rhs) == 0;
   1.894 +}
   1.895 +
   1.896 +#if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
   1.897 +
   1.898 +// Converts an array of wide chars to a narrow string using the UTF-8
   1.899 +// encoding, and streams the result to the given Message object.
   1.900 +static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
   1.901 +                                     Message* msg) {
   1.902 +  // TODO(wan): consider allowing a testing::String object to
   1.903 +  // contain '\0'.  This will make it behave more like std::string,
   1.904 +  // and will allow ToUtf8String() to return the correct encoding
   1.905 +  // for '\0' s.t. we can get rid of the conditional here (and in
   1.906 +  // several other places).
   1.907 +  for (size_t i = 0; i != length; ) {  // NOLINT
   1.908 +    if (wstr[i] != L'\0') {
   1.909 +      *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
   1.910 +      while (i != length && wstr[i] != L'\0')
   1.911 +        i++;
   1.912 +    } else {
   1.913 +      *msg << '\0';
   1.914 +      i++;
   1.915 +    }
   1.916 +  }
   1.917 +}
   1.918 +
   1.919 +#endif  // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
   1.920 +
   1.921 +}  // namespace internal
   1.922 +
   1.923 +#if GTEST_HAS_STD_WSTRING
   1.924 +// Converts the given wide string to a narrow string using the UTF-8
   1.925 +// encoding, and streams the result to this Message object.
   1.926 +Message& Message::operator <<(const ::std::wstring& wstr) {
   1.927 +  internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
   1.928 +  return *this;
   1.929 +}
   1.930 +#endif  // GTEST_HAS_STD_WSTRING
   1.931 +
   1.932 +#if GTEST_HAS_GLOBAL_WSTRING
   1.933 +// Converts the given wide string to a narrow string using the UTF-8
   1.934 +// encoding, and streams the result to this Message object.
   1.935 +Message& Message::operator <<(const ::wstring& wstr) {
   1.936 +  internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
   1.937 +  return *this;
   1.938 +}
   1.939 +#endif  // GTEST_HAS_GLOBAL_WSTRING
   1.940 +
   1.941 +// AssertionResult constructors.
   1.942 +// Used in EXPECT_TRUE/FALSE(assertion_result).
   1.943 +AssertionResult::AssertionResult(const AssertionResult& other)
   1.944 +    : success_(other.success_),
   1.945 +      message_(other.message_.get() != NULL ?
   1.946 +               new ::std::string(*other.message_) :
   1.947 +               static_cast< ::std::string*>(NULL)) {
   1.948 +}
   1.949 +
   1.950 +// Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
   1.951 +AssertionResult AssertionResult::operator!() const {
   1.952 +  AssertionResult negation(!success_);
   1.953 +  if (message_.get() != NULL)
   1.954 +    negation << *message_;
   1.955 +  return negation;
   1.956 +}
   1.957 +
   1.958 +// Makes a successful assertion result.
   1.959 +AssertionResult AssertionSuccess() {
   1.960 +  return AssertionResult(true);
   1.961 +}
   1.962 +
   1.963 +// Makes a failed assertion result.
   1.964 +AssertionResult AssertionFailure() {
   1.965 +  return AssertionResult(false);
   1.966 +}
   1.967 +
   1.968 +// Makes a failed assertion result with the given failure message.
   1.969 +// Deprecated; use AssertionFailure() << message.
   1.970 +AssertionResult AssertionFailure(const Message& message) {
   1.971 +  return AssertionFailure() << message;
   1.972 +}
   1.973 +
   1.974 +namespace internal {
   1.975 +
   1.976 +// Constructs and returns the message for an equality assertion
   1.977 +// (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
   1.978 +//
   1.979 +// The first four parameters are the expressions used in the assertion
   1.980 +// and their values, as strings.  For example, for ASSERT_EQ(foo, bar)
   1.981 +// where foo is 5 and bar is 6, we have:
   1.982 +//
   1.983 +//   expected_expression: "foo"
   1.984 +//   actual_expression:   "bar"
   1.985 +//   expected_value:      "5"
   1.986 +//   actual_value:        "6"
   1.987 +//
   1.988 +// The ignoring_case parameter is true iff the assertion is a
   1.989 +// *_STRCASEEQ*.  When it's true, the string " (ignoring case)" will
   1.990 +// be inserted into the message.
   1.991 +AssertionResult EqFailure(const char* expected_expression,
   1.992 +                          const char* actual_expression,
   1.993 +                          const String& expected_value,
   1.994 +                          const String& actual_value,
   1.995 +                          bool ignoring_case) {
   1.996 +  Message msg;
   1.997 +  msg << "Value of: " << actual_expression;
   1.998 +  if (actual_value != actual_expression) {
   1.999 +    msg << "\n  Actual: " << actual_value;
  1.1000 +  }
  1.1001 +
  1.1002 +  msg << "\nExpected: " << expected_expression;
  1.1003 +  if (ignoring_case) {
  1.1004 +    msg << " (ignoring case)";
  1.1005 +  }
  1.1006 +  if (expected_value != expected_expression) {
  1.1007 +    msg << "\nWhich is: " << expected_value;
  1.1008 +  }
  1.1009 +
  1.1010 +  return AssertionFailure() << msg;
  1.1011 +}
  1.1012 +
  1.1013 +// Constructs and returns the message for an equality assertion
  1.1014 +// (e.g. ASSERT_NE, EXPECT_NE, etc) failure.
  1.1015 +//
  1.1016 +// The first four parameters are the expressions used in the assertion
  1.1017 +// and their values, as strings.  For example, for ASSERT_NE(foo, bar)
  1.1018 +// where foo is 5 and bar is 6, we have:
  1.1019 +//
  1.1020 +//   expected_expression: "foo"
  1.1021 +//   actual_expression:   "bar"
  1.1022 +//   expected_value:      "5"
  1.1023 +//   actual_value:        "6"
  1.1024 +//
  1.1025 +// The ignoring_case parameter is true iff the assertion is a
  1.1026 +// *_STRCASENE*.  When it's true, the string " (ignoring case)" will
  1.1027 +// be inserted into the message.
  1.1028 +AssertionResult NeFailure(const char* expected_expression,
  1.1029 +                          const char* actual_expression,
  1.1030 +                          const String& expected_value,
  1.1031 +                          const String& actual_value,
  1.1032 +                          bool ignoring_case) {
  1.1033 +  Message msg;
  1.1034 +  msg << "Value of: " << actual_expression;
  1.1035 +  if (actual_value != actual_expression) {
  1.1036 +    msg << "\n  Actual: " << actual_value;
  1.1037 +  }
  1.1038 +
  1.1039 +  msg << "\nExpected: " << expected_expression;
  1.1040 +  if (ignoring_case) {
  1.1041 +    msg << " (ignoring case)";
  1.1042 +  }
  1.1043 +  if (expected_value != expected_expression) {
  1.1044 +    msg << "\nWhich is: " << expected_value;
  1.1045 +  }
  1.1046 +
  1.1047 +  return AssertionFailure() << msg;
  1.1048 +}
  1.1049 +
  1.1050 +// Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
  1.1051 +String GetBoolAssertionFailureMessage(const AssertionResult& assertion_result,
  1.1052 +                                      const char* expression_text,
  1.1053 +                                      const char* actual_predicate_value,
  1.1054 +                                      const char* expected_predicate_value) {
  1.1055 +  const char* actual_message = assertion_result.message();
  1.1056 +  Message msg;
  1.1057 +  msg << "Value of: " << expression_text
  1.1058 +      << "\n  Actual: " << actual_predicate_value;
  1.1059 +  if (actual_message[0] != '\0')
  1.1060 +    msg << " (" << actual_message << ")";
  1.1061 +  msg << "\nExpected: " << expected_predicate_value;
  1.1062 +  return msg.GetString();
  1.1063 +}
  1.1064 +
  1.1065 +// Helper function for implementing ASSERT_NEAR.
  1.1066 +AssertionResult DoubleNearPredFormat(const char* expr1,
  1.1067 +                                     const char* expr2,
  1.1068 +                                     const char* abs_error_expr,
  1.1069 +                                     double val1,
  1.1070 +                                     double val2,
  1.1071 +                                     double abs_error) {
  1.1072 +  const double diff = fabs(val1 - val2);
  1.1073 +  if (diff <= abs_error) return AssertionSuccess();
  1.1074 +
  1.1075 +  // TODO(wan): do not print the value of an expression if it's
  1.1076 +  // already a literal.
  1.1077 +  return AssertionFailure()
  1.1078 +      << "The difference between " << expr1 << " and " << expr2
  1.1079 +      << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"
  1.1080 +      << expr1 << " evaluates to " << val1 << ",\n"
  1.1081 +      << expr2 << " evaluates to " << val2 << ", and\n"
  1.1082 +      << abs_error_expr << " evaluates to " << abs_error << ".";
  1.1083 +}
  1.1084 +
  1.1085 +
  1.1086 +// Helper template for implementing FloatLE() and DoubleLE().
  1.1087 +template <typename RawType>
  1.1088 +AssertionResult FloatingPointLE(const char* expr1,
  1.1089 +                                const char* expr2,
  1.1090 +                                RawType val1,
  1.1091 +                                RawType val2) {
  1.1092 +  // Returns success if val1 is less than val2,
  1.1093 +  if (val1 < val2) {
  1.1094 +    return AssertionSuccess();
  1.1095 +  }
  1.1096 +
  1.1097 +  // or if val1 is almost equal to val2.
  1.1098 +  const FloatingPoint<RawType> lhs(val1), rhs(val2);
  1.1099 +  if (lhs.AlmostEquals(rhs)) {
  1.1100 +    return AssertionSuccess();
  1.1101 +  }
  1.1102 +
  1.1103 +  // Note that the above two checks will both fail if either val1 or
  1.1104 +  // val2 is NaN, as the IEEE floating-point standard requires that
  1.1105 +  // any predicate involving a NaN must return false.
  1.1106 +
  1.1107 +  ::std::stringstream val1_ss;
  1.1108 +  val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
  1.1109 +          << val1;
  1.1110 +
  1.1111 +  ::std::stringstream val2_ss;
  1.1112 +  val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
  1.1113 +          << val2;
  1.1114 +
  1.1115 +  return AssertionFailure()
  1.1116 +      << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
  1.1117 +      << "  Actual: " << StringStreamToString(&val1_ss) << " vs "
  1.1118 +      << StringStreamToString(&val2_ss);
  1.1119 +}
  1.1120 +
  1.1121 +}  // namespace internal
  1.1122 +
  1.1123 +// Asserts that val1 is less than, or almost equal to, val2.  Fails
  1.1124 +// otherwise.  In particular, it fails if either val1 or val2 is NaN.
  1.1125 +AssertionResult FloatLE(const char* expr1, const char* expr2,
  1.1126 +                        float val1, float val2) {
  1.1127 +  return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
  1.1128 +}
  1.1129 +
  1.1130 +// Asserts that val1 is less than, or almost equal to, val2.  Fails
  1.1131 +// otherwise.  In particular, it fails if either val1 or val2 is NaN.
  1.1132 +AssertionResult DoubleLE(const char* expr1, const char* expr2,
  1.1133 +                         double val1, double val2) {
  1.1134 +  return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
  1.1135 +}
  1.1136 +
  1.1137 +namespace internal {
  1.1138 +
  1.1139 +// The helper function for {ASSERT|EXPECT}_EQ with int or enum
  1.1140 +// arguments.
  1.1141 +AssertionResult CmpHelperEQ(const char* expected_expression,
  1.1142 +                            const char* actual_expression,
  1.1143 +                            BiggestInt expected,
  1.1144 +                            BiggestInt actual) {
  1.1145 +  if (expected == actual) {
  1.1146 +    return AssertionSuccess();
  1.1147 +  }
  1.1148 +
  1.1149 +  return EqFailure(expected_expression,
  1.1150 +                   actual_expression,
  1.1151 +                   FormatForComparisonFailureMessage(expected, actual),
  1.1152 +                   FormatForComparisonFailureMessage(actual, expected),
  1.1153 +                   false);
  1.1154 +}
  1.1155 +
  1.1156 +// A macro for implementing the helper functions needed to implement
  1.1157 +// ASSERT_?? and EXPECT_?? with integer or enum arguments.  It is here
  1.1158 +// just to avoid copy-and-paste of similar code.
  1.1159 +#define GTEST_IMPL_CMP_HELPER_(op_name, op)\
  1.1160 +AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
  1.1161 +                                   BiggestInt val1, BiggestInt val2) {\
  1.1162 +  if (val1 op val2) {\
  1.1163 +    return AssertionSuccess();\
  1.1164 +  } else {\
  1.1165 +    return AssertionFailure() \
  1.1166 +        << "Expected: (" << expr1 << ") " #op " (" << expr2\
  1.1167 +        << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
  1.1168 +        << " vs " << FormatForComparisonFailureMessage(val2, val1);\
  1.1169 +  }\
  1.1170 +}
  1.1171 +
  1.1172 +// Implements the helper function for {ASSERT|EXPECT}_NE with int or
  1.1173 +// enum arguments.
  1.1174 +GTEST_IMPL_CMP_HELPER_(NE, !=)
  1.1175 +// Implements the helper function for {ASSERT|EXPECT}_LE with int or
  1.1176 +// enum arguments.
  1.1177 +GTEST_IMPL_CMP_HELPER_(LE, <=)
  1.1178 +// Implements the helper function for {ASSERT|EXPECT}_LT with int or
  1.1179 +// enum arguments.
  1.1180 +GTEST_IMPL_CMP_HELPER_(LT, < )
  1.1181 +// Implements the helper function for {ASSERT|EXPECT}_GE with int or
  1.1182 +// enum arguments.
  1.1183 +GTEST_IMPL_CMP_HELPER_(GE, >=)
  1.1184 +// Implements the helper function for {ASSERT|EXPECT}_GT with int or
  1.1185 +// enum arguments.
  1.1186 +GTEST_IMPL_CMP_HELPER_(GT, > )
  1.1187 +
  1.1188 +#undef GTEST_IMPL_CMP_HELPER_
  1.1189 +
  1.1190 +// The helper function for {ASSERT|EXPECT}_STREQ.
  1.1191 +AssertionResult CmpHelperSTREQ(const char* expected_expression,
  1.1192 +                               const char* actual_expression,
  1.1193 +                               const char* expected,
  1.1194 +                               const char* actual) {
  1.1195 +  if (String::CStringEquals(expected, actual)) {
  1.1196 +    return AssertionSuccess();
  1.1197 +  }
  1.1198 +
  1.1199 +  return EqFailure(expected_expression,
  1.1200 +                   actual_expression,
  1.1201 +                   PrintToString(expected),
  1.1202 +                   PrintToString(actual),
  1.1203 +                   false);
  1.1204 +}
  1.1205 +
  1.1206 +// The helper function for {ASSERT|EXPECT}_STRCASEEQ.
  1.1207 +AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression,
  1.1208 +                                   const char* actual_expression,
  1.1209 +                                   const char* expected,
  1.1210 +                                   const char* actual) {
  1.1211 +  if (String::CaseInsensitiveCStringEquals(expected, actual)) {
  1.1212 +    return AssertionSuccess();
  1.1213 +  }
  1.1214 +
  1.1215 +  return EqFailure(expected_expression,
  1.1216 +                   actual_expression,
  1.1217 +                   PrintToString(expected),
  1.1218 +                   PrintToString(actual),
  1.1219 +                   true);
  1.1220 +}
  1.1221 +
  1.1222 +// The helper function for {ASSERT|EXPECT}_STRNE.
  1.1223 +AssertionResult CmpHelperSTRNE(const char* s1_expression,
  1.1224 +                               const char* s2_expression,
  1.1225 +                               const char* s1,
  1.1226 +                               const char* s2) {
  1.1227 +  if (!String::CStringEquals(s1, s2)) {
  1.1228 +    return AssertionSuccess();
  1.1229 +  } else {
  1.1230 +    return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
  1.1231 +                              << s2_expression << "), actual: \""
  1.1232 +                              << s1 << "\" vs \"" << s2 << "\"";
  1.1233 +  }
  1.1234 +}
  1.1235 +
  1.1236 +// The helper function for {ASSERT|EXPECT}_STRCASENE.
  1.1237 +AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
  1.1238 +                                   const char* s2_expression,
  1.1239 +                                   const char* s1,
  1.1240 +                                   const char* s2) {
  1.1241 +  if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
  1.1242 +    return AssertionSuccess();
  1.1243 +  } else {
  1.1244 +    return AssertionFailure()
  1.1245 +        << "Expected: (" << s1_expression << ") != ("
  1.1246 +        << s2_expression << ") (ignoring case), actual: \""
  1.1247 +        << s1 << "\" vs \"" << s2 << "\"";
  1.1248 +  }
  1.1249 +}
  1.1250 +
  1.1251 +}  // namespace internal
  1.1252 +
  1.1253 +namespace {
  1.1254 +
  1.1255 +// Helper functions for implementing IsSubString() and IsNotSubstring().
  1.1256 +
  1.1257 +// This group of overloaded functions return true iff needle is a
  1.1258 +// substring of haystack.  NULL is considered a substring of itself
  1.1259 +// only.
  1.1260 +
  1.1261 +bool IsSubstringPred(const char* needle, const char* haystack) {
  1.1262 +  if (needle == NULL || haystack == NULL)
  1.1263 +    return needle == haystack;
  1.1264 +
  1.1265 +  return strstr(haystack, needle) != NULL;
  1.1266 +}
  1.1267 +
  1.1268 +bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
  1.1269 +  if (needle == NULL || haystack == NULL)
  1.1270 +    return needle == haystack;
  1.1271 +
  1.1272 +  return wcsstr(haystack, needle) != NULL;
  1.1273 +}
  1.1274 +
  1.1275 +// StringType here can be either ::std::string or ::std::wstring.
  1.1276 +template <typename StringType>
  1.1277 +bool IsSubstringPred(const StringType& needle,
  1.1278 +                     const StringType& haystack) {
  1.1279 +  return haystack.find(needle) != StringType::npos;
  1.1280 +}
  1.1281 +
  1.1282 +// This function implements either IsSubstring() or IsNotSubstring(),
  1.1283 +// depending on the value of the expected_to_be_substring parameter.
  1.1284 +// StringType here can be const char*, const wchar_t*, ::std::string,
  1.1285 +// or ::std::wstring.
  1.1286 +template <typename StringType>
  1.1287 +AssertionResult IsSubstringImpl(
  1.1288 +    bool expected_to_be_substring,
  1.1289 +    const char* needle_expr, const char* haystack_expr,
  1.1290 +    const StringType& needle, const StringType& haystack) {
  1.1291 +  if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
  1.1292 +    return AssertionSuccess();
  1.1293 +
  1.1294 +  const bool is_wide_string = sizeof(needle[0]) > 1;
  1.1295 +  const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
  1.1296 +  return AssertionFailure()
  1.1297 +      << "Value of: " << needle_expr << "\n"
  1.1298 +      << "  Actual: " << begin_string_quote << needle << "\"\n"
  1.1299 +      << "Expected: " << (expected_to_be_substring ? "" : "not ")
  1.1300 +      << "a substring of " << haystack_expr << "\n"
  1.1301 +      << "Which is: " << begin_string_quote << haystack << "\"";
  1.1302 +}
  1.1303 +
  1.1304 +}  // namespace
  1.1305 +
  1.1306 +// IsSubstring() and IsNotSubstring() check whether needle is a
  1.1307 +// substring of haystack (NULL is considered a substring of itself
  1.1308 +// only), and return an appropriate error message when they fail.
  1.1309 +
  1.1310 +AssertionResult IsSubstring(
  1.1311 +    const char* needle_expr, const char* haystack_expr,
  1.1312 +    const char* needle, const char* haystack) {
  1.1313 +  return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
  1.1314 +}
  1.1315 +
  1.1316 +AssertionResult IsSubstring(
  1.1317 +    const char* needle_expr, const char* haystack_expr,
  1.1318 +    const wchar_t* needle, const wchar_t* haystack) {
  1.1319 +  return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
  1.1320 +}
  1.1321 +
  1.1322 +AssertionResult IsNotSubstring(
  1.1323 +    const char* needle_expr, const char* haystack_expr,
  1.1324 +    const char* needle, const char* haystack) {
  1.1325 +  return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
  1.1326 +}
  1.1327 +
  1.1328 +AssertionResult IsNotSubstring(
  1.1329 +    const char* needle_expr, const char* haystack_expr,
  1.1330 +    const wchar_t* needle, const wchar_t* haystack) {
  1.1331 +  return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
  1.1332 +}
  1.1333 +
  1.1334 +AssertionResult IsSubstring(
  1.1335 +    const char* needle_expr, const char* haystack_expr,
  1.1336 +    const ::std::string& needle, const ::std::string& haystack) {
  1.1337 +  return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
  1.1338 +}
  1.1339 +
  1.1340 +AssertionResult IsNotSubstring(
  1.1341 +    const char* needle_expr, const char* haystack_expr,
  1.1342 +    const ::std::string& needle, const ::std::string& haystack) {
  1.1343 +  return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
  1.1344 +}
  1.1345 +
  1.1346 +#if GTEST_HAS_STD_WSTRING
  1.1347 +AssertionResult IsSubstring(
  1.1348 +    const char* needle_expr, const char* haystack_expr,
  1.1349 +    const ::std::wstring& needle, const ::std::wstring& haystack) {
  1.1350 +  return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
  1.1351 +}
  1.1352 +
  1.1353 +AssertionResult IsNotSubstring(
  1.1354 +    const char* needle_expr, const char* haystack_expr,
  1.1355 +    const ::std::wstring& needle, const ::std::wstring& haystack) {
  1.1356 +  return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
  1.1357 +}
  1.1358 +#endif  // GTEST_HAS_STD_WSTRING
  1.1359 +
  1.1360 +namespace internal {
  1.1361 +
  1.1362 +#if GTEST_OS_WINDOWS
  1.1363 +
  1.1364 +namespace {
  1.1365 +
  1.1366 +// Helper function for IsHRESULT{SuccessFailure} predicates
  1.1367 +AssertionResult HRESULTFailureHelper(const char* expr,
  1.1368 +                                     const char* expected,
  1.1369 +                                     long hr) {  // NOLINT
  1.1370 +# if GTEST_OS_WINDOWS_MOBILE
  1.1371 +
  1.1372 +  // Windows CE doesn't support FormatMessage.
  1.1373 +  const char error_text[] = "";
  1.1374 +
  1.1375 +# else
  1.1376 +
  1.1377 +  // Looks up the human-readable system message for the HRESULT code
  1.1378 +  // and since we're not passing any params to FormatMessage, we don't
  1.1379 +  // want inserts expanded.
  1.1380 +  const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
  1.1381 +                       FORMAT_MESSAGE_IGNORE_INSERTS;
  1.1382 +  const DWORD kBufSize = 4096;  // String::Format can't exceed this length.
  1.1383 +  // Gets the system's human readable message string for this HRESULT.
  1.1384 +  char error_text[kBufSize] = { '\0' };
  1.1385 +  DWORD message_length = ::FormatMessageA(kFlags,
  1.1386 +                                          0,  // no source, we're asking system
  1.1387 +                                          hr,  // the error
  1.1388 +                                          0,  // no line width restrictions
  1.1389 +                                          error_text,  // output buffer
  1.1390 +                                          kBufSize,  // buf size
  1.1391 +                                          NULL);  // no arguments for inserts
  1.1392 +  // Trims tailing white space (FormatMessage leaves a trailing cr-lf)
  1.1393 +  for (; message_length && IsSpace(error_text[message_length - 1]);
  1.1394 +          --message_length) {
  1.1395 +    error_text[message_length - 1] = '\0';
  1.1396 +  }
  1.1397 +
  1.1398 +# endif  // GTEST_OS_WINDOWS_MOBILE
  1.1399 +
  1.1400 +  const String error_hex(String::Format("0x%08X ", hr));
  1.1401 +  return ::testing::AssertionFailure()
  1.1402 +      << "Expected: " << expr << " " << expected << ".\n"
  1.1403 +      << "  Actual: " << error_hex << error_text << "\n";
  1.1404 +}
  1.1405 +
  1.1406 +}  // namespace
  1.1407 +
  1.1408 +AssertionResult IsHRESULTSuccess(const char* expr, long hr) {  // NOLINT
  1.1409 +  if (SUCCEEDED(hr)) {
  1.1410 +    return AssertionSuccess();
  1.1411 +  }
  1.1412 +  return HRESULTFailureHelper(expr, "succeeds", hr);
  1.1413 +}
  1.1414 +
  1.1415 +AssertionResult IsHRESULTFailure(const char* expr, long hr) {  // NOLINT
  1.1416 +  if (FAILED(hr)) {
  1.1417 +    return AssertionSuccess();
  1.1418 +  }
  1.1419 +  return HRESULTFailureHelper(expr, "fails", hr);
  1.1420 +}
  1.1421 +
  1.1422 +#endif  // GTEST_OS_WINDOWS
  1.1423 +
  1.1424 +// Utility functions for encoding Unicode text (wide strings) in
  1.1425 +// UTF-8.
  1.1426 +
  1.1427 +// A Unicode code-point can have upto 21 bits, and is encoded in UTF-8
  1.1428 +// like this:
  1.1429 +//
  1.1430 +// Code-point length   Encoding
  1.1431 +//   0 -  7 bits       0xxxxxxx
  1.1432 +//   8 - 11 bits       110xxxxx 10xxxxxx
  1.1433 +//  12 - 16 bits       1110xxxx 10xxxxxx 10xxxxxx
  1.1434 +//  17 - 21 bits       11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  1.1435 +
  1.1436 +// The maximum code-point a one-byte UTF-8 sequence can represent.
  1.1437 +const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) <<  7) - 1;
  1.1438 +
  1.1439 +// The maximum code-point a two-byte UTF-8 sequence can represent.
  1.1440 +const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1;
  1.1441 +
  1.1442 +// The maximum code-point a three-byte UTF-8 sequence can represent.
  1.1443 +const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2*6)) - 1;
  1.1444 +
  1.1445 +// The maximum code-point a four-byte UTF-8 sequence can represent.
  1.1446 +const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3*6)) - 1;
  1.1447 +
  1.1448 +// Chops off the n lowest bits from a bit pattern.  Returns the n
  1.1449 +// lowest bits.  As a side effect, the original bit pattern will be
  1.1450 +// shifted to the right by n bits.
  1.1451 +inline UInt32 ChopLowBits(UInt32* bits, int n) {
  1.1452 +  const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1);
  1.1453 +  *bits >>= n;
  1.1454 +  return low_bits;
  1.1455 +}
  1.1456 +
  1.1457 +// Converts a Unicode code point to a narrow string in UTF-8 encoding.
  1.1458 +// code_point parameter is of type UInt32 because wchar_t may not be
  1.1459 +// wide enough to contain a code point.
  1.1460 +// The output buffer str must containt at least 32 characters.
  1.1461 +// The function returns the address of the output buffer.
  1.1462 +// If the code_point is not a valid Unicode code point
  1.1463 +// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be output
  1.1464 +// as '(Invalid Unicode 0xXXXXXXXX)'.
  1.1465 +char* CodePointToUtf8(UInt32 code_point, char* str) {
  1.1466 +  if (code_point <= kMaxCodePoint1) {
  1.1467 +    str[1] = '\0';
  1.1468 +    str[0] = static_cast<char>(code_point);                          // 0xxxxxxx
  1.1469 +  } else if (code_point <= kMaxCodePoint2) {
  1.1470 +    str[2] = '\0';
  1.1471 +    str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
  1.1472 +    str[0] = static_cast<char>(0xC0 | code_point);                   // 110xxxxx
  1.1473 +  } else if (code_point <= kMaxCodePoint3) {
  1.1474 +    str[3] = '\0';
  1.1475 +    str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
  1.1476 +    str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
  1.1477 +    str[0] = static_cast<char>(0xE0 | code_point);                   // 1110xxxx
  1.1478 +  } else if (code_point <= kMaxCodePoint4) {
  1.1479 +    str[4] = '\0';
  1.1480 +    str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
  1.1481 +    str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
  1.1482 +    str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
  1.1483 +    str[0] = static_cast<char>(0xF0 | code_point);                   // 11110xxx
  1.1484 +  } else {
  1.1485 +    // The longest string String::Format can produce when invoked
  1.1486 +    // with these parameters is 28 character long (not including
  1.1487 +    // the terminating nul character). We are asking for 32 character
  1.1488 +    // buffer just in case. This is also enough for strncpy to
  1.1489 +    // null-terminate the destination string.
  1.1490 +    posix::StrNCpy(
  1.1491 +        str, String::Format("(Invalid Unicode 0x%X)", code_point).c_str(), 32);
  1.1492 +    str[31] = '\0';  // Makes sure no change in the format to strncpy leaves
  1.1493 +                     // the result unterminated.
  1.1494 +  }
  1.1495 +  return str;
  1.1496 +}
  1.1497 +
  1.1498 +// The following two functions only make sense if the the system
  1.1499 +// uses UTF-16 for wide string encoding. All supported systems
  1.1500 +// with 16 bit wchar_t (Windows, Cygwin, Symbian OS) do use UTF-16.
  1.1501 +
  1.1502 +// Determines if the arguments constitute UTF-16 surrogate pair
  1.1503 +// and thus should be combined into a single Unicode code point
  1.1504 +// using CreateCodePointFromUtf16SurrogatePair.
  1.1505 +inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
  1.1506 +  return sizeof(wchar_t) == 2 &&
  1.1507 +      (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;
  1.1508 +}
  1.1509 +
  1.1510 +// Creates a Unicode code point from UTF16 surrogate pair.
  1.1511 +inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first,
  1.1512 +                                                    wchar_t second) {
  1.1513 +  const UInt32 mask = (1 << 10) - 1;
  1.1514 +  return (sizeof(wchar_t) == 2) ?
  1.1515 +      (((first & mask) << 10) | (second & mask)) + 0x10000 :
  1.1516 +      // This function should not be called when the condition is
  1.1517 +      // false, but we provide a sensible default in case it is.
  1.1518 +      static_cast<UInt32>(first);
  1.1519 +}
  1.1520 +
  1.1521 +// Converts a wide string to a narrow string in UTF-8 encoding.
  1.1522 +// The wide string is assumed to have the following encoding:
  1.1523 +//   UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
  1.1524 +//   UTF-32 if sizeof(wchar_t) == 4 (on Linux)
  1.1525 +// Parameter str points to a null-terminated wide string.
  1.1526 +// Parameter num_chars may additionally limit the number
  1.1527 +// of wchar_t characters processed. -1 is used when the entire string
  1.1528 +// should be processed.
  1.1529 +// If the string contains code points that are not valid Unicode code points
  1.1530 +// (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
  1.1531 +// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
  1.1532 +// and contains invalid UTF-16 surrogate pairs, values in those pairs
  1.1533 +// will be encoded as individual Unicode characters from Basic Normal Plane.
  1.1534 +String WideStringToUtf8(const wchar_t* str, int num_chars) {
  1.1535 +  if (num_chars == -1)
  1.1536 +    num_chars = static_cast<int>(wcslen(str));
  1.1537 +
  1.1538 +  ::std::stringstream stream;
  1.1539 +  for (int i = 0; i < num_chars; ++i) {
  1.1540 +    UInt32 unicode_code_point;
  1.1541 +
  1.1542 +    if (str[i] == L'\0') {
  1.1543 +      break;
  1.1544 +    } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
  1.1545 +      unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i],
  1.1546 +                                                                 str[i + 1]);
  1.1547 +      i++;
  1.1548 +    } else {
  1.1549 +      unicode_code_point = static_cast<UInt32>(str[i]);
  1.1550 +    }
  1.1551 +
  1.1552 +    char buffer[32];  // CodePointToUtf8 requires a buffer this big.
  1.1553 +    stream << CodePointToUtf8(unicode_code_point, buffer);
  1.1554 +  }
  1.1555 +  return StringStreamToString(&stream);
  1.1556 +}
  1.1557 +
  1.1558 +// Converts a wide C string to a String using the UTF-8 encoding.
  1.1559 +// NULL will be converted to "(null)".
  1.1560 +String String::ShowWideCString(const wchar_t * wide_c_str) {
  1.1561 +  if (wide_c_str == NULL) return String("(null)");
  1.1562 +
  1.1563 +  return String(internal::WideStringToUtf8(wide_c_str, -1).c_str());
  1.1564 +}
  1.1565 +
  1.1566 +// Compares two wide C strings.  Returns true iff they have the same
  1.1567 +// content.
  1.1568 +//
  1.1569 +// Unlike wcscmp(), this function can handle NULL argument(s).  A NULL
  1.1570 +// C string is considered different to any non-NULL C string,
  1.1571 +// including the empty string.
  1.1572 +bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {
  1.1573 +  if (lhs == NULL) return rhs == NULL;
  1.1574 +
  1.1575 +  if (rhs == NULL) return false;
  1.1576 +
  1.1577 +  return wcscmp(lhs, rhs) == 0;
  1.1578 +}
  1.1579 +
  1.1580 +// Helper function for *_STREQ on wide strings.
  1.1581 +AssertionResult CmpHelperSTREQ(const char* expected_expression,
  1.1582 +                               const char* actual_expression,
  1.1583 +                               const wchar_t* expected,
  1.1584 +                               const wchar_t* actual) {
  1.1585 +  if (String::WideCStringEquals(expected, actual)) {
  1.1586 +    return AssertionSuccess();
  1.1587 +  }
  1.1588 +
  1.1589 +  return EqFailure(expected_expression,
  1.1590 +                   actual_expression,
  1.1591 +                   PrintToString(expected),
  1.1592 +                   PrintToString(actual),
  1.1593 +                   false);
  1.1594 +}
  1.1595 +
  1.1596 +// Helper function for *_STRNE on wide strings.
  1.1597 +AssertionResult CmpHelperSTRNE(const char* s1_expression,
  1.1598 +                               const char* s2_expression,
  1.1599 +                               const wchar_t* s1,
  1.1600 +                               const wchar_t* s2) {
  1.1601 +  if (!String::WideCStringEquals(s1, s2)) {
  1.1602 +    return AssertionSuccess();
  1.1603 +  }
  1.1604 +
  1.1605 +  return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
  1.1606 +                            << s2_expression << "), actual: "
  1.1607 +                            << PrintToString(s1)
  1.1608 +                            << " vs " << PrintToString(s2);
  1.1609 +}
  1.1610 +
  1.1611 +// Compares two C strings, ignoring case.  Returns true iff they have
  1.1612 +// the same content.
  1.1613 +//
  1.1614 +// Unlike strcasecmp(), this function can handle NULL argument(s).  A
  1.1615 +// NULL C string is considered different to any non-NULL C string,
  1.1616 +// including the empty string.
  1.1617 +bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) {
  1.1618 +  if (lhs == NULL)
  1.1619 +    return rhs == NULL;
  1.1620 +  if (rhs == NULL)
  1.1621 +    return false;
  1.1622 +  return posix::StrCaseCmp(lhs, rhs) == 0;
  1.1623 +}
  1.1624 +
  1.1625 +  // Compares two wide C strings, ignoring case.  Returns true iff they
  1.1626 +  // have the same content.
  1.1627 +  //
  1.1628 +  // Unlike wcscasecmp(), this function can handle NULL argument(s).
  1.1629 +  // A NULL C string is considered different to any non-NULL wide C string,
  1.1630 +  // including the empty string.
  1.1631 +  // NB: The implementations on different platforms slightly differ.
  1.1632 +  // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
  1.1633 +  // environment variable. On GNU platform this method uses wcscasecmp
  1.1634 +  // which compares according to LC_CTYPE category of the current locale.
  1.1635 +  // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
  1.1636 +  // current locale.
  1.1637 +bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
  1.1638 +                                              const wchar_t* rhs) {
  1.1639 +  if (lhs == NULL) return rhs == NULL;
  1.1640 +
  1.1641 +  if (rhs == NULL) return false;
  1.1642 +
  1.1643 +#if GTEST_OS_WINDOWS
  1.1644 +  return _wcsicmp(lhs, rhs) == 0;
  1.1645 +#elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID
  1.1646 +  return wcscasecmp(lhs, rhs) == 0;
  1.1647 +#else
  1.1648 +  // Android, Mac OS X and Cygwin don't define wcscasecmp.
  1.1649 +  // Other unknown OSes may not define it either.
  1.1650 +  wint_t left, right;
  1.1651 +  do {
  1.1652 +    left = towlower(*lhs++);
  1.1653 +    right = towlower(*rhs++);
  1.1654 +  } while (left && left == right);
  1.1655 +  return left == right;
  1.1656 +#endif  // OS selector
  1.1657 +}
  1.1658 +
  1.1659 +// Compares this with another String.
  1.1660 +// Returns < 0 if this is less than rhs, 0 if this is equal to rhs, or > 0
  1.1661 +// if this is greater than rhs.
  1.1662 +int String::Compare(const String & rhs) const {
  1.1663 +  const char* const lhs_c_str = c_str();
  1.1664 +  const char* const rhs_c_str = rhs.c_str();
  1.1665 +
  1.1666 +  if (lhs_c_str == NULL) {
  1.1667 +    return rhs_c_str == NULL ? 0 : -1;  // NULL < anything except NULL
  1.1668 +  } else if (rhs_c_str == NULL) {
  1.1669 +    return 1;
  1.1670 +  }
  1.1671 +
  1.1672 +  const size_t shorter_str_len =
  1.1673 +      length() <= rhs.length() ? length() : rhs.length();
  1.1674 +  for (size_t i = 0; i != shorter_str_len; i++) {
  1.1675 +    if (lhs_c_str[i] < rhs_c_str[i]) {
  1.1676 +      return -1;
  1.1677 +    } else if (lhs_c_str[i] > rhs_c_str[i]) {
  1.1678 +      return 1;
  1.1679 +    }
  1.1680 +  }
  1.1681 +  return (length() < rhs.length()) ? -1 :
  1.1682 +      (length() > rhs.length()) ? 1 : 0;
  1.1683 +}
  1.1684 +
  1.1685 +// Returns true iff this String ends with the given suffix.  *Any*
  1.1686 +// String is considered to end with a NULL or empty suffix.
  1.1687 +bool String::EndsWith(const char* suffix) const {
  1.1688 +  if (suffix == NULL || CStringEquals(suffix, "")) return true;
  1.1689 +
  1.1690 +  if (c_str() == NULL) return false;
  1.1691 +
  1.1692 +  const size_t this_len = strlen(c_str());
  1.1693 +  const size_t suffix_len = strlen(suffix);
  1.1694 +  return (this_len >= suffix_len) &&
  1.1695 +         CStringEquals(c_str() + this_len - suffix_len, suffix);
  1.1696 +}
  1.1697 +
  1.1698 +// Returns true iff this String ends with the given suffix, ignoring case.
  1.1699 +// Any String is considered to end with a NULL or empty suffix.
  1.1700 +bool String::EndsWithCaseInsensitive(const char* suffix) const {
  1.1701 +  if (suffix == NULL || CStringEquals(suffix, "")) return true;
  1.1702 +
  1.1703 +  if (c_str() == NULL) return false;
  1.1704 +
  1.1705 +  const size_t this_len = strlen(c_str());
  1.1706 +  const size_t suffix_len = strlen(suffix);
  1.1707 +  return (this_len >= suffix_len) &&
  1.1708 +         CaseInsensitiveCStringEquals(c_str() + this_len - suffix_len, suffix);
  1.1709 +}
  1.1710 +
  1.1711 +// Formats a list of arguments to a String, using the same format
  1.1712 +// spec string as for printf.
  1.1713 +//
  1.1714 +// We do not use the StringPrintf class as it is not universally
  1.1715 +// available.
  1.1716 +//
  1.1717 +// The result is limited to 4096 characters (including the tailing 0).
  1.1718 +// If 4096 characters are not enough to format the input, or if
  1.1719 +// there's an error, "<formatting error or buffer exceeded>" is
  1.1720 +// returned.
  1.1721 +String String::Format(const char * format, ...) {
  1.1722 +  va_list args;
  1.1723 +  va_start(args, format);
  1.1724 +
  1.1725 +  char buffer[4096];
  1.1726 +  const int kBufferSize = sizeof(buffer)/sizeof(buffer[0]);
  1.1727 +
  1.1728 +  // MSVC 8 deprecates vsnprintf(), so we want to suppress warning
  1.1729 +  // 4996 (deprecated function) there.
  1.1730 +#ifdef _MSC_VER  // We are using MSVC.
  1.1731 +# pragma warning(push)          // Saves the current warning state.
  1.1732 +# pragma warning(disable:4996)  // Temporarily disables warning 4996.
  1.1733 +
  1.1734 +  const int size = vsnprintf(buffer, kBufferSize, format, args);
  1.1735 +
  1.1736 +# pragma warning(pop)           // Restores the warning state.
  1.1737 +#else  // We are not using MSVC.
  1.1738 +  const int size = vsnprintf(buffer, kBufferSize, format, args);
  1.1739 +#endif  // _MSC_VER
  1.1740 +  va_end(args);
  1.1741 +
  1.1742 +  // vsnprintf()'s behavior is not portable.  When the buffer is not
  1.1743 +  // big enough, it returns a negative value in MSVC, and returns the
  1.1744 +  // needed buffer size on Linux.  When there is an output error, it
  1.1745 +  // always returns a negative value.  For simplicity, we lump the two
  1.1746 +  // error cases together.
  1.1747 +  if (size < 0 || size >= kBufferSize) {
  1.1748 +    return String("<formatting error or buffer exceeded>");
  1.1749 +  } else {
  1.1750 +    return String(buffer, size);
  1.1751 +  }
  1.1752 +}
  1.1753 +
  1.1754 +// Converts the buffer in a stringstream to a String, converting NUL
  1.1755 +// bytes to "\\0" along the way.
  1.1756 +String StringStreamToString(::std::stringstream* ss) {
  1.1757 +  const ::std::string& str = ss->str();
  1.1758 +  const char* const start = str.c_str();
  1.1759 +  const char* const end = start + str.length();
  1.1760 +
  1.1761 +  // We need to use a helper stringstream to do this transformation
  1.1762 +  // because String doesn't support push_back().
  1.1763 +  ::std::stringstream helper;
  1.1764 +  for (const char* ch = start; ch != end; ++ch) {
  1.1765 +    if (*ch == '\0') {
  1.1766 +      helper << "\\0";  // Replaces NUL with "\\0";
  1.1767 +    } else {
  1.1768 +      helper.put(*ch);
  1.1769 +    }
  1.1770 +  }
  1.1771 +
  1.1772 +  return String(helper.str().c_str());
  1.1773 +}
  1.1774 +
  1.1775 +// Appends the user-supplied message to the Google-Test-generated message.
  1.1776 +String AppendUserMessage(const String& gtest_msg,
  1.1777 +                         const Message& user_msg) {
  1.1778 +  // Appends the user message if it's non-empty.
  1.1779 +  const String user_msg_string = user_msg.GetString();
  1.1780 +  if (user_msg_string.empty()) {
  1.1781 +    return gtest_msg;
  1.1782 +  }
  1.1783 +
  1.1784 +  Message msg;
  1.1785 +  msg << gtest_msg << "\n" << user_msg_string;
  1.1786 +
  1.1787 +  return msg.GetString();
  1.1788 +}
  1.1789 +
  1.1790 +}  // namespace internal
  1.1791 +
  1.1792 +// class TestResult
  1.1793 +
  1.1794 +// Creates an empty TestResult.
  1.1795 +TestResult::TestResult()
  1.1796 +    : death_test_count_(0),
  1.1797 +      elapsed_time_(0) {
  1.1798 +}
  1.1799 +
  1.1800 +// D'tor.
  1.1801 +TestResult::~TestResult() {
  1.1802 +}
  1.1803 +
  1.1804 +// Returns the i-th test part result among all the results. i can
  1.1805 +// range from 0 to total_part_count() - 1. If i is not in that range,
  1.1806 +// aborts the program.
  1.1807 +const TestPartResult& TestResult::GetTestPartResult(int i) const {
  1.1808 +  if (i < 0 || i >= total_part_count())
  1.1809 +    internal::posix::Abort();
  1.1810 +  return test_part_results_.at(i);
  1.1811 +}
  1.1812 +
  1.1813 +// Returns the i-th test property. i can range from 0 to
  1.1814 +// test_property_count() - 1. If i is not in that range, aborts the
  1.1815 +// program.
  1.1816 +const TestProperty& TestResult::GetTestProperty(int i) const {
  1.1817 +  if (i < 0 || i >= test_property_count())
  1.1818 +    internal::posix::Abort();
  1.1819 +  return test_properties_.at(i);
  1.1820 +}
  1.1821 +
  1.1822 +// Clears the test part results.
  1.1823 +void TestResult::ClearTestPartResults() {
  1.1824 +  test_part_results_.clear();
  1.1825 +}
  1.1826 +
  1.1827 +// Adds a test part result to the list.
  1.1828 +void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
  1.1829 +  test_part_results_.push_back(test_part_result);
  1.1830 +}
  1.1831 +
  1.1832 +// Adds a test property to the list. If a property with the same key as the
  1.1833 +// supplied property is already represented, the value of this test_property
  1.1834 +// replaces the old value for that key.
  1.1835 +void TestResult::RecordProperty(const TestProperty& test_property) {
  1.1836 +  if (!ValidateTestProperty(test_property)) {
  1.1837 +    return;
  1.1838 +  }
  1.1839 +  internal::MutexLock lock(&test_properites_mutex_);
  1.1840 +  const std::vector<TestProperty>::iterator property_with_matching_key =
  1.1841 +      std::find_if(test_properties_.begin(), test_properties_.end(),
  1.1842 +                   internal::TestPropertyKeyIs(test_property.key()));
  1.1843 +  if (property_with_matching_key == test_properties_.end()) {
  1.1844 +    test_properties_.push_back(test_property);
  1.1845 +    return;
  1.1846 +  }
  1.1847 +  property_with_matching_key->SetValue(test_property.value());
  1.1848 +}
  1.1849 +
  1.1850 +// Adds a failure if the key is a reserved attribute of Google Test
  1.1851 +// testcase tags.  Returns true if the property is valid.
  1.1852 +bool TestResult::ValidateTestProperty(const TestProperty& test_property) {
  1.1853 +  internal::String key(test_property.key());
  1.1854 +  if (key == "name" || key == "status" || key == "time" || key == "classname") {
  1.1855 +    ADD_FAILURE()
  1.1856 +        << "Reserved key used in RecordProperty(): "
  1.1857 +        << key
  1.1858 +        << " ('name', 'status', 'time', and 'classname' are reserved by "
  1.1859 +        << GTEST_NAME_ << ")";
  1.1860 +    return false;
  1.1861 +  }
  1.1862 +  return true;
  1.1863 +}
  1.1864 +
  1.1865 +// Clears the object.
  1.1866 +void TestResult::Clear() {
  1.1867 +  test_part_results_.clear();
  1.1868 +  test_properties_.clear();
  1.1869 +  death_test_count_ = 0;
  1.1870 +  elapsed_time_ = 0;
  1.1871 +}
  1.1872 +
  1.1873 +// Returns true iff the test failed.
  1.1874 +bool TestResult::Failed() const {
  1.1875 +  for (int i = 0; i < total_part_count(); ++i) {
  1.1876 +    if (GetTestPartResult(i).failed())
  1.1877 +      return true;
  1.1878 +  }
  1.1879 +  return false;
  1.1880 +}
  1.1881 +
  1.1882 +// Returns true iff the test part fatally failed.
  1.1883 +static bool TestPartFatallyFailed(const TestPartResult& result) {
  1.1884 +  return result.fatally_failed();
  1.1885 +}
  1.1886 +
  1.1887 +// Returns true iff the test fatally failed.
  1.1888 +bool TestResult::HasFatalFailure() const {
  1.1889 +  return CountIf(test_part_results_, TestPartFatallyFailed) > 0;
  1.1890 +}
  1.1891 +
  1.1892 +// Returns true iff the test part non-fatally failed.
  1.1893 +static bool TestPartNonfatallyFailed(const TestPartResult& result) {
  1.1894 +  return result.nonfatally_failed();
  1.1895 +}
  1.1896 +
  1.1897 +// Returns true iff the test has a non-fatal failure.
  1.1898 +bool TestResult::HasNonfatalFailure() const {
  1.1899 +  return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0;
  1.1900 +}
  1.1901 +
  1.1902 +// Gets the number of all test parts.  This is the sum of the number
  1.1903 +// of successful test parts and the number of failed test parts.
  1.1904 +int TestResult::total_part_count() const {
  1.1905 +  return static_cast<int>(test_part_results_.size());
  1.1906 +}
  1.1907 +
  1.1908 +// Returns the number of the test properties.
  1.1909 +int TestResult::test_property_count() const {
  1.1910 +  return static_cast<int>(test_properties_.size());
  1.1911 +}
  1.1912 +
  1.1913 +// class Test
  1.1914 +
  1.1915 +// Creates a Test object.
  1.1916 +
  1.1917 +// The c'tor saves the values of all Google Test flags.
  1.1918 +Test::Test()
  1.1919 +    : gtest_flag_saver_(new internal::GTestFlagSaver) {
  1.1920 +}
  1.1921 +
  1.1922 +// The d'tor restores the values of all Google Test flags.
  1.1923 +Test::~Test() {
  1.1924 +  delete gtest_flag_saver_;
  1.1925 +}
  1.1926 +
  1.1927 +// Sets up the test fixture.
  1.1928 +//
  1.1929 +// A sub-class may override this.
  1.1930 +void Test::SetUp() {
  1.1931 +}
  1.1932 +
  1.1933 +// Tears down the test fixture.
  1.1934 +//
  1.1935 +// A sub-class may override this.
  1.1936 +void Test::TearDown() {
  1.1937 +}
  1.1938 +
  1.1939 +// Allows user supplied key value pairs to be recorded for later output.
  1.1940 +void Test::RecordProperty(const char* key, const char* value) {
  1.1941 +  UnitTest::GetInstance()->RecordPropertyForCurrentTest(key, value);
  1.1942 +}
  1.1943 +
  1.1944 +// Allows user supplied key value pairs to be recorded for later output.
  1.1945 +void Test::RecordProperty(const char* key, int value) {
  1.1946 +  Message value_message;
  1.1947 +  value_message << value;
  1.1948 +  RecordProperty(key, value_message.GetString().c_str());
  1.1949 +}
  1.1950 +
  1.1951 +namespace internal {
  1.1952 +
  1.1953 +void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
  1.1954 +                                    const String& message) {
  1.1955 +  // This function is a friend of UnitTest and as such has access to
  1.1956 +  // AddTestPartResult.
  1.1957 +  UnitTest::GetInstance()->AddTestPartResult(
  1.1958 +      result_type,
  1.1959 +      NULL,  // No info about the source file where the exception occurred.
  1.1960 +      -1,    // We have no info on which line caused the exception.
  1.1961 +      message,
  1.1962 +      String());  // No stack trace, either.
  1.1963 +}
  1.1964 +
  1.1965 +}  // namespace internal
  1.1966 +
  1.1967 +// Google Test requires all tests in the same test case to use the same test
  1.1968 +// fixture class.  This function checks if the current test has the
  1.1969 +// same fixture class as the first test in the current test case.  If
  1.1970 +// yes, it returns true; otherwise it generates a Google Test failure and
  1.1971 +// returns false.
  1.1972 +bool Test::HasSameFixtureClass() {
  1.1973 +  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  1.1974 +  const TestCase* const test_case = impl->current_test_case();
  1.1975 +
  1.1976 +  // Info about the first test in the current test case.
  1.1977 +  const TestInfo* const first_test_info = test_case->test_info_list()[0];
  1.1978 +  const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_;
  1.1979 +  const char* const first_test_name = first_test_info->name();
  1.1980 +
  1.1981 +  // Info about the current test.
  1.1982 +  const TestInfo* const this_test_info = impl->current_test_info();
  1.1983 +  const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_;
  1.1984 +  const char* const this_test_name = this_test_info->name();
  1.1985 +
  1.1986 +  if (this_fixture_id != first_fixture_id) {
  1.1987 +    // Is the first test defined using TEST?
  1.1988 +    const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();
  1.1989 +    // Is this test defined using TEST?
  1.1990 +    const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();
  1.1991 +
  1.1992 +    if (first_is_TEST || this_is_TEST) {
  1.1993 +      // The user mixed TEST and TEST_F in this test case - we'll tell
  1.1994 +      // him/her how to fix it.
  1.1995 +
  1.1996 +      // Gets the name of the TEST and the name of the TEST_F.  Note
  1.1997 +      // that first_is_TEST and this_is_TEST cannot both be true, as
  1.1998 +      // the fixture IDs are different for the two tests.
  1.1999 +      const char* const TEST_name =
  1.2000 +          first_is_TEST ? first_test_name : this_test_name;
  1.2001 +      const char* const TEST_F_name =
  1.2002 +          first_is_TEST ? this_test_name : first_test_name;
  1.2003 +
  1.2004 +      ADD_FAILURE()
  1.2005 +          << "All tests in the same test case must use the same test fixture\n"
  1.2006 +          << "class, so mixing TEST_F and TEST in the same test case is\n"
  1.2007 +          << "illegal.  In test case " << this_test_info->test_case_name()
  1.2008 +          << ",\n"
  1.2009 +          << "test " << TEST_F_name << " is defined using TEST_F but\n"
  1.2010 +          << "test " << TEST_name << " is defined using TEST.  You probably\n"
  1.2011 +          << "want to change the TEST to TEST_F or move it to another test\n"
  1.2012 +          << "case.";
  1.2013 +    } else {
  1.2014 +      // The user defined two fixture classes with the same name in
  1.2015 +      // two namespaces - we'll tell him/her how to fix it.
  1.2016 +      ADD_FAILURE()
  1.2017 +          << "All tests in the same test case must use the same test fixture\n"
  1.2018 +          << "class.  However, in test case "
  1.2019 +          << this_test_info->test_case_name() << ",\n"
  1.2020 +          << "you defined test " << first_test_name
  1.2021 +          << " and test " << this_test_name << "\n"
  1.2022 +          << "using two different test fixture classes.  This can happen if\n"
  1.2023 +          << "the two classes are from different namespaces or translation\n"
  1.2024 +          << "units and have the same name.  You should probably rename one\n"
  1.2025 +          << "of the classes to put the tests into different test cases.";
  1.2026 +    }
  1.2027 +    return false;
  1.2028 +  }
  1.2029 +
  1.2030 +  return true;
  1.2031 +}
  1.2032 +
  1.2033 +#if GTEST_HAS_SEH
  1.2034 +
  1.2035 +// Adds an "exception thrown" fatal failure to the current test.  This
  1.2036 +// function returns its result via an output parameter pointer because VC++
  1.2037 +// prohibits creation of objects with destructors on stack in functions
  1.2038 +// using __try (see error C2712).
  1.2039 +static internal::String* FormatSehExceptionMessage(DWORD exception_code,
  1.2040 +                                                   const char* location) {
  1.2041 +  Message message;
  1.2042 +  message << "SEH exception with code 0x" << std::setbase(16) <<
  1.2043 +    exception_code << std::setbase(10) << " thrown in " << location << ".";
  1.2044 +
  1.2045 +  return new internal::String(message.GetString());
  1.2046 +}
  1.2047 +
  1.2048 +#endif  // GTEST_HAS_SEH
  1.2049 +
  1.2050 +#if GTEST_HAS_EXCEPTIONS
  1.2051 +
  1.2052 +// Adds an "exception thrown" fatal failure to the current test.
  1.2053 +static internal::String FormatCxxExceptionMessage(const char* description,
  1.2054 +                                                  const char* location) {
  1.2055 +  Message message;
  1.2056 +  if (description != NULL) {
  1.2057 +    message << "C++ exception with description \"" << description << "\"";
  1.2058 +  } else {
  1.2059 +    message << "Unknown C++ exception";
  1.2060 +  }
  1.2061 +  message << " thrown in " << location << ".";
  1.2062 +
  1.2063 +  return message.GetString();
  1.2064 +}
  1.2065 +
  1.2066 +static internal::String PrintTestPartResultToString(
  1.2067 +    const TestPartResult& test_part_result);
  1.2068 +
  1.2069 +// A failed Google Test assertion will throw an exception of this type when
  1.2070 +// GTEST_FLAG(throw_on_failure) is true (if exceptions are enabled).  We
  1.2071 +// derive it from std::runtime_error, which is for errors presumably
  1.2072 +// detectable only at run time.  Since std::runtime_error inherits from
  1.2073 +// std::exception, many testing frameworks know how to extract and print the
  1.2074 +// message inside it.
  1.2075 +class GoogleTestFailureException : public ::std::runtime_error {
  1.2076 + public:
  1.2077 +  explicit GoogleTestFailureException(const TestPartResult& failure)
  1.2078 +      : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
  1.2079 +};
  1.2080 +#endif  // GTEST_HAS_EXCEPTIONS
  1.2081 +
  1.2082 +namespace internal {
  1.2083 +// We put these helper functions in the internal namespace as IBM's xlC
  1.2084 +// compiler rejects the code if they were declared static.
  1.2085 +
  1.2086 +// Runs the given method and handles SEH exceptions it throws, when
  1.2087 +// SEH is supported; returns the 0-value for type Result in case of an
  1.2088 +// SEH exception.  (Microsoft compilers cannot handle SEH and C++
  1.2089 +// exceptions in the same function.  Therefore, we provide a separate
  1.2090 +// wrapper function for handling SEH exceptions.)
  1.2091 +template <class T, typename Result>
  1.2092 +Result HandleSehExceptionsInMethodIfSupported(
  1.2093 +    T* object, Result (T::*method)(), const char* location) {
  1.2094 +#if GTEST_HAS_SEH
  1.2095 +  __try {
  1.2096 +    return (object->*method)();
  1.2097 +  } __except (internal::UnitTestOptions::GTestShouldProcessSEH(  // NOLINT
  1.2098 +      GetExceptionCode())) {
  1.2099 +    // We create the exception message on the heap because VC++ prohibits
  1.2100 +    // creation of objects with destructors on stack in functions using __try
  1.2101 +    // (see error C2712).
  1.2102 +    internal::String* exception_message = FormatSehExceptionMessage(
  1.2103 +        GetExceptionCode(), location);
  1.2104 +    internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
  1.2105 +                                             *exception_message);
  1.2106 +    delete exception_message;
  1.2107 +    return static_cast<Result>(0);
  1.2108 +  }
  1.2109 +#else
  1.2110 +  (void)location;
  1.2111 +  return (object->*method)();
  1.2112 +#endif  // GTEST_HAS_SEH
  1.2113 +}
  1.2114 +
  1.2115 +// Runs the given method and catches and reports C++ and/or SEH-style
  1.2116 +// exceptions, if they are supported; returns the 0-value for type
  1.2117 +// Result in case of an SEH exception.
  1.2118 +template <class T, typename Result>
  1.2119 +Result HandleExceptionsInMethodIfSupported(
  1.2120 +    T* object, Result (T::*method)(), const char* location) {
  1.2121 +  // NOTE: The user code can affect the way in which Google Test handles
  1.2122 +  // exceptions by setting GTEST_FLAG(catch_exceptions), but only before
  1.2123 +  // RUN_ALL_TESTS() starts. It is technically possible to check the flag
  1.2124 +  // after the exception is caught and either report or re-throw the
  1.2125 +  // exception based on the flag's value:
  1.2126 +  //
  1.2127 +  // try {
  1.2128 +  //   // Perform the test method.
  1.2129 +  // } catch (...) {
  1.2130 +  //   if (GTEST_FLAG(catch_exceptions))
  1.2131 +  //     // Report the exception as failure.
  1.2132 +  //   else
  1.2133 +  //     throw;  // Re-throws the original exception.
  1.2134 +  // }
  1.2135 +  //
  1.2136 +  // However, the purpose of this flag is to allow the program to drop into
  1.2137 +  // the debugger when the exception is thrown. On most platforms, once the
  1.2138 +  // control enters the catch block, the exception origin information is
  1.2139 +  // lost and the debugger will stop the program at the point of the
  1.2140 +  // re-throw in this function -- instead of at the point of the original
  1.2141 +  // throw statement in the code under test.  For this reason, we perform
  1.2142 +  // the check early, sacrificing the ability to affect Google Test's
  1.2143 +  // exception handling in the method where the exception is thrown.
  1.2144 +  if (internal::GetUnitTestImpl()->catch_exceptions()) {
  1.2145 +#if GTEST_HAS_EXCEPTIONS
  1.2146 +    try {
  1.2147 +      return HandleSehExceptionsInMethodIfSupported(object, method, location);
  1.2148 +    } catch (const GoogleTestFailureException&) {  // NOLINT
  1.2149 +      // This exception doesn't originate in code under test. It makes no
  1.2150 +      // sense to report it as a test failure.
  1.2151 +      throw;
  1.2152 +    } catch (const std::exception& e) {  // NOLINT
  1.2153 +      internal::ReportFailureInUnknownLocation(
  1.2154 +          TestPartResult::kFatalFailure,
  1.2155 +          FormatCxxExceptionMessage(e.what(), location));
  1.2156 +    } catch (...) {  // NOLINT
  1.2157 +      internal::ReportFailureInUnknownLocation(
  1.2158 +          TestPartResult::kFatalFailure,
  1.2159 +          FormatCxxExceptionMessage(NULL, location));
  1.2160 +    }
  1.2161 +    return static_cast<Result>(0);
  1.2162 +#else
  1.2163 +    return HandleSehExceptionsInMethodIfSupported(object, method, location);
  1.2164 +#endif  // GTEST_HAS_EXCEPTIONS
  1.2165 +  } else {
  1.2166 +    return (object->*method)();
  1.2167 +  }
  1.2168 +}
  1.2169 +
  1.2170 +}  // namespace internal
  1.2171 +
  1.2172 +// Runs the test and updates the test result.
  1.2173 +void Test::Run() {
  1.2174 +  if (!HasSameFixtureClass()) return;
  1.2175 +
  1.2176 +  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  1.2177 +  impl->os_stack_trace_getter()->UponLeavingGTest();
  1.2178 +  internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()");
  1.2179 +  // We will run the test only if SetUp() was successful.
  1.2180 +  if (!HasFatalFailure()) {
  1.2181 +    impl->os_stack_trace_getter()->UponLeavingGTest();
  1.2182 +    internal::HandleExceptionsInMethodIfSupported(
  1.2183 +        this, &Test::TestBody, "the test body");
  1.2184 +  }
  1.2185 +
  1.2186 +  // However, we want to clean up as much as possible.  Hence we will
  1.2187 +  // always call TearDown(), even if SetUp() or the test body has
  1.2188 +  // failed.
  1.2189 +  impl->os_stack_trace_getter()->UponLeavingGTest();
  1.2190 +  internal::HandleExceptionsInMethodIfSupported(
  1.2191 +      this, &Test::TearDown, "TearDown()");
  1.2192 +}
  1.2193 +
  1.2194 +// Returns true iff the current test has a fatal failure.
  1.2195 +bool Test::HasFatalFailure() {
  1.2196 +  return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
  1.2197 +}
  1.2198 +
  1.2199 +// Returns true iff the current test has a non-fatal failure.
  1.2200 +bool Test::HasNonfatalFailure() {
  1.2201 +  return internal::GetUnitTestImpl()->current_test_result()->
  1.2202 +      HasNonfatalFailure();
  1.2203 +}
  1.2204 +
  1.2205 +// class TestInfo
  1.2206 +
  1.2207 +// Constructs a TestInfo object. It assumes ownership of the test factory
  1.2208 +// object.
  1.2209 +// TODO(vladl@google.com): Make a_test_case_name and a_name const string&'s
  1.2210 +// to signify they cannot be NULLs.
  1.2211 +TestInfo::TestInfo(const char* a_test_case_name,
  1.2212 +                   const char* a_name,
  1.2213 +                   const char* a_type_param,
  1.2214 +                   const char* a_value_param,
  1.2215 +                   internal::TypeId fixture_class_id,
  1.2216 +                   internal::TestFactoryBase* factory)
  1.2217 +    : test_case_name_(a_test_case_name),
  1.2218 +      name_(a_name),
  1.2219 +      type_param_(a_type_param ? new std::string(a_type_param) : NULL),
  1.2220 +      value_param_(a_value_param ? new std::string(a_value_param) : NULL),
  1.2221 +      fixture_class_id_(fixture_class_id),
  1.2222 +      should_run_(false),
  1.2223 +      is_disabled_(false),
  1.2224 +      matches_filter_(false),
  1.2225 +      factory_(factory),
  1.2226 +      result_() {}
  1.2227 +
  1.2228 +// Destructs a TestInfo object.
  1.2229 +TestInfo::~TestInfo() { delete factory_; }
  1.2230 +
  1.2231 +namespace internal {
  1.2232 +
  1.2233 +// Creates a new TestInfo object and registers it with Google Test;
  1.2234 +// returns the created object.
  1.2235 +//
  1.2236 +// Arguments:
  1.2237 +//
  1.2238 +//   test_case_name:   name of the test case
  1.2239 +//   name:             name of the test
  1.2240 +//   type_param:       the name of the test's type parameter, or NULL if
  1.2241 +//                     this is not a typed or a type-parameterized test.
  1.2242 +//   value_param:      text representation of the test's value parameter,
  1.2243 +//                     or NULL if this is not a value-parameterized test.
  1.2244 +//   fixture_class_id: ID of the test fixture class
  1.2245 +//   set_up_tc:        pointer to the function that sets up the test case
  1.2246 +//   tear_down_tc:     pointer to the function that tears down the test case
  1.2247 +//   factory:          pointer to the factory that creates a test object.
  1.2248 +//                     The newly created TestInfo instance will assume
  1.2249 +//                     ownership of the factory object.
  1.2250 +TestInfo* MakeAndRegisterTestInfo(
  1.2251 +    const char* test_case_name, const char* name,
  1.2252 +    const char* type_param,
  1.2253 +    const char* value_param,
  1.2254 +    TypeId fixture_class_id,
  1.2255 +    SetUpTestCaseFunc set_up_tc,
  1.2256 +    TearDownTestCaseFunc tear_down_tc,
  1.2257 +    TestFactoryBase* factory) {
  1.2258 +  TestInfo* const test_info =
  1.2259 +      new TestInfo(test_case_name, name, type_param, value_param,
  1.2260 +                   fixture_class_id, factory);
  1.2261 +  GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
  1.2262 +  return test_info;
  1.2263 +}
  1.2264 +
  1.2265 +#if GTEST_HAS_PARAM_TEST
  1.2266 +void ReportInvalidTestCaseType(const char* test_case_name,
  1.2267 +                               const char* file, int line) {
  1.2268 +  Message errors;
  1.2269 +  errors
  1.2270 +      << "Attempted redefinition of test case " << test_case_name << ".\n"
  1.2271 +      << "All tests in the same test case must use the same test fixture\n"
  1.2272 +      << "class.  However, in test case " << test_case_name << ", you tried\n"
  1.2273 +      << "to define a test using a fixture class different from the one\n"
  1.2274 +      << "used earlier. This can happen if the two fixture classes are\n"
  1.2275 +      << "from different namespaces and have the same name. You should\n"
  1.2276 +      << "probably rename one of the classes to put the tests into different\n"
  1.2277 +      << "test cases.";
  1.2278 +
  1.2279 +  fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
  1.2280 +          errors.GetString().c_str());
  1.2281 +}
  1.2282 +#endif  // GTEST_HAS_PARAM_TEST
  1.2283 +
  1.2284 +}  // namespace internal
  1.2285 +
  1.2286 +namespace {
  1.2287 +
  1.2288 +// A predicate that checks the test name of a TestInfo against a known
  1.2289 +// value.
  1.2290 +//
  1.2291 +// This is used for implementation of the TestCase class only.  We put
  1.2292 +// it in the anonymous namespace to prevent polluting the outer
  1.2293 +// namespace.
  1.2294 +//
  1.2295 +// TestNameIs is copyable.
  1.2296 +class TestNameIs {
  1.2297 + public:
  1.2298 +  // Constructor.
  1.2299 +  //
  1.2300 +  // TestNameIs has NO default constructor.
  1.2301 +  explicit TestNameIs(const char* name)
  1.2302 +      : name_(name) {}
  1.2303 +
  1.2304 +  // Returns true iff the test name of test_info matches name_.
  1.2305 +  bool operator()(const TestInfo * test_info) const {
  1.2306 +    return test_info && internal::String(test_info->name()).Compare(name_) == 0;
  1.2307 +  }
  1.2308 +
  1.2309 + private:
  1.2310 +  internal::String name_;
  1.2311 +};
  1.2312 +
  1.2313 +}  // namespace
  1.2314 +
  1.2315 +namespace internal {
  1.2316 +
  1.2317 +// This method expands all parameterized tests registered with macros TEST_P
  1.2318 +// and INSTANTIATE_TEST_CASE_P into regular tests and registers those.
  1.2319 +// This will be done just once during the program runtime.
  1.2320 +void UnitTestImpl::RegisterParameterizedTests() {
  1.2321 +#if GTEST_HAS_PARAM_TEST
  1.2322 +  if (!parameterized_tests_registered_) {
  1.2323 +    parameterized_test_registry_.RegisterTests();
  1.2324 +    parameterized_tests_registered_ = true;
  1.2325 +  }
  1.2326 +#endif
  1.2327 +}
  1.2328 +
  1.2329 +}  // namespace internal
  1.2330 +
  1.2331 +// Creates the test object, runs it, records its result, and then
  1.2332 +// deletes it.
  1.2333 +void TestInfo::Run() {
  1.2334 +  if (!should_run_) return;
  1.2335 +
  1.2336 +  // Tells UnitTest where to store test result.
  1.2337 +  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  1.2338 +  impl->set_current_test_info(this);
  1.2339 +
  1.2340 +  TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
  1.2341 +
  1.2342 +  // Notifies the unit test event listeners that a test is about to start.
  1.2343 +  repeater->OnTestStart(*this);
  1.2344 +
  1.2345 +  const TimeInMillis start = internal::GetTimeInMillis();
  1.2346 +
  1.2347 +  impl->os_stack_trace_getter()->UponLeavingGTest();
  1.2348 +
  1.2349 +  // Creates the test object.
  1.2350 +  Test* const test = internal::HandleExceptionsInMethodIfSupported(
  1.2351 +      factory_, &internal::TestFactoryBase::CreateTest,
  1.2352 +      "the test fixture's constructor");
  1.2353 +
  1.2354 +  // Runs the test only if the test object was created and its
  1.2355 +  // constructor didn't generate a fatal failure.
  1.2356 +  if ((test != NULL) && !Test::HasFatalFailure()) {
  1.2357 +    // This doesn't throw as all user code that can throw are wrapped into
  1.2358 +    // exception handling code.
  1.2359 +    test->Run();
  1.2360 +  }
  1.2361 +
  1.2362 +  // Deletes the test object.
  1.2363 +  impl->os_stack_trace_getter()->UponLeavingGTest();
  1.2364 +  internal::HandleExceptionsInMethodIfSupported(
  1.2365 +      test, &Test::DeleteSelf_, "the test fixture's destructor");
  1.2366 +
  1.2367 +  result_.set_elapsed_time(internal::GetTimeInMillis() - start);
  1.2368 +
  1.2369 +  // Notifies the unit test event listener that a test has just finished.
  1.2370 +  repeater->OnTestEnd(*this);
  1.2371 +
  1.2372 +  // Tells UnitTest to stop associating assertion results to this
  1.2373 +  // test.
  1.2374 +  impl->set_current_test_info(NULL);
  1.2375 +}
  1.2376 +
  1.2377 +// class TestCase
  1.2378 +
  1.2379 +// Gets the number of successful tests in this test case.
  1.2380 +int TestCase::successful_test_count() const {
  1.2381 +  return CountIf(test_info_list_, TestPassed);
  1.2382 +}
  1.2383 +
  1.2384 +// Gets the number of failed tests in this test case.
  1.2385 +int TestCase::failed_test_count() const {
  1.2386 +  return CountIf(test_info_list_, TestFailed);
  1.2387 +}
  1.2388 +
  1.2389 +int TestCase::disabled_test_count() const {
  1.2390 +  return CountIf(test_info_list_, TestDisabled);
  1.2391 +}
  1.2392 +
  1.2393 +// Get the number of tests in this test case that should run.
  1.2394 +int TestCase::test_to_run_count() const {
  1.2395 +  return CountIf(test_info_list_, ShouldRunTest);
  1.2396 +}
  1.2397 +
  1.2398 +// Gets the number of all tests.
  1.2399 +int TestCase::total_test_count() const {
  1.2400 +  return static_cast<int>(test_info_list_.size());
  1.2401 +}
  1.2402 +
  1.2403 +// Creates a TestCase with the given name.
  1.2404 +//
  1.2405 +// Arguments:
  1.2406 +//
  1.2407 +//   name:         name of the test case
  1.2408 +//   a_type_param: the name of the test case's type parameter, or NULL if
  1.2409 +//                 this is not a typed or a type-parameterized test case.
  1.2410 +//   set_up_tc:    pointer to the function that sets up the test case
  1.2411 +//   tear_down_tc: pointer to the function that tears down the test case
  1.2412 +TestCase::TestCase(const char* a_name, const char* a_type_param,
  1.2413 +                   Test::SetUpTestCaseFunc set_up_tc,
  1.2414 +                   Test::TearDownTestCaseFunc tear_down_tc)
  1.2415 +    : name_(a_name),
  1.2416 +      type_param_(a_type_param ? new std::string(a_type_param) : NULL),
  1.2417 +      set_up_tc_(set_up_tc),
  1.2418 +      tear_down_tc_(tear_down_tc),
  1.2419 +      should_run_(false),
  1.2420 +      elapsed_time_(0) {
  1.2421 +}
  1.2422 +
  1.2423 +// Destructor of TestCase.
  1.2424 +TestCase::~TestCase() {
  1.2425 +  // Deletes every Test in the collection.
  1.2426 +  ForEach(test_info_list_, internal::Delete<TestInfo>);
  1.2427 +}
  1.2428 +
  1.2429 +// Returns the i-th test among all the tests. i can range from 0 to
  1.2430 +// total_test_count() - 1. If i is not in that range, returns NULL.
  1.2431 +const TestInfo* TestCase::GetTestInfo(int i) const {
  1.2432 +  const int index = GetElementOr(test_indices_, i, -1);
  1.2433 +  return index < 0 ? NULL : test_info_list_[index];
  1.2434 +}
  1.2435 +
  1.2436 +// Returns the i-th test among all the tests. i can range from 0 to
  1.2437 +// total_test_count() - 1. If i is not in that range, returns NULL.
  1.2438 +TestInfo* TestCase::GetMutableTestInfo(int i) {
  1.2439 +  const int index = GetElementOr(test_indices_, i, -1);
  1.2440 +  return index < 0 ? NULL : test_info_list_[index];
  1.2441 +}
  1.2442 +
  1.2443 +// Adds a test to this test case.  Will delete the test upon
  1.2444 +// destruction of the TestCase object.
  1.2445 +void TestCase::AddTestInfo(TestInfo * test_info) {
  1.2446 +  test_info_list_.push_back(test_info);
  1.2447 +  test_indices_.push_back(static_cast<int>(test_indices_.size()));
  1.2448 +}
  1.2449 +
  1.2450 +// Runs every test in this TestCase.
  1.2451 +void TestCase::Run() {
  1.2452 +  if (!should_run_) return;
  1.2453 +
  1.2454 +  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
  1.2455 +  impl->set_current_test_case(this);
  1.2456 +
  1.2457 +  TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
  1.2458 +
  1.2459 +  repeater->OnTestCaseStart(*this);
  1.2460 +  impl->os_stack_trace_getter()->UponLeavingGTest();
  1.2461 +  internal::HandleExceptionsInMethodIfSupported(
  1.2462 +      this, &TestCase::RunSetUpTestCase, "SetUpTestCase()");
  1.2463 +
  1.2464 +  const internal::TimeInMillis start = internal::GetTimeInMillis();
  1.2465 +  for (int i = 0; i < total_test_count(); i++) {
  1.2466 +    GetMutableTestInfo(i)->Run();
  1.2467 +  }
  1.2468 +  elapsed_time_ = internal::GetTimeInMillis() - start;
  1.2469 +
  1.2470 +  impl->os_stack_trace_getter()->UponLeavingGTest();
  1.2471 +  internal::HandleExceptionsInMethodIfSupported(
  1.2472 +      this, &TestCase::RunTearDownTestCase, "TearDownTestCase()");
  1.2473 +
  1.2474 +  repeater->OnTestCaseEnd(*this);
  1.2475 +  impl->set_current_test_case(NULL);
  1.2476 +}
  1.2477 +
  1.2478 +// Clears the results of all tests in this test case.
  1.2479 +void TestCase::ClearResult() {
  1.2480 +  ForEach(test_info_list_, TestInfo::ClearTestResult);
  1.2481 +}
  1.2482 +
  1.2483 +// Shuffles the tests in this test case.
  1.2484 +void TestCase::ShuffleTests(internal::Random* random) {
  1.2485 +  Shuffle(random, &test_indices_);
  1.2486 +}
  1.2487 +
  1.2488 +// Restores the test order to before the first shuffle.
  1.2489 +void TestCase::UnshuffleTests() {
  1.2490 +  for (size_t i = 0; i < test_indices_.size(); i++) {
  1.2491 +    test_indices_[i] = static_cast<int>(i);
  1.2492 +  }
  1.2493 +}
  1.2494 +
  1.2495 +// Formats a countable noun.  Depending on its quantity, either the
  1.2496 +// singular form or the plural form is used. e.g.
  1.2497 +//
  1.2498 +// FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
  1.2499 +// FormatCountableNoun(5, "book", "books") returns "5 books".
  1.2500 +static internal::String FormatCountableNoun(int count,
  1.2501 +                                            const char * singular_form,
  1.2502 +                                            const char * plural_form) {
  1.2503 +  return internal::String::Format("%d %s", count,
  1.2504 +                                  count == 1 ? singular_form : plural_form);
  1.2505 +}
  1.2506 +
  1.2507 +// Formats the count of tests.
  1.2508 +static internal::String FormatTestCount(int test_count) {
  1.2509 +  return FormatCountableNoun(test_count, "test", "tests");
  1.2510 +}
  1.2511 +
  1.2512 +// Formats the count of test cases.
  1.2513 +static internal::String FormatTestCaseCount(int test_case_count) {
  1.2514 +  return FormatCountableNoun(test_case_count, "test case", "test cases");
  1.2515 +}
  1.2516 +
  1.2517 +// Converts a TestPartResult::Type enum to human-friendly string
  1.2518 +// representation.  Both kNonFatalFailure and kFatalFailure are translated
  1.2519 +// to "Failure", as the user usually doesn't care about the difference
  1.2520 +// between the two when viewing the test result.
  1.2521 +static const char * TestPartResultTypeToString(TestPartResult::Type type) {
  1.2522 +  switch (type) {
  1.2523 +    case TestPartResult::kSuccess:
  1.2524 +      return "Success";
  1.2525 +
  1.2526 +    case TestPartResult::kNonFatalFailure:
  1.2527 +    case TestPartResult::kFatalFailure:
  1.2528 +#ifdef _MSC_VER
  1.2529 +      return "error: ";
  1.2530 +#else
  1.2531 +      return "Failure\n";
  1.2532 +#endif
  1.2533 +    default:
  1.2534 +      return "Unknown result type";
  1.2535 +  }
  1.2536 +}
  1.2537 +
  1.2538 +// Prints a TestPartResult to a String.
  1.2539 +static internal::String PrintTestPartResultToString(
  1.2540 +    const TestPartResult& test_part_result) {
  1.2541 +  return (Message()
  1.2542 +          << internal::FormatFileLocation(test_part_result.file_name(),
  1.2543 +                                          test_part_result.line_number())
  1.2544 +          << " " << TestPartResultTypeToString(test_part_result.type())
  1.2545 +          << test_part_result.message()).GetString();
  1.2546 +}
  1.2547 +
  1.2548 +// Prints a TestPartResult.
  1.2549 +static void PrintTestPartResult(const TestPartResult& test_part_result) {
  1.2550 +  const internal::String& result =
  1.2551 +      PrintTestPartResultToString(test_part_result);
  1.2552 +  printf("%s\n", result.c_str());
  1.2553 +  fflush(stdout);
  1.2554 +  // If the test program runs in Visual Studio or a debugger, the
  1.2555 +  // following statements add the test part result message to the Output
  1.2556 +  // window such that the user can double-click on it to jump to the
  1.2557 +  // corresponding source code location; otherwise they do nothing.
  1.2558 +#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
  1.2559 +  // We don't call OutputDebugString*() on Windows Mobile, as printing
  1.2560 +  // to stdout is done by OutputDebugString() there already - we don't
  1.2561 +  // want the same message printed twice.
  1.2562 +  ::OutputDebugStringA(result.c_str());
  1.2563 +  ::OutputDebugStringA("\n");
  1.2564 +#endif
  1.2565 +}
  1.2566 +
  1.2567 +// class PrettyUnitTestResultPrinter
  1.2568 +
  1.2569 +namespace internal {
  1.2570 +
  1.2571 +enum GTestColor {
  1.2572 +  COLOR_DEFAULT,
  1.2573 +  COLOR_RED,
  1.2574 +  COLOR_GREEN,
  1.2575 +  COLOR_YELLOW
  1.2576 +};
  1.2577 +
  1.2578 +#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
  1.2579 +
  1.2580 +// Returns the character attribute for the given color.
  1.2581 +WORD GetColorAttribute(GTestColor color) {
  1.2582 +  switch (color) {
  1.2583 +    case COLOR_RED:    return FOREGROUND_RED;
  1.2584 +    case COLOR_GREEN:  return FOREGROUND_GREEN;
  1.2585 +    case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
  1.2586 +    default:           return 0;
  1.2587 +  }
  1.2588 +}
  1.2589 +
  1.2590 +#else
  1.2591 +
  1.2592 +// Returns the ANSI color code for the given color.  COLOR_DEFAULT is
  1.2593 +// an invalid input.
  1.2594 +const char* GetAnsiColorCode(GTestColor color) {
  1.2595 +  switch (color) {
  1.2596 +    case COLOR_RED:     return "1";
  1.2597 +    case COLOR_GREEN:   return "2";
  1.2598 +    case COLOR_YELLOW:  return "3";
  1.2599 +    default:            return NULL;
  1.2600 +  };
  1.2601 +}
  1.2602 +
  1.2603 +#endif  // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
  1.2604 +
  1.2605 +// Returns true iff Google Test should use colors in the output.
  1.2606 +bool ShouldUseColor(bool stdout_is_tty) {
  1.2607 +  const char* const gtest_color = GTEST_FLAG(color).c_str();
  1.2608 +
  1.2609 +  if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
  1.2610 +#if GTEST_OS_WINDOWS
  1.2611 +    // On Windows the TERM variable is usually not set, but the
  1.2612 +    // console there does support colors.
  1.2613 +    return stdout_is_tty;
  1.2614 +#else
  1.2615 +    // On non-Windows platforms, we rely on the TERM variable.
  1.2616 +    const char* const term = posix::GetEnv("TERM");
  1.2617 +    const bool term_supports_color =
  1.2618 +        String::CStringEquals(term, "xterm") ||
  1.2619 +        String::CStringEquals(term, "xterm-color") ||
  1.2620 +        String::CStringEquals(term, "xterm-256color") ||
  1.2621 +        String::CStringEquals(term, "screen") ||
  1.2622 +        String::CStringEquals(term, "linux") ||
  1.2623 +        String::CStringEquals(term, "cygwin");
  1.2624 +    return stdout_is_tty && term_supports_color;
  1.2625 +#endif  // GTEST_OS_WINDOWS
  1.2626 +  }
  1.2627 +
  1.2628 +  return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
  1.2629 +      String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
  1.2630 +      String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
  1.2631 +      String::CStringEquals(gtest_color, "1");
  1.2632 +  // We take "yes", "true", "t", and "1" as meaning "yes".  If the
  1.2633 +  // value is neither one of these nor "auto", we treat it as "no" to
  1.2634 +  // be conservative.
  1.2635 +}
  1.2636 +
  1.2637 +// Helpers for printing colored strings to stdout. Note that on Windows, we
  1.2638 +// cannot simply emit special characters and have the terminal change colors.
  1.2639 +// This routine must actually emit the characters rather than return a string
  1.2640 +// that would be colored when printed, as can be done on Linux.
  1.2641 +void ColoredPrintf(GTestColor color, const char* fmt, ...) {
  1.2642 +  va_list args;
  1.2643 +  va_start(args, fmt);
  1.2644 +
  1.2645 +#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS || GTEST_OS_IOS
  1.2646 +  const bool use_color = false;
  1.2647 +#else
  1.2648 +  static const bool in_color_mode =
  1.2649 +      ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
  1.2650 +  const bool use_color = in_color_mode && (color != COLOR_DEFAULT);
  1.2651 +#endif  // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
  1.2652 +  // The '!= 0' comparison is necessary to satisfy MSVC 7.1.
  1.2653 +
  1.2654 +  if (!use_color) {
  1.2655 +    vprintf(fmt, args);
  1.2656 +    va_end(args);
  1.2657 +    return;
  1.2658 +  }
  1.2659 +
  1.2660 +#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
  1.2661 +  const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
  1.2662 +
  1.2663 +  // Gets the current text color.
  1.2664 +  CONSOLE_SCREEN_BUFFER_INFO buffer_info;
  1.2665 +  GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
  1.2666 +  const WORD old_color_attrs = buffer_info.wAttributes;
  1.2667 +
  1.2668 +  // We need to flush the stream buffers into the console before each
  1.2669 +  // SetConsoleTextAttribute call lest it affect the text that is already
  1.2670 +  // printed but has not yet reached the console.
  1.2671 +  fflush(stdout);
  1.2672 +  SetConsoleTextAttribute(stdout_handle,
  1.2673 +                          GetColorAttribute(color) | FOREGROUND_INTENSITY);
  1.2674 +  vprintf(fmt, args);
  1.2675 +
  1.2676 +  fflush(stdout);
  1.2677 +  // Restores the text color.
  1.2678 +  SetConsoleTextAttribute(stdout_handle, old_color_attrs);
  1.2679 +#else
  1.2680 +  printf("\033[0;3%sm", GetAnsiColorCode(color));
  1.2681 +  vprintf(fmt, args);
  1.2682 +  printf("\033[m");  // Resets the terminal to default.
  1.2683 +#endif  // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
  1.2684 +  va_end(args);
  1.2685 +}
  1.2686 +
  1.2687 +void PrintFullTestCommentIfPresent(const TestInfo& test_info) {
  1.2688 +  const char* const type_param = test_info.type_param();
  1.2689 +  const char* const value_param = test_info.value_param();
  1.2690 +
  1.2691 +  if (type_param != NULL || value_param != NULL) {
  1.2692 +    printf(", where ");
  1.2693 +    if (type_param != NULL) {
  1.2694 +      printf("TypeParam = %s", type_param);
  1.2695 +      if (value_param != NULL)
  1.2696 +        printf(" and ");
  1.2697 +    }
  1.2698 +    if (value_param != NULL) {
  1.2699 +      printf("GetParam() = %s", value_param);
  1.2700 +    }
  1.2701 +  }
  1.2702 +}
  1.2703 +
  1.2704 +// This class implements the TestEventListener interface.
  1.2705 +//
  1.2706 +// Class PrettyUnitTestResultPrinter is copyable.
  1.2707 +class PrettyUnitTestResultPrinter : public TestEventListener {
  1.2708 + public:
  1.2709 +  PrettyUnitTestResultPrinter() {}
  1.2710 +  static void PrintTestName(const char * test_case, const char * test) {
  1.2711 +    printf("%s.%s", test_case, test);
  1.2712 +  }
  1.2713 +
  1.2714 +  // The following methods override what's in the TestEventListener class.
  1.2715 +  virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {}
  1.2716 +  virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
  1.2717 +  virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
  1.2718 +  virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {}
  1.2719 +  virtual void OnTestCaseStart(const TestCase& test_case);
  1.2720 +  virtual void OnTestStart(const TestInfo& test_info);
  1.2721 +  virtual void OnTestPartResult(const TestPartResult& result);
  1.2722 +  virtual void OnTestEnd(const TestInfo& test_info);
  1.2723 +  virtual void OnTestCaseEnd(const TestCase& test_case);
  1.2724 +  virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
  1.2725 +  virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {}
  1.2726 +  virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
  1.2727 +  virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {}
  1.2728 +
  1.2729 + private:
  1.2730 +  static void PrintFailedTests(const UnitTest& unit_test);
  1.2731 +};
  1.2732 +
  1.2733 +  // Fired before each iteration of tests starts.
  1.2734 +void PrettyUnitTestResultPrinter::OnTestIterationStart(
  1.2735 +    const UnitTest& unit_test, int iteration) {
  1.2736 +  if (GTEST_FLAG(repeat) != 1)
  1.2737 +    printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
  1.2738 +
  1.2739 +  const char* const filter = GTEST_FLAG(filter).c_str();
  1.2740 +
  1.2741 +  // Prints the filter if it's not *.  This reminds the user that some
  1.2742 +  // tests may be skipped.
  1.2743 +  if (!internal::String::CStringEquals(filter, kUniversalFilter)) {
  1.2744 +    ColoredPrintf(COLOR_YELLOW,
  1.2745 +                  "Note: %s filter = %s\n", GTEST_NAME_, filter);
  1.2746 +  }
  1.2747 +
  1.2748 +  if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
  1.2749 +    const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
  1.2750 +    ColoredPrintf(COLOR_YELLOW,
  1.2751 +                  "Note: This is test shard %d of %s.\n",
  1.2752 +                  static_cast<int>(shard_index) + 1,
  1.2753 +                  internal::posix::GetEnv(kTestTotalShards));
  1.2754 +  }
  1.2755 +
  1.2756 +  if (GTEST_FLAG(shuffle)) {
  1.2757 +    ColoredPrintf(COLOR_YELLOW,
  1.2758 +                  "Note: Randomizing tests' orders with a seed of %d .\n",
  1.2759 +                  unit_test.random_seed());
  1.2760 +  }
  1.2761 +
  1.2762 +  ColoredPrintf(COLOR_GREEN,  "[==========] ");
  1.2763 +  printf("Running %s from %s.\n",
  1.2764 +         FormatTestCount(unit_test.test_to_run_count()).c_str(),
  1.2765 +         FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
  1.2766 +  fflush(stdout);
  1.2767 +}
  1.2768 +
  1.2769 +void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
  1.2770 +    const UnitTest& /*unit_test*/) {
  1.2771 +  ColoredPrintf(COLOR_GREEN,  "[----------] ");
  1.2772 +  printf("Global test environment set-up.\n");
  1.2773 +  fflush(stdout);
  1.2774 +}
  1.2775 +
  1.2776 +void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {
  1.2777 +  const internal::String counts =
  1.2778 +      FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
  1.2779 +  ColoredPrintf(COLOR_GREEN, "[----------] ");
  1.2780 +  printf("%s from %s", counts.c_str(), test_case.name());
  1.2781 +  if (test_case.type_param() == NULL) {
  1.2782 +    printf("\n");
  1.2783 +  } else {
  1.2784 +    printf(", where TypeParam = %s\n", test_case.type_param());
  1.2785 +  }
  1.2786 +  fflush(stdout);
  1.2787 +}
  1.2788 +
  1.2789 +void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
  1.2790 +  ColoredPrintf(COLOR_GREEN,  "[ RUN      ] ");
  1.2791 +  PrintTestName(test_info.test_case_name(), test_info.name());
  1.2792 +  printf("\n");
  1.2793 +  fflush(stdout);
  1.2794 +}
  1.2795 +
  1.2796 +// Called after an assertion failure.
  1.2797 +void PrettyUnitTestResultPrinter::OnTestPartResult(
  1.2798 +    const TestPartResult& result) {
  1.2799 +  // If the test part succeeded, we don't need to do anything.
  1.2800 +  if (result.type() == TestPartResult::kSuccess)
  1.2801 +    return;
  1.2802 +
  1.2803 +  // Print failure message from the assertion (e.g. expected this and got that).
  1.2804 +  PrintTestPartResult(result);
  1.2805 +  fflush(stdout);
  1.2806 +}
  1.2807 +
  1.2808 +void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
  1.2809 +  if (test_info.result()->Passed()) {
  1.2810 +    ColoredPrintf(COLOR_GREEN, "[       OK ] ");
  1.2811 +  } else {
  1.2812 +    ColoredPrintf(COLOR_RED, "[  FAILED  ] ");
  1.2813 +  }
  1.2814 +  PrintTestName(test_info.test_case_name(), test_info.name());
  1.2815 +  if (test_info.result()->Failed())
  1.2816 +    PrintFullTestCommentIfPresent(test_info);
  1.2817 +
  1.2818 +  if (GTEST_FLAG(print_time)) {
  1.2819 +    printf(" (%s ms)\n", internal::StreamableToString(
  1.2820 +           test_info.result()->elapsed_time()).c_str());
  1.2821 +  } else {
  1.2822 +    printf("\n");
  1.2823 +  }
  1.2824 +  fflush(stdout);
  1.2825 +}
  1.2826 +
  1.2827 +void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {
  1.2828 +  if (!GTEST_FLAG(print_time)) return;
  1.2829 +
  1.2830 +  const internal::String counts =
  1.2831 +      FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
  1.2832 +  ColoredPrintf(COLOR_GREEN, "[----------] ");
  1.2833 +  printf("%s from %s (%s ms total)\n\n",
  1.2834 +         counts.c_str(), test_case.name(),
  1.2835 +         internal::StreamableToString(test_case.elapsed_time()).c_str());
  1.2836 +  fflush(stdout);
  1.2837 +}
  1.2838 +
  1.2839 +void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
  1.2840 +    const UnitTest& /*unit_test*/) {
  1.2841 +  ColoredPrintf(COLOR_GREEN,  "[----------] ");
  1.2842 +  printf("Global test environment tear-down\n");
  1.2843 +  fflush(stdout);
  1.2844 +}
  1.2845 +
  1.2846 +// Internal helper for printing the list of failed tests.
  1.2847 +void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
  1.2848 +  const int failed_test_count = unit_test.failed_test_count();
  1.2849 +  if (failed_test_count == 0) {
  1.2850 +    return;
  1.2851 +  }
  1.2852 +
  1.2853 +  for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
  1.2854 +    const TestCase& test_case = *unit_test.GetTestCase(i);
  1.2855 +    if (!test_case.should_run() || (test_case.failed_test_count() == 0)) {
  1.2856 +      continue;
  1.2857 +    }
  1.2858 +    for (int j = 0; j < test_case.total_test_count(); ++j) {
  1.2859 +      const TestInfo& test_info = *test_case.GetTestInfo(j);
  1.2860 +      if (!test_info.should_run() || test_info.result()->Passed()) {
  1.2861 +        continue;
  1.2862 +      }
  1.2863 +      ColoredPrintf(COLOR_RED, "[  FAILED  ] ");
  1.2864 +      printf("%s.%s", test_case.name(), test_info.name());
  1.2865 +      PrintFullTestCommentIfPresent(test_info);
  1.2866 +      printf("\n");
  1.2867 +    }
  1.2868 +  }
  1.2869 +}
  1.2870 +
  1.2871 +void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
  1.2872 +                                                     int /*iteration*/) {
  1.2873 +  ColoredPrintf(COLOR_GREEN,  "[==========] ");
  1.2874 +  printf("%s from %s ran.",
  1.2875 +         FormatTestCount(unit_test.test_to_run_count()).c_str(),
  1.2876 +         FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
  1.2877 +  if (GTEST_FLAG(print_time)) {
  1.2878 +    printf(" (%s ms total)",
  1.2879 +           internal::StreamableToString(unit_test.elapsed_time()).c_str());
  1.2880 +  }
  1.2881 +  printf("\n");
  1.2882 +  ColoredPrintf(COLOR_GREEN,  "[  PASSED  ] ");
  1.2883 +  printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
  1.2884 +
  1.2885 +  int num_failures = unit_test.failed_test_count();
  1.2886 +  if (!unit_test.Passed()) {
  1.2887 +    const int failed_test_count = unit_test.failed_test_count();
  1.2888 +    ColoredPrintf(COLOR_RED,  "[  FAILED  ] ");
  1.2889 +    printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
  1.2890 +    PrintFailedTests(unit_test);
  1.2891 +    printf("\n%2d FAILED %s\n", num_failures,
  1.2892 +                        num_failures == 1 ? "TEST" : "TESTS");
  1.2893 +  }
  1.2894 +
  1.2895 +  int num_disabled = unit_test.disabled_test_count();
  1.2896 +  if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
  1.2897 +    if (!num_failures) {
  1.2898 +      printf("\n");  // Add a spacer if no FAILURE banner is displayed.
  1.2899 +    }
  1.2900 +    ColoredPrintf(COLOR_YELLOW,
  1.2901 +                  "  YOU HAVE %d DISABLED %s\n\n",
  1.2902 +                  num_disabled,
  1.2903 +                  num_disabled == 1 ? "TEST" : "TESTS");
  1.2904 +  }
  1.2905 +  // Ensure that Google Test output is printed before, e.g., heapchecker output.
  1.2906 +  fflush(stdout);
  1.2907 +}
  1.2908 +
  1.2909 +// End PrettyUnitTestResultPrinter
  1.2910 +
  1.2911 +// class TestEventRepeater
  1.2912 +//
  1.2913 +// This class forwards events to other event listeners.
  1.2914 +class TestEventRepeater : public TestEventListener {
  1.2915 + public:
  1.2916 +  TestEventRepeater() : forwarding_enabled_(true) {}
  1.2917 +  virtual ~TestEventRepeater();
  1.2918 +  void Append(TestEventListener *listener);
  1.2919 +  TestEventListener* Release(TestEventListener* listener);
  1.2920 +
  1.2921 +  // Controls whether events will be forwarded to listeners_. Set to false
  1.2922 +  // in death test child processes.
  1.2923 +  bool forwarding_enabled() const { return forwarding_enabled_; }
  1.2924 +  void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }
  1.2925 +
  1.2926 +  virtual void OnTestProgramStart(const UnitTest& unit_test);
  1.2927 +  virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
  1.2928 +  virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
  1.2929 +  virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test);
  1.2930 +  virtual void OnTestCaseStart(const TestCase& test_case);
  1.2931 +  virtual void OnTestStart(const TestInfo& test_info);
  1.2932 +  virtual void OnTestPartResult(const TestPartResult& result);
  1.2933 +  virtual void OnTestEnd(const TestInfo& test_info);
  1.2934 +  virtual void OnTestCaseEnd(const TestCase& test_case);
  1.2935 +  virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
  1.2936 +  virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test);
  1.2937 +  virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
  1.2938 +  virtual void OnTestProgramEnd(const UnitTest& unit_test);
  1.2939 +
  1.2940 + private:
  1.2941 +  // Controls whether events will be forwarded to listeners_. Set to false
  1.2942 +  // in death test child processes.
  1.2943 +  bool forwarding_enabled_;
  1.2944 +  // The list of listeners that receive events.
  1.2945 +  std::vector<TestEventListener*> listeners_;
  1.2946 +
  1.2947 +  GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater);
  1.2948 +};
  1.2949 +
  1.2950 +TestEventRepeater::~TestEventRepeater() {
  1.2951 +  ForEach(listeners_, Delete<TestEventListener>);
  1.2952 +}
  1.2953 +
  1.2954 +void TestEventRepeater::Append(TestEventListener *listener) {
  1.2955 +  listeners_.push_back(listener);
  1.2956 +}
  1.2957 +
  1.2958 +// TODO(vladl@google.com): Factor the search functionality into Vector::Find.
  1.2959 +TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {
  1.2960 +  for (size_t i = 0; i < listeners_.size(); ++i) {
  1.2961 +    if (listeners_[i] == listener) {
  1.2962 +      listeners_.erase(listeners_.begin() + i);
  1.2963 +      return listener;
  1.2964 +    }
  1.2965 +  }
  1.2966 +
  1.2967 +  return NULL;
  1.2968 +}
  1.2969 +
  1.2970 +// Since most methods are very similar, use macros to reduce boilerplate.
  1.2971 +// This defines a member that forwards the call to all listeners.
  1.2972 +#define GTEST_REPEATER_METHOD_(Name, Type) \
  1.2973 +void TestEventRepeater::Name(const Type& parameter) { \
  1.2974 +  if (forwarding_enabled_) { \
  1.2975 +    for (size_t i = 0; i < listeners_.size(); i++) { \
  1.2976 +      listeners_[i]->Name(parameter); \
  1.2977 +    } \
  1.2978 +  } \
  1.2979 +}
  1.2980 +// This defines a member that forwards the call to all listeners in reverse
  1.2981 +// order.
  1.2982 +#define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
  1.2983 +void TestEventRepeater::Name(const Type& parameter) { \
  1.2984 +  if (forwarding_enabled_) { \
  1.2985 +    for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \
  1.2986 +      listeners_[i]->Name(parameter); \
  1.2987 +    } \
  1.2988 +  } \
  1.2989 +}
  1.2990 +
  1.2991 +GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)
  1.2992 +GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)
  1.2993 +GTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase)
  1.2994 +GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
  1.2995 +GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)
  1.2996 +GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)
  1.2997 +GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)
  1.2998 +GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)
  1.2999 +GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)
  1.3000 +GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestCase)
  1.3001 +GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)
  1.3002 +
  1.3003 +#undef GTEST_REPEATER_METHOD_
  1.3004 +#undef GTEST_REVERSE_REPEATER_METHOD_
  1.3005 +
  1.3006 +void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,
  1.3007 +                                             int iteration) {
  1.3008 +  if (forwarding_enabled_) {
  1.3009 +    for (size_t i = 0; i < listeners_.size(); i++) {
  1.3010 +      listeners_[i]->OnTestIterationStart(unit_test, iteration);
  1.3011 +    }
  1.3012 +  }
  1.3013 +}
  1.3014 +
  1.3015 +void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,
  1.3016 +                                           int iteration) {
  1.3017 +  if (forwarding_enabled_) {
  1.3018 +    for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) {
  1.3019 +      listeners_[i]->OnTestIterationEnd(unit_test, iteration);
  1.3020 +    }
  1.3021 +  }
  1.3022 +}
  1.3023 +
  1.3024 +// End TestEventRepeater
  1.3025 +
  1.3026 +// This class generates an XML output file.
  1.3027 +class XmlUnitTestResultPrinter : public EmptyTestEventListener {
  1.3028 + public:
  1.3029 +  explicit XmlUnitTestResultPrinter(const char* output_file);
  1.3030 +
  1.3031 +  virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
  1.3032 +
  1.3033 + private:
  1.3034 +  // Is c a whitespace character that is normalized to a space character
  1.3035 +  // when it appears in an XML attribute value?
  1.3036 +  static bool IsNormalizableWhitespace(char c) {
  1.3037 +    return c == 0x9 || c == 0xA || c == 0xD;
  1.3038 +  }
  1.3039 +
  1.3040 +  // May c appear in a well-formed XML document?
  1.3041 +  static bool IsValidXmlCharacter(char c) {
  1.3042 +    return IsNormalizableWhitespace(c) || c >= 0x20;
  1.3043 +  }
  1.3044 +
  1.3045 +  // Returns an XML-escaped copy of the input string str.  If
  1.3046 +  // is_attribute is true, the text is meant to appear as an attribute
  1.3047 +  // value, and normalizable whitespace is preserved by replacing it
  1.3048 +  // with character references.
  1.3049 +  static String EscapeXml(const char* str, bool is_attribute);
  1.3050 +
  1.3051 +  // Returns the given string with all characters invalid in XML removed.
  1.3052 +  static string RemoveInvalidXmlCharacters(const string& str);
  1.3053 +
  1.3054 +  // Convenience wrapper around EscapeXml when str is an attribute value.
  1.3055 +  static String EscapeXmlAttribute(const char* str) {
  1.3056 +    return EscapeXml(str, true);
  1.3057 +  }
  1.3058 +
  1.3059 +  // Convenience wrapper around EscapeXml when str is not an attribute value.
  1.3060 +  static String EscapeXmlText(const char* str) { return EscapeXml(str, false); }
  1.3061 +
  1.3062 +  // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
  1.3063 +  static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
  1.3064 +
  1.3065 +  // Streams an XML representation of a TestInfo object.
  1.3066 +  static void OutputXmlTestInfo(::std::ostream* stream,
  1.3067 +                                const char* test_case_name,
  1.3068 +                                const TestInfo& test_info);
  1.3069 +
  1.3070 +  // Prints an XML representation of a TestCase object
  1.3071 +  static void PrintXmlTestCase(FILE* out, const TestCase& test_case);
  1.3072 +
  1.3073 +  // Prints an XML summary of unit_test to output stream out.
  1.3074 +  static void PrintXmlUnitTest(FILE* out, const UnitTest& unit_test);
  1.3075 +
  1.3076 +  // Produces a string representing the test properties in a result as space
  1.3077 +  // delimited XML attributes based on the property key="value" pairs.
  1.3078 +  // When the String is not empty, it includes a space at the beginning,
  1.3079 +  // to delimit this attribute from prior attributes.
  1.3080 +  static String TestPropertiesAsXmlAttributes(const TestResult& result);
  1.3081 +
  1.3082 +  // The output file.
  1.3083 +  const String output_file_;
  1.3084 +
  1.3085 +  GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);
  1.3086 +};
  1.3087 +
  1.3088 +// Creates a new XmlUnitTestResultPrinter.
  1.3089 +XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
  1.3090 +    : output_file_(output_file) {
  1.3091 +  if (output_file_.c_str() == NULL || output_file_.empty()) {
  1.3092 +    fprintf(stderr, "XML output file may not be null\n");
  1.3093 +    fflush(stderr);
  1.3094 +    exit(EXIT_FAILURE);
  1.3095 +  }
  1.3096 +}
  1.3097 +
  1.3098 +// Called after the unit test ends.
  1.3099 +void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
  1.3100 +                                                  int /*iteration*/) {
  1.3101 +  FILE* xmlout = NULL;
  1.3102 +  FilePath output_file(output_file_);
  1.3103 +  FilePath output_dir(output_file.RemoveFileName());
  1.3104 +
  1.3105 +  if (output_dir.CreateDirectoriesRecursively()) {
  1.3106 +    xmlout = posix::FOpen(output_file_.c_str(), "w");
  1.3107 +  }
  1.3108 +  if (xmlout == NULL) {
  1.3109 +    // TODO(wan): report the reason of the failure.
  1.3110 +    //
  1.3111 +    // We don't do it for now as:
  1.3112 +    //
  1.3113 +    //   1. There is no urgent need for it.
  1.3114 +    //   2. It's a bit involved to make the errno variable thread-safe on
  1.3115 +    //      all three operating systems (Linux, Windows, and Mac OS).
  1.3116 +    //   3. To interpret the meaning of errno in a thread-safe way,
  1.3117 +    //      we need the strerror_r() function, which is not available on
  1.3118 +    //      Windows.
  1.3119 +    fprintf(stderr,
  1.3120 +            "Unable to open file \"%s\"\n",
  1.3121 +            output_file_.c_str());
  1.3122 +    fflush(stderr);
  1.3123 +    exit(EXIT_FAILURE);
  1.3124 +  }
  1.3125 +  PrintXmlUnitTest(xmlout, unit_test);
  1.3126 +  fclose(xmlout);
  1.3127 +}
  1.3128 +
  1.3129 +// Returns an XML-escaped copy of the input string str.  If is_attribute
  1.3130 +// is true, the text is meant to appear as an attribute value, and
  1.3131 +// normalizable whitespace is preserved by replacing it with character
  1.3132 +// references.
  1.3133 +//
  1.3134 +// Invalid XML characters in str, if any, are stripped from the output.
  1.3135 +// It is expected that most, if not all, of the text processed by this
  1.3136 +// module will consist of ordinary English text.
  1.3137 +// If this module is ever modified to produce version 1.1 XML output,
  1.3138 +// most invalid characters can be retained using character references.
  1.3139 +// TODO(wan): It might be nice to have a minimally invasive, human-readable
  1.3140 +// escaping scheme for invalid characters, rather than dropping them.
  1.3141 +String XmlUnitTestResultPrinter::EscapeXml(const char* str, bool is_attribute) {
  1.3142 +  Message m;
  1.3143 +
  1.3144 +  if (str != NULL) {
  1.3145 +    for (const char* src = str; *src; ++src) {
  1.3146 +      switch (*src) {
  1.3147 +        case '<':
  1.3148 +          m << "&lt;";
  1.3149 +          break;
  1.3150 +        case '>':
  1.3151 +          m << "&gt;";
  1.3152 +          break;
  1.3153 +        case '&':
  1.3154 +          m << "&amp;";
  1.3155 +          break;
  1.3156 +        case '\'':
  1.3157 +          if (is_attribute)
  1.3158 +            m << "&apos;";
  1.3159 +          else
  1.3160 +            m << '\'';
  1.3161 +          break;
  1.3162 +        case '"':
  1.3163 +          if (is_attribute)
  1.3164 +            m << "&quot;";
  1.3165 +          else
  1.3166 +            m << '"';
  1.3167 +          break;
  1.3168 +        default:
  1.3169 +          if (IsValidXmlCharacter(*src)) {
  1.3170 +            if (is_attribute && IsNormalizableWhitespace(*src))
  1.3171 +              m << String::Format("&#x%02X;", unsigned(*src));
  1.3172 +            else
  1.3173 +              m << *src;
  1.3174 +          }
  1.3175 +          break;
  1.3176 +      }
  1.3177 +    }
  1.3178 +  }
  1.3179 +
  1.3180 +  return m.GetString();
  1.3181 +}
  1.3182 +
  1.3183 +// Returns the given string with all characters invalid in XML removed.
  1.3184 +// Currently invalid characters are dropped from the string. An
  1.3185 +// alternative is to replace them with certain characters such as . or ?.
  1.3186 +string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(const string& str) {
  1.3187 +  string output;
  1.3188 +  output.reserve(str.size());
  1.3189 +  for (string::const_iterator it = str.begin(); it != str.end(); ++it)
  1.3190 +    if (IsValidXmlCharacter(*it))
  1.3191 +      output.push_back(*it);
  1.3192 +
  1.3193 +  return output;
  1.3194 +}
  1.3195 +
  1.3196 +// The following routines generate an XML representation of a UnitTest
  1.3197 +// object.
  1.3198 +//
  1.3199 +// This is how Google Test concepts map to the DTD:
  1.3200 +//
  1.3201 +// <testsuites name="AllTests">        <-- corresponds to a UnitTest object
  1.3202 +//   <testsuite name="testcase-name">  <-- corresponds to a TestCase object
  1.3203 +//     <testcase name="test-name">     <-- corresponds to a TestInfo object
  1.3204 +//       <failure message="...">...</failure>
  1.3205 +//       <failure message="...">...</failure>
  1.3206 +//       <failure message="...">...</failure>
  1.3207 +//                                     <-- individual assertion failures
  1.3208 +//     </testcase>
  1.3209 +//   </testsuite>
  1.3210 +// </testsuites>
  1.3211 +
  1.3212 +// Formats the given time in milliseconds as seconds.
  1.3213 +std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {
  1.3214 +  ::std::stringstream ss;
  1.3215 +  ss << ms/1000.0;
  1.3216 +  return ss.str();
  1.3217 +}
  1.3218 +
  1.3219 +// Converts the given epoch time in milliseconds to a date string in the ISO
  1.3220 +// 8601 format, without the timezone information.
  1.3221 +std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) {
  1.3222 +  // Using non-reentrant version as localtime_r is not portable.
  1.3223 +  time_t seconds = static_cast<time_t>(ms / 1000);
  1.3224 +#ifdef _MSC_VER
  1.3225 +# pragma warning(push)          // Saves the current warning state.
  1.3226 +# pragma warning(disable:4996)  // Temporarily disables warning 4996
  1.3227 +                                // (function or variable may be unsafe).
  1.3228 +  const struct tm* const time_struct = localtime(&seconds);  // NOLINT
  1.3229 +# pragma warning(pop)           // Restores the warning state again.
  1.3230 +#else
  1.3231 +  const struct tm* const time_struct = localtime(&seconds);  // NOLINT
  1.3232 +#endif
  1.3233 +  if (time_struct == NULL)
  1.3234 +    return "";  // Invalid ms value
  1.3235 +
  1.3236 +  return String::Format("%d-%02d-%02dT%02d:%02d:%02d",  // YYYY-MM-DDThh:mm:ss
  1.3237 +                        time_struct->tm_year + 1900,
  1.3238 +                        time_struct->tm_mon + 1,
  1.3239 +                        time_struct->tm_mday,
  1.3240 +                        time_struct->tm_hour,
  1.3241 +                        time_struct->tm_min,
  1.3242 +                        time_struct->tm_sec);
  1.3243 +}
  1.3244 +
  1.3245 +// Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
  1.3246 +void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
  1.3247 +                                                     const char* data) {
  1.3248 +  const char* segment = data;
  1.3249 +  *stream << "<![CDATA[";
  1.3250 +  for (;;) {
  1.3251 +    const char* const next_segment = strstr(segment, "]]>");
  1.3252 +    if (next_segment != NULL) {
  1.3253 +      stream->write(
  1.3254 +          segment, static_cast<std::streamsize>(next_segment - segment));
  1.3255 +      *stream << "]]>]]&gt;<![CDATA[";
  1.3256 +      segment = next_segment + strlen("]]>");
  1.3257 +    } else {
  1.3258 +      *stream << segment;
  1.3259 +      break;
  1.3260 +    }
  1.3261 +  }
  1.3262 +  *stream << "]]>";
  1.3263 +}
  1.3264 +
  1.3265 +// Prints an XML representation of a TestInfo object.
  1.3266 +// TODO(wan): There is also value in printing properties with the plain printer.
  1.3267 +void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
  1.3268 +                                                 const char* test_case_name,
  1.3269 +                                                 const TestInfo& test_info) {
  1.3270 +  const TestResult& result = *test_info.result();
  1.3271 +  *stream << "    <testcase name=\""
  1.3272 +          << EscapeXmlAttribute(test_info.name()).c_str() << "\"";
  1.3273 +
  1.3274 +  if (test_info.value_param() != NULL) {
  1.3275 +    *stream << " value_param=\"" << EscapeXmlAttribute(test_info.value_param())
  1.3276 +            << "\"";
  1.3277 +  }
  1.3278 +  if (test_info.type_param() != NULL) {
  1.3279 +    *stream << " type_param=\"" << EscapeXmlAttribute(test_info.type_param())
  1.3280 +            << "\"";
  1.3281 +  }
  1.3282 +
  1.3283 +  *stream << " status=\""
  1.3284 +          << (test_info.should_run() ? "run" : "notrun")
  1.3285 +          << "\" time=\""
  1.3286 +          << FormatTimeInMillisAsSeconds(result.elapsed_time())
  1.3287 +          << "\" classname=\"" << EscapeXmlAttribute(test_case_name).c_str()
  1.3288 +          << "\"" << TestPropertiesAsXmlAttributes(result).c_str();
  1.3289 +
  1.3290 +  int failures = 0;
  1.3291 +  for (int i = 0; i < result.total_part_count(); ++i) {
  1.3292 +    const TestPartResult& part = result.GetTestPartResult(i);
  1.3293 +    if (part.failed()) {
  1.3294 +      if (++failures == 1) {
  1.3295 +        *stream << ">\n";
  1.3296 +      }
  1.3297 +      const string location = internal::FormatCompilerIndependentFileLocation(
  1.3298 +          part.file_name(), part.line_number());
  1.3299 +      const string summary = location + "\n" + part.summary();
  1.3300 +      *stream << "      <failure message=\""
  1.3301 +              << EscapeXmlAttribute(summary.c_str())
  1.3302 +              << "\" type=\"\">";
  1.3303 +      const string detail = location + "\n" + part.message();
  1.3304 +      OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
  1.3305 +      *stream << "</failure>\n";
  1.3306 +    }
  1.3307 +  }
  1.3308 +
  1.3309 +  if (failures == 0)
  1.3310 +    *stream << " />\n";
  1.3311 +  else
  1.3312 +    *stream << "    </testcase>\n";
  1.3313 +}
  1.3314 +
  1.3315 +// Prints an XML representation of a TestCase object
  1.3316 +void XmlUnitTestResultPrinter::PrintXmlTestCase(FILE* out,
  1.3317 +                                                const TestCase& test_case) {
  1.3318 +  fprintf(out,
  1.3319 +          "  <testsuite name=\"%s\" tests=\"%d\" failures=\"%d\" "
  1.3320 +          "disabled=\"%d\" ",
  1.3321 +          EscapeXmlAttribute(test_case.name()).c_str(),
  1.3322 +          test_case.total_test_count(),
  1.3323 +          test_case.failed_test_count(),
  1.3324 +          test_case.disabled_test_count());
  1.3325 +  fprintf(out,
  1.3326 +          "errors=\"0\" time=\"%s\">\n",
  1.3327 +          FormatTimeInMillisAsSeconds(test_case.elapsed_time()).c_str());
  1.3328 +  for (int i = 0; i < test_case.total_test_count(); ++i) {
  1.3329 +    ::std::stringstream stream;
  1.3330 +    OutputXmlTestInfo(&stream, test_case.name(), *test_case.GetTestInfo(i));
  1.3331 +    fprintf(out, "%s", StringStreamToString(&stream).c_str());
  1.3332 +  }
  1.3333 +  fprintf(out, "  </testsuite>\n");
  1.3334 +}
  1.3335 +
  1.3336 +// Prints an XML summary of unit_test to output stream out.
  1.3337 +void XmlUnitTestResultPrinter::PrintXmlUnitTest(FILE* out,
  1.3338 +                                                const UnitTest& unit_test) {
  1.3339 +  fprintf(out, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
  1.3340 +  fprintf(out,
  1.3341 +          "<testsuites tests=\"%d\" failures=\"%d\" disabled=\"%d\" "
  1.3342 +          "errors=\"0\" timestamp=\"%s\" time=\"%s\" ",
  1.3343 +          unit_test.total_test_count(),
  1.3344 +          unit_test.failed_test_count(),
  1.3345 +          unit_test.disabled_test_count(),
  1.3346 +          FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp()).c_str(),
  1.3347 +          FormatTimeInMillisAsSeconds(unit_test.elapsed_time()).c_str());
  1.3348 +  if (GTEST_FLAG(shuffle)) {
  1.3349 +    fprintf(out, "random_seed=\"%d\" ", unit_test.random_seed());
  1.3350 +  }
  1.3351 +  fprintf(out, "name=\"AllTests\">\n");
  1.3352 +  for (int i = 0; i < unit_test.total_test_case_count(); ++i)
  1.3353 +    PrintXmlTestCase(out, *unit_test.GetTestCase(i));
  1.3354 +  fprintf(out, "</testsuites>\n");
  1.3355 +}
  1.3356 +
  1.3357 +// Produces a string representing the test properties in a result as space
  1.3358 +// delimited XML attributes based on the property key="value" pairs.
  1.3359 +String XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
  1.3360 +    const TestResult& result) {
  1.3361 +  Message attributes;
  1.3362 +  for (int i = 0; i < result.test_property_count(); ++i) {
  1.3363 +    const TestProperty& property = result.GetTestProperty(i);
  1.3364 +    attributes << " " << property.key() << "="
  1.3365 +        << "\"" << EscapeXmlAttribute(property.value()) << "\"";
  1.3366 +  }
  1.3367 +  return attributes.GetString();
  1.3368 +}
  1.3369 +
  1.3370 +// End XmlUnitTestResultPrinter
  1.3371 +
  1.3372 +#if GTEST_CAN_STREAM_RESULTS_
  1.3373 +
  1.3374 +// Streams test results to the given port on the given host machine.
  1.3375 +class StreamingListener : public EmptyTestEventListener {
  1.3376 + public:
  1.3377 +  // Escapes '=', '&', '%', and '\n' characters in str as "%xx".
  1.3378 +  static string UrlEncode(const char* str);
  1.3379 +
  1.3380 +  StreamingListener(const string& host, const string& port)
  1.3381 +      : sockfd_(-1), host_name_(host), port_num_(port) {
  1.3382 +    MakeConnection();
  1.3383 +    Send("gtest_streaming_protocol_version=1.0\n");
  1.3384 +  }
  1.3385 +
  1.3386 +  virtual ~StreamingListener() {
  1.3387 +    if (sockfd_ != -1)
  1.3388 +      CloseConnection();
  1.3389 +  }
  1.3390 +
  1.3391 +  void OnTestProgramStart(const UnitTest& /* unit_test */) {
  1.3392 +    Send("event=TestProgramStart\n");
  1.3393 +  }
  1.3394 +
  1.3395 +  void OnTestProgramEnd(const UnitTest& unit_test) {
  1.3396 +    // Note that Google Test current only report elapsed time for each
  1.3397 +    // test iteration, not for the entire test program.
  1.3398 +    Send(String::Format("event=TestProgramEnd&passed=%d\n",
  1.3399 +                        unit_test.Passed()));
  1.3400 +
  1.3401 +    // Notify the streaming server to stop.
  1.3402 +    CloseConnection();
  1.3403 +  }
  1.3404 +
  1.3405 +  void OnTestIterationStart(const UnitTest& /* unit_test */, int iteration) {
  1.3406 +    Send(String::Format("event=TestIterationStart&iteration=%d\n",
  1.3407 +                        iteration));
  1.3408 +  }
  1.3409 +
  1.3410 +  void OnTestIterationEnd(const UnitTest& unit_test, int /* iteration */) {
  1.3411 +    Send(String::Format("event=TestIterationEnd&passed=%d&elapsed_time=%sms\n",
  1.3412 +                        unit_test.Passed(),
  1.3413 +                        StreamableToString(unit_test.elapsed_time()).c_str()));
  1.3414 +  }
  1.3415 +
  1.3416 +  void OnTestCaseStart(const TestCase& test_case) {
  1.3417 +    Send(String::Format("event=TestCaseStart&name=%s\n", test_case.name()));
  1.3418 +  }
  1.3419 +
  1.3420 +  void OnTestCaseEnd(const TestCase& test_case) {
  1.3421 +    Send(String::Format("event=TestCaseEnd&passed=%d&elapsed_time=%sms\n",
  1.3422 +                        test_case.Passed(),
  1.3423 +                        StreamableToString(test_case.elapsed_time()).c_str()));
  1.3424 +  }
  1.3425 +
  1.3426 +  void OnTestStart(const TestInfo& test_info) {
  1.3427 +    Send(String::Format("event=TestStart&name=%s\n", test_info.name()));
  1.3428 +  }
  1.3429 +
  1.3430 +  void OnTestEnd(const TestInfo& test_info) {
  1.3431 +    Send(String::Format(
  1.3432 +        "event=TestEnd&passed=%d&elapsed_time=%sms\n",
  1.3433 +        (test_info.result())->Passed(),
  1.3434 +        StreamableToString((test_info.result())->elapsed_time()).c_str()));
  1.3435 +  }
  1.3436 +
  1.3437 +  void OnTestPartResult(const TestPartResult& test_part_result) {
  1.3438 +    const char* file_name = test_part_result.file_name();
  1.3439 +    if (file_name == NULL)
  1.3440 +      file_name = "";
  1.3441 +    Send(String::Format("event=TestPartResult&file=%s&line=%d&message=",
  1.3442 +                        UrlEncode(file_name).c_str(),
  1.3443 +                        test_part_result.line_number()));
  1.3444 +    Send(UrlEncode(test_part_result.message()) + "\n");
  1.3445 +  }
  1.3446 +
  1.3447 + private:
  1.3448 +  // Creates a client socket and connects to the server.
  1.3449 +  void MakeConnection();
  1.3450 +
  1.3451 +  // Closes the socket.
  1.3452 +  void CloseConnection() {
  1.3453 +    GTEST_CHECK_(sockfd_ != -1)
  1.3454 +        << "CloseConnection() can be called only when there is a connection.";
  1.3455 +
  1.3456 +    close(sockfd_);
  1.3457 +    sockfd_ = -1;
  1.3458 +  }
  1.3459 +
  1.3460 +  // Sends a string to the socket.
  1.3461 +  void Send(const string& message) {
  1.3462 +    GTEST_CHECK_(sockfd_ != -1)
  1.3463 +        << "Send() can be called only when there is a connection.";
  1.3464 +
  1.3465 +    const int len = static_cast<int>(message.length());
  1.3466 +    if (write(sockfd_, message.c_str(), len) != len) {
  1.3467 +      GTEST_LOG_(WARNING)
  1.3468 +          << "stream_result_to: failed to stream to "
  1.3469 +          << host_name_ << ":" << port_num_;
  1.3470 +    }
  1.3471 +  }
  1.3472 +
  1.3473 +  int sockfd_;   // socket file descriptor
  1.3474 +  const string host_name_;
  1.3475 +  const string port_num_;
  1.3476 +
  1.3477 +  GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener);
  1.3478 +};  // class StreamingListener
  1.3479 +
  1.3480 +// Checks if str contains '=', '&', '%' or '\n' characters. If yes,
  1.3481 +// replaces them by "%xx" where xx is their hexadecimal value. For
  1.3482 +// example, replaces "=" with "%3D".  This algorithm is O(strlen(str))
  1.3483 +// in both time and space -- important as the input str may contain an
  1.3484 +// arbitrarily long test failure message and stack trace.
  1.3485 +string StreamingListener::UrlEncode(const char* str) {
  1.3486 +  string result;
  1.3487 +  result.reserve(strlen(str) + 1);
  1.3488 +  for (char ch = *str; ch != '\0'; ch = *++str) {
  1.3489 +    switch (ch) {
  1.3490 +      case '%':
  1.3491 +      case '=':
  1.3492 +      case '&':
  1.3493 +      case '\n':
  1.3494 +        result.append(String::Format("%%%02x", static_cast<unsigned char>(ch)));
  1.3495 +        break;
  1.3496 +      default:
  1.3497 +        result.push_back(ch);
  1.3498 +        break;
  1.3499 +    }
  1.3500 +  }
  1.3501 +  return result;
  1.3502 +}
  1.3503 +
  1.3504 +void StreamingListener::MakeConnection() {
  1.3505 +  GTEST_CHECK_(sockfd_ == -1)
  1.3506 +      << "MakeConnection() can't be called when there is already a connection.";
  1.3507 +
  1.3508 +  addrinfo hints;
  1.3509 +  memset(&hints, 0, sizeof(hints));
  1.3510 +  hints.ai_family = AF_UNSPEC;    // To allow both IPv4 and IPv6 addresses.
  1.3511 +  hints.ai_socktype = SOCK_STREAM;
  1.3512 +  addrinfo* servinfo = NULL;
  1.3513 +
  1.3514 +  // Use the getaddrinfo() to get a linked list of IP addresses for
  1.3515 +  // the given host name.
  1.3516 +  const int error_num = getaddrinfo(
  1.3517 +      host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
  1.3518 +  if (error_num != 0) {
  1.3519 +    GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: "
  1.3520 +                        << gai_strerror(error_num);
  1.3521 +  }
  1.3522 +
  1.3523 +  // Loop through all the results and connect to the first we can.
  1.3524 +  for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != NULL;
  1.3525 +       cur_addr = cur_addr->ai_next) {
  1.3526 +    sockfd_ = socket(
  1.3527 +        cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol);
  1.3528 +    if (sockfd_ != -1) {
  1.3529 +      // Connect the client socket to the server socket.
  1.3530 +      if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
  1.3531 +        close(sockfd_);
  1.3532 +        sockfd_ = -1;
  1.3533 +      }
  1.3534 +    }
  1.3535 +  }
  1.3536 +
  1.3537 +  freeaddrinfo(servinfo);  // all done with this structure
  1.3538 +
  1.3539 +  if (sockfd_ == -1) {
  1.3540 +    GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to "
  1.3541 +                        << host_name_ << ":" << port_num_;
  1.3542 +  }
  1.3543 +}
  1.3544 +
  1.3545 +// End of class Streaming Listener
  1.3546 +#endif  // GTEST_CAN_STREAM_RESULTS__
  1.3547 +
  1.3548 +// Class ScopedTrace
  1.3549 +
  1.3550 +// Pushes the given source file location and message onto a per-thread
  1.3551 +// trace stack maintained by Google Test.
  1.3552 +ScopedTrace::ScopedTrace(const char* file, int line, const Message& message)
  1.3553 +    GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
  1.3554 +  TraceInfo trace;
  1.3555 +  trace.file = file;
  1.3556 +  trace.line = line;
  1.3557 +  trace.message = message.GetString();
  1.3558 +
  1.3559 +  UnitTest::GetInstance()->PushGTestTrace(trace);
  1.3560 +}
  1.3561 +
  1.3562 +// Pops the info pushed by the c'tor.
  1.3563 +ScopedTrace::~ScopedTrace()
  1.3564 +    GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
  1.3565 +  UnitTest::GetInstance()->PopGTestTrace();
  1.3566 +}
  1.3567 +
  1.3568 +
  1.3569 +// class OsStackTraceGetter
  1.3570 +
  1.3571 +// Returns the current OS stack trace as a String.  Parameters:
  1.3572 +//
  1.3573 +//   max_depth  - the maximum number of stack frames to be included
  1.3574 +//                in the trace.
  1.3575 +//   skip_count - the number of top frames to be skipped; doesn't count
  1.3576 +//                against max_depth.
  1.3577 +//
  1.3578 +String OsStackTraceGetter::CurrentStackTrace(int /* max_depth */,
  1.3579 +                                             int /* skip_count */)
  1.3580 +    GTEST_LOCK_EXCLUDED_(mutex_) {
  1.3581 +  return String("");
  1.3582 +}
  1.3583 +
  1.3584 +void OsStackTraceGetter::UponLeavingGTest()
  1.3585 +    GTEST_LOCK_EXCLUDED_(mutex_) {
  1.3586 +}
  1.3587 +
  1.3588 +const char* const
  1.3589 +OsStackTraceGetter::kElidedFramesMarker =
  1.3590 +    "... " GTEST_NAME_ " internal frames ...";
  1.3591 +
  1.3592 +}  // namespace internal
  1.3593 +
  1.3594 +// class TestEventListeners
  1.3595 +
  1.3596 +TestEventListeners::TestEventListeners()
  1.3597 +    : repeater_(new internal::TestEventRepeater()),
  1.3598 +      default_result_printer_(NULL),
  1.3599 +      default_xml_generator_(NULL) {
  1.3600 +}
  1.3601 +
  1.3602 +TestEventListeners::~TestEventListeners() { delete repeater_; }
  1.3603 +
  1.3604 +// Returns the standard listener responsible for the default console
  1.3605 +// output.  Can be removed from the listeners list to shut down default
  1.3606 +// console output.  Note that removing this object from the listener list
  1.3607 +// with Release transfers its ownership to the user.
  1.3608 +void TestEventListeners::Append(TestEventListener* listener) {
  1.3609 +  repeater_->Append(listener);
  1.3610 +}
  1.3611 +
  1.3612 +// Removes the given event listener from the list and returns it.  It then
  1.3613 +// becomes the caller's responsibility to delete the listener. Returns
  1.3614 +// NULL if the listener is not found in the list.
  1.3615 +TestEventListener* TestEventListeners::Release(TestEventListener* listener) {
  1.3616 +  if (listener == default_result_printer_)
  1.3617 +    default_result_printer_ = NULL;
  1.3618 +  else if (listener == default_xml_generator_)
  1.3619 +    default_xml_generator_ = NULL;
  1.3620 +  return repeater_->Release(listener);
  1.3621 +}
  1.3622 +
  1.3623 +// Returns repeater that broadcasts the TestEventListener events to all
  1.3624 +// subscribers.
  1.3625 +TestEventListener* TestEventListeners::repeater() { return repeater_; }
  1.3626 +
  1.3627 +// Sets the default_result_printer attribute to the provided listener.
  1.3628 +// The listener is also added to the listener list and previous
  1.3629 +// default_result_printer is removed from it and deleted. The listener can
  1.3630 +// also be NULL in which case it will not be added to the list. Does
  1.3631 +// nothing if the previous and the current listener objects are the same.
  1.3632 +void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
  1.3633 +  if (default_result_printer_ != listener) {
  1.3634 +    // It is an error to pass this method a listener that is already in the
  1.3635 +    // list.
  1.3636 +    delete Release(default_result_printer_);
  1.3637 +    default_result_printer_ = listener;
  1.3638 +    if (listener != NULL)
  1.3639 +      Append(listener);
  1.3640 +  }
  1.3641 +}
  1.3642 +
  1.3643 +// Sets the default_xml_generator attribute to the provided listener.  The
  1.3644 +// listener is also added to the listener list and previous
  1.3645 +// default_xml_generator is removed from it and deleted. The listener can
  1.3646 +// also be NULL in which case it will not be added to the list. Does
  1.3647 +// nothing if the previous and the current listener objects are the same.
  1.3648 +void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
  1.3649 +  if (default_xml_generator_ != listener) {
  1.3650 +    // It is an error to pass this method a listener that is already in the
  1.3651 +    // list.
  1.3652 +    delete Release(default_xml_generator_);
  1.3653 +    default_xml_generator_ = listener;
  1.3654 +    if (listener != NULL)
  1.3655 +      Append(listener);
  1.3656 +  }
  1.3657 +}
  1.3658 +
  1.3659 +// Controls whether events will be forwarded by the repeater to the
  1.3660 +// listeners in the list.
  1.3661 +bool TestEventListeners::EventForwardingEnabled() const {
  1.3662 +  return repeater_->forwarding_enabled();
  1.3663 +}
  1.3664 +
  1.3665 +void TestEventListeners::SuppressEventForwarding() {
  1.3666 +  repeater_->set_forwarding_enabled(false);
  1.3667 +}
  1.3668 +
  1.3669 +// class UnitTest
  1.3670 +
  1.3671 +// Gets the singleton UnitTest object.  The first time this method is
  1.3672 +// called, a UnitTest object is constructed and returned.  Consecutive
  1.3673 +// calls will return the same object.
  1.3674 +//
  1.3675 +// We don't protect this under mutex_ as a user is not supposed to
  1.3676 +// call this before main() starts, from which point on the return
  1.3677 +// value will never change.
  1.3678 +UnitTest * UnitTest::GetInstance() {
  1.3679 +  // When compiled with MSVC 7.1 in optimized mode, destroying the
  1.3680 +  // UnitTest object upon exiting the program messes up the exit code,
  1.3681 +  // causing successful tests to appear failed.  We have to use a
  1.3682 +  // different implementation in this case to bypass the compiler bug.
  1.3683 +  // This implementation makes the compiler happy, at the cost of
  1.3684 +  // leaking the UnitTest object.
  1.3685 +
  1.3686 +  // CodeGear C++Builder insists on a public destructor for the
  1.3687 +  // default implementation.  Use this implementation to keep good OO
  1.3688 +  // design with private destructor.
  1.3689 +
  1.3690 +#if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
  1.3691 +  static UnitTest* const instance = new UnitTest;
  1.3692 +  return instance;
  1.3693 +#else
  1.3694 +  static UnitTest instance;
  1.3695 +  return &instance;
  1.3696 +#endif  // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
  1.3697 +}
  1.3698 +
  1.3699 +// Gets the number of successful test cases.
  1.3700 +int UnitTest::successful_test_case_count() const {
  1.3701 +  return impl()->successful_test_case_count();
  1.3702 +}
  1.3703 +
  1.3704 +// Gets the number of failed test cases.
  1.3705 +int UnitTest::failed_test_case_count() const {
  1.3706 +  return impl()->failed_test_case_count();
  1.3707 +}
  1.3708 +
  1.3709 +// Gets the number of all test cases.
  1.3710 +int UnitTest::total_test_case_count() const {
  1.3711 +  return impl()->total_test_case_count();
  1.3712 +}
  1.3713 +
  1.3714 +// Gets the number of all test cases that contain at least one test
  1.3715 +// that should run.
  1.3716 +int UnitTest::test_case_to_run_count() const {
  1.3717 +  return impl()->test_case_to_run_count();
  1.3718 +}
  1.3719 +
  1.3720 +// Gets the number of successful tests.
  1.3721 +int UnitTest::successful_test_count() const {
  1.3722 +  return impl()->successful_test_count();
  1.3723 +}
  1.3724 +
  1.3725 +// Gets the number of failed tests.
  1.3726 +int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
  1.3727 +
  1.3728 +// Gets the number of disabled tests.
  1.3729 +int UnitTest::disabled_test_count() const {
  1.3730 +  return impl()->disabled_test_count();
  1.3731 +}
  1.3732 +
  1.3733 +// Gets the number of all tests.
  1.3734 +int UnitTest::total_test_count() const { return impl()->total_test_count(); }
  1.3735 +
  1.3736 +// Gets the number of tests that should run.
  1.3737 +int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
  1.3738 +
  1.3739 +// Gets the time of the test program start, in ms from the start of the
  1.3740 +// UNIX epoch.
  1.3741 +internal::TimeInMillis UnitTest::start_timestamp() const {
  1.3742 +    return impl()->start_timestamp();
  1.3743 +}
  1.3744 +
  1.3745 +// Gets the elapsed time, in milliseconds.
  1.3746 +internal::TimeInMillis UnitTest::elapsed_time() const {
  1.3747 +  return impl()->elapsed_time();
  1.3748 +}
  1.3749 +
  1.3750 +// Returns true iff the unit test passed (i.e. all test cases passed).
  1.3751 +bool UnitTest::Passed() const { return impl()->Passed(); }
  1.3752 +
  1.3753 +// Returns true iff the unit test failed (i.e. some test case failed
  1.3754 +// or something outside of all tests failed).
  1.3755 +bool UnitTest::Failed() const { return impl()->Failed(); }
  1.3756 +
  1.3757 +// Gets the i-th test case among all the test cases. i can range from 0 to
  1.3758 +// total_test_case_count() - 1. If i is not in that range, returns NULL.
  1.3759 +const TestCase* UnitTest::GetTestCase(int i) const {
  1.3760 +  return impl()->GetTestCase(i);
  1.3761 +}
  1.3762 +
  1.3763 +// Gets the i-th test case among all the test cases. i can range from 0 to
  1.3764 +// total_test_case_count() - 1. If i is not in that range, returns NULL.
  1.3765 +TestCase* UnitTest::GetMutableTestCase(int i) {
  1.3766 +  return impl()->GetMutableTestCase(i);
  1.3767 +}
  1.3768 +
  1.3769 +// Returns the list of event listeners that can be used to track events
  1.3770 +// inside Google Test.
  1.3771 +TestEventListeners& UnitTest::listeners() {
  1.3772 +  return *impl()->listeners();
  1.3773 +}
  1.3774 +
  1.3775 +// Registers and returns a global test environment.  When a test
  1.3776 +// program is run, all global test environments will be set-up in the
  1.3777 +// order they were registered.  After all tests in the program have
  1.3778 +// finished, all global test environments will be torn-down in the
  1.3779 +// *reverse* order they were registered.
  1.3780 +//
  1.3781 +// The UnitTest object takes ownership of the given environment.
  1.3782 +//
  1.3783 +// We don't protect this under mutex_, as we only support calling it
  1.3784 +// from the main thread.
  1.3785 +Environment* UnitTest::AddEnvironment(Environment* env) {
  1.3786 +  if (env == NULL) {
  1.3787 +    return NULL;
  1.3788 +  }
  1.3789 +
  1.3790 +  impl_->environments().push_back(env);
  1.3791 +  return env;
  1.3792 +}
  1.3793 +
  1.3794 +// Adds a TestPartResult to the current TestResult object.  All Google Test
  1.3795 +// assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
  1.3796 +// this to report their results.  The user code should use the
  1.3797 +// assertion macros instead of calling this directly.
  1.3798 +void UnitTest::AddTestPartResult(
  1.3799 +    TestPartResult::Type result_type,
  1.3800 +    const char* file_name,
  1.3801 +    int line_number,
  1.3802 +    const internal::String& message,
  1.3803 +    const internal::String& os_stack_trace)
  1.3804 +        GTEST_LOCK_EXCLUDED_(mutex_) {
  1.3805 +  Message msg;
  1.3806 +  msg << message;
  1.3807 +
  1.3808 +  internal::MutexLock lock(&mutex_);
  1.3809 +  if (impl_->gtest_trace_stack().size() > 0) {
  1.3810 +    msg << "\n" << GTEST_NAME_ << " trace:";
  1.3811 +
  1.3812 +    for (int i = static_cast<int>(impl_->gtest_trace_stack().size());
  1.3813 +         i > 0; --i) {
  1.3814 +      const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
  1.3815 +      msg << "\n" << internal::FormatFileLocation(trace.file, trace.line)
  1.3816 +          << " " << trace.message;
  1.3817 +    }
  1.3818 +  }
  1.3819 +
  1.3820 +  if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) {
  1.3821 +    msg << internal::kStackTraceMarker << os_stack_trace;
  1.3822 +  }
  1.3823 +
  1.3824 +  const TestPartResult result =
  1.3825 +    TestPartResult(result_type, file_name, line_number,
  1.3826 +                   msg.GetString().c_str());
  1.3827 +  impl_->GetTestPartResultReporterForCurrentThread()->
  1.3828 +      ReportTestPartResult(result);
  1.3829 +
  1.3830 +  if (result_type != TestPartResult::kSuccess) {
  1.3831 +    // gtest_break_on_failure takes precedence over
  1.3832 +    // gtest_throw_on_failure.  This allows a user to set the latter
  1.3833 +    // in the code (perhaps in order to use Google Test assertions
  1.3834 +    // with another testing framework) and specify the former on the
  1.3835 +    // command line for debugging.
  1.3836 +    if (GTEST_FLAG(break_on_failure)) {
  1.3837 +#if GTEST_OS_WINDOWS
  1.3838 +      // Using DebugBreak on Windows allows gtest to still break into a debugger
  1.3839 +      // when a failure happens and both the --gtest_break_on_failure and
  1.3840 +      // the --gtest_catch_exceptions flags are specified.
  1.3841 +      DebugBreak();
  1.3842 +#else
  1.3843 +      // Dereference NULL through a volatile pointer to prevent the compiler
  1.3844 +      // from removing. We use this rather than abort() or __builtin_trap() for
  1.3845 +      // portability: Symbian doesn't implement abort() well, and some debuggers
  1.3846 +      // don't correctly trap abort().
  1.3847 +      *static_cast<volatile int*>(NULL) = 1;
  1.3848 +#endif  // GTEST_OS_WINDOWS
  1.3849 +    } else if (GTEST_FLAG(throw_on_failure)) {
  1.3850 +#if GTEST_HAS_EXCEPTIONS
  1.3851 +      throw GoogleTestFailureException(result);
  1.3852 +#else
  1.3853 +      // We cannot call abort() as it generates a pop-up in debug mode
  1.3854 +      // that cannot be suppressed in VC 7.1 or below.
  1.3855 +      exit(1);
  1.3856 +#endif
  1.3857 +    }
  1.3858 +  }
  1.3859 +}
  1.3860 +
  1.3861 +// Creates and adds a property to the current TestResult. If a property matching
  1.3862 +// the supplied value already exists, updates its value instead.
  1.3863 +void UnitTest::RecordPropertyForCurrentTest(const char* key,
  1.3864 +                                            const char* value) {
  1.3865 +  const TestProperty test_property(key, value);
  1.3866 +  impl_->current_test_result()->RecordProperty(test_property);
  1.3867 +}
  1.3868 +
  1.3869 +// Runs all tests in this UnitTest object and prints the result.
  1.3870 +// Returns 0 if successful, or 1 otherwise.
  1.3871 +//
  1.3872 +// We don't protect this under mutex_, as we only support calling it
  1.3873 +// from the main thread.
  1.3874 +int UnitTest::Run() {
  1.3875 +  // Captures the value of GTEST_FLAG(catch_exceptions).  This value will be
  1.3876 +  // used for the duration of the program.
  1.3877 +  impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions));
  1.3878 +
  1.3879 +#if GTEST_HAS_SEH
  1.3880 +  const bool in_death_test_child_process =
  1.3881 +      internal::GTEST_FLAG(internal_run_death_test).length() > 0;
  1.3882 +
  1.3883 +  // Either the user wants Google Test to catch exceptions thrown by the
  1.3884 +  // tests or this is executing in the context of death test child
  1.3885 +  // process. In either case the user does not want to see pop-up dialogs
  1.3886 +  // about crashes - they are expected.
  1.3887 +  if (impl()->catch_exceptions() || in_death_test_child_process) {
  1.3888 +# if !GTEST_OS_WINDOWS_MOBILE
  1.3889 +    // SetErrorMode doesn't exist on CE.
  1.3890 +    SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
  1.3891 +                 SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
  1.3892 +# endif  // !GTEST_OS_WINDOWS_MOBILE
  1.3893 +
  1.3894 +# if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
  1.3895 +    // Death test children can be terminated with _abort().  On Windows,
  1.3896 +    // _abort() can show a dialog with a warning message.  This forces the
  1.3897 +    // abort message to go to stderr instead.
  1.3898 +    _set_error_mode(_OUT_TO_STDERR);
  1.3899 +# endif
  1.3900 +
  1.3901 +# if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
  1.3902 +    // In the debug version, Visual Studio pops up a separate dialog
  1.3903 +    // offering a choice to debug the aborted program. We need to suppress
  1.3904 +    // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
  1.3905 +    // executed. Google Test will notify the user of any unexpected
  1.3906 +    // failure via stderr.
  1.3907 +    //
  1.3908 +    // VC++ doesn't define _set_abort_behavior() prior to the version 8.0.
  1.3909 +    // Users of prior VC versions shall suffer the agony and pain of
  1.3910 +    // clicking through the countless debug dialogs.
  1.3911 +    // TODO(vladl@google.com): find a way to suppress the abort dialog() in the
  1.3912 +    // debug mode when compiled with VC 7.1 or lower.
  1.3913 +    if (!GTEST_FLAG(break_on_failure))
  1.3914 +      _set_abort_behavior(
  1.3915 +          0x0,                                    // Clear the following flags:
  1.3916 +          _WRITE_ABORT_MSG | _CALL_REPORTFAULT);  // pop-up window, core dump.
  1.3917 +# endif
  1.3918 +  }
  1.3919 +#endif  // GTEST_HAS_SEH
  1.3920 +
  1.3921 +  return internal::HandleExceptionsInMethodIfSupported(
  1.3922 +      impl(),
  1.3923 +      &internal::UnitTestImpl::RunAllTests,
  1.3924 +      "auxiliary test code (environments or event listeners)") ? 0 : 1;
  1.3925 +}
  1.3926 +
  1.3927 +// Returns the working directory when the first TEST() or TEST_F() was
  1.3928 +// executed.
  1.3929 +const char* UnitTest::original_working_dir() const {
  1.3930 +  return impl_->original_working_dir_.c_str();
  1.3931 +}
  1.3932 +
  1.3933 +// Returns the TestCase object for the test that's currently running,
  1.3934 +// or NULL if no test is running.
  1.3935 +const TestCase* UnitTest::current_test_case() const
  1.3936 +    GTEST_LOCK_EXCLUDED_(mutex_) {
  1.3937 +  internal::MutexLock lock(&mutex_);
  1.3938 +  return impl_->current_test_case();
  1.3939 +}
  1.3940 +
  1.3941 +// Returns the TestInfo object for the test that's currently running,
  1.3942 +// or NULL if no test is running.
  1.3943 +const TestInfo* UnitTest::current_test_info() const
  1.3944 +    GTEST_LOCK_EXCLUDED_(mutex_) {
  1.3945 +  internal::MutexLock lock(&mutex_);
  1.3946 +  return impl_->current_test_info();
  1.3947 +}
  1.3948 +
  1.3949 +// Returns the random seed used at the start of the current test run.
  1.3950 +int UnitTest::random_seed() const { return impl_->random_seed(); }
  1.3951 +
  1.3952 +#if GTEST_HAS_PARAM_TEST
  1.3953 +// Returns ParameterizedTestCaseRegistry object used to keep track of
  1.3954 +// value-parameterized tests and instantiate and register them.
  1.3955 +internal::ParameterizedTestCaseRegistry&
  1.3956 +    UnitTest::parameterized_test_registry()
  1.3957 +        GTEST_LOCK_EXCLUDED_(mutex_) {
  1.3958 +  return impl_->parameterized_test_registry();
  1.3959 +}
  1.3960 +#endif  // GTEST_HAS_PARAM_TEST
  1.3961 +
  1.3962 +// Creates an empty UnitTest.
  1.3963 +UnitTest::UnitTest() {
  1.3964 +  impl_ = new internal::UnitTestImpl(this);
  1.3965 +}
  1.3966 +
  1.3967 +// Destructor of UnitTest.
  1.3968 +UnitTest::~UnitTest() {
  1.3969 +  delete impl_;
  1.3970 +}
  1.3971 +
  1.3972 +// Pushes a trace defined by SCOPED_TRACE() on to the per-thread
  1.3973 +// Google Test trace stack.
  1.3974 +void UnitTest::PushGTestTrace(const internal::TraceInfo& trace)
  1.3975 +    GTEST_LOCK_EXCLUDED_(mutex_) {
  1.3976 +  internal::MutexLock lock(&mutex_);
  1.3977 +  impl_->gtest_trace_stack().push_back(trace);
  1.3978 +}
  1.3979 +
  1.3980 +// Pops a trace from the per-thread Google Test trace stack.
  1.3981 +void UnitTest::PopGTestTrace()
  1.3982 +    GTEST_LOCK_EXCLUDED_(mutex_) {
  1.3983 +  internal::MutexLock lock(&mutex_);
  1.3984 +  impl_->gtest_trace_stack().pop_back();
  1.3985 +}
  1.3986 +
  1.3987 +namespace internal {
  1.3988 +
  1.3989 +UnitTestImpl::UnitTestImpl(UnitTest* parent)
  1.3990 +    : parent_(parent),
  1.3991 +#ifdef _MSC_VER
  1.3992 +# pragma warning(push)                    // Saves the current warning state.
  1.3993 +# pragma warning(disable:4355)            // Temporarily disables warning 4355
  1.3994 +                                         // (using this in initializer).
  1.3995 +      default_global_test_part_result_reporter_(this),
  1.3996 +      default_per_thread_test_part_result_reporter_(this),
  1.3997 +# pragma warning(pop)                     // Restores the warning state again.
  1.3998 +#else
  1.3999 +      default_global_test_part_result_reporter_(this),
  1.4000 +      default_per_thread_test_part_result_reporter_(this),
  1.4001 +#endif  // _MSC_VER
  1.4002 +      global_test_part_result_repoter_(
  1.4003 +          &default_global_test_part_result_reporter_),
  1.4004 +      per_thread_test_part_result_reporter_(
  1.4005 +          &default_per_thread_test_part_result_reporter_),
  1.4006 +#if GTEST_HAS_PARAM_TEST
  1.4007 +      parameterized_test_registry_(),
  1.4008 +      parameterized_tests_registered_(false),
  1.4009 +#endif  // GTEST_HAS_PARAM_TEST
  1.4010 +      last_death_test_case_(-1),
  1.4011 +      current_test_case_(NULL),
  1.4012 +      current_test_info_(NULL),
  1.4013 +      ad_hoc_test_result_(),
  1.4014 +      os_stack_trace_getter_(NULL),
  1.4015 +      post_flag_parse_init_performed_(false),
  1.4016 +      random_seed_(0),  // Will be overridden by the flag before first use.
  1.4017 +      random_(0),  // Will be reseeded before first use.
  1.4018 +      start_timestamp_(0),
  1.4019 +      elapsed_time_(0),
  1.4020 +#if GTEST_HAS_DEATH_TEST
  1.4021 +      internal_run_death_test_flag_(NULL),
  1.4022 +      death_test_factory_(new DefaultDeathTestFactory),
  1.4023 +#endif
  1.4024 +      // Will be overridden by the flag before first use.
  1.4025 +      catch_exceptions_(false) {
  1.4026 +  listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);
  1.4027 +}
  1.4028 +
  1.4029 +UnitTestImpl::~UnitTestImpl() {
  1.4030 +  // Deletes every TestCase.
  1.4031 +  ForEach(test_cases_, internal::Delete<TestCase>);
  1.4032 +
  1.4033 +  // Deletes every Environment.
  1.4034 +  ForEach(environments_, internal::Delete<Environment>);
  1.4035 +
  1.4036 +  delete os_stack_trace_getter_;
  1.4037 +}
  1.4038 +
  1.4039 +#if GTEST_HAS_DEATH_TEST
  1.4040 +// Disables event forwarding if the control is currently in a death test
  1.4041 +// subprocess. Must not be called before InitGoogleTest.
  1.4042 +void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
  1.4043 +  if (internal_run_death_test_flag_.get() != NULL)
  1.4044 +    listeners()->SuppressEventForwarding();
  1.4045 +}
  1.4046 +#endif  // GTEST_HAS_DEATH_TEST
  1.4047 +
  1.4048 +// Initializes event listeners performing XML output as specified by
  1.4049 +// UnitTestOptions. Must not be called before InitGoogleTest.
  1.4050 +void UnitTestImpl::ConfigureXmlOutput() {
  1.4051 +  const String& output_format = UnitTestOptions::GetOutputFormat();
  1.4052 +  if (output_format == "xml") {
  1.4053 +    listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
  1.4054 +        UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
  1.4055 +  } else if (output_format != "") {
  1.4056 +    printf("WARNING: unrecognized output format \"%s\" ignored.\n",
  1.4057 +           output_format.c_str());
  1.4058 +    fflush(stdout);
  1.4059 +  }
  1.4060 +}
  1.4061 +
  1.4062 +#if GTEST_CAN_STREAM_RESULTS_
  1.4063 +// Initializes event listeners for streaming test results in String form.
  1.4064 +// Must not be called before InitGoogleTest.
  1.4065 +void UnitTestImpl::ConfigureStreamingOutput() {
  1.4066 +  const string& target = GTEST_FLAG(stream_result_to);
  1.4067 +  if (!target.empty()) {
  1.4068 +    const size_t pos = target.find(':');
  1.4069 +    if (pos != string::npos) {
  1.4070 +      listeners()->Append(new StreamingListener(target.substr(0, pos),
  1.4071 +                                                target.substr(pos+1)));
  1.4072 +    } else {
  1.4073 +      printf("WARNING: unrecognized streaming target \"%s\" ignored.\n",
  1.4074 +             target.c_str());
  1.4075 +      fflush(stdout);
  1.4076 +    }
  1.4077 +  }
  1.4078 +}
  1.4079 +#endif  // GTEST_CAN_STREAM_RESULTS_
  1.4080 +
  1.4081 +// Performs initialization dependent upon flag values obtained in
  1.4082 +// ParseGoogleTestFlagsOnly.  Is called from InitGoogleTest after the call to
  1.4083 +// ParseGoogleTestFlagsOnly.  In case a user neglects to call InitGoogleTest
  1.4084 +// this function is also called from RunAllTests.  Since this function can be
  1.4085 +// called more than once, it has to be idempotent.
  1.4086 +void UnitTestImpl::PostFlagParsingInit() {
  1.4087 +  // Ensures that this function does not execute more than once.
  1.4088 +  if (!post_flag_parse_init_performed_) {
  1.4089 +    post_flag_parse_init_performed_ = true;
  1.4090 +
  1.4091 +#if GTEST_HAS_DEATH_TEST
  1.4092 +    InitDeathTestSubprocessControlInfo();
  1.4093 +    SuppressTestEventsIfInSubprocess();
  1.4094 +#endif  // GTEST_HAS_DEATH_TEST
  1.4095 +
  1.4096 +    // Registers parameterized tests. This makes parameterized tests
  1.4097 +    // available to the UnitTest reflection API without running
  1.4098 +    // RUN_ALL_TESTS.
  1.4099 +    RegisterParameterizedTests();
  1.4100 +
  1.4101 +    // Configures listeners for XML output. This makes it possible for users
  1.4102 +    // to shut down the default XML output before invoking RUN_ALL_TESTS.
  1.4103 +    ConfigureXmlOutput();
  1.4104 +
  1.4105 +#if GTEST_CAN_STREAM_RESULTS_
  1.4106 +    // Configures listeners for streaming test results to the specified server.
  1.4107 +    ConfigureStreamingOutput();
  1.4108 +#endif  // GTEST_CAN_STREAM_RESULTS_
  1.4109 +  }
  1.4110 +}
  1.4111 +
  1.4112 +// A predicate that checks the name of a TestCase against a known
  1.4113 +// value.
  1.4114 +//
  1.4115 +// This is used for implementation of the UnitTest class only.  We put
  1.4116 +// it in the anonymous namespace to prevent polluting the outer
  1.4117 +// namespace.
  1.4118 +//
  1.4119 +// TestCaseNameIs is copyable.
  1.4120 +class TestCaseNameIs {
  1.4121 + public:
  1.4122 +  // Constructor.
  1.4123 +  explicit TestCaseNameIs(const String& name)
  1.4124 +      : name_(name) {}
  1.4125 +
  1.4126 +  // Returns true iff the name of test_case matches name_.
  1.4127 +  bool operator()(const TestCase* test_case) const {
  1.4128 +    return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0;
  1.4129 +  }
  1.4130 +
  1.4131 + private:
  1.4132 +  String name_;
  1.4133 +};
  1.4134 +
  1.4135 +// Finds and returns a TestCase with the given name.  If one doesn't
  1.4136 +// exist, creates one and returns it.  It's the CALLER'S
  1.4137 +// RESPONSIBILITY to ensure that this function is only called WHEN THE
  1.4138 +// TESTS ARE NOT SHUFFLED.
  1.4139 +//
  1.4140 +// Arguments:
  1.4141 +//
  1.4142 +//   test_case_name: name of the test case
  1.4143 +//   type_param:     the name of the test case's type parameter, or NULL if
  1.4144 +//                   this is not a typed or a type-parameterized test case.
  1.4145 +//   set_up_tc:      pointer to the function that sets up the test case
  1.4146 +//   tear_down_tc:   pointer to the function that tears down the test case
  1.4147 +TestCase* UnitTestImpl::GetTestCase(const char* test_case_name,
  1.4148 +                                    const char* type_param,
  1.4149 +                                    Test::SetUpTestCaseFunc set_up_tc,
  1.4150 +                                    Test::TearDownTestCaseFunc tear_down_tc) {
  1.4151 +  // Can we find a TestCase with the given name?
  1.4152 +  const std::vector<TestCase*>::const_iterator test_case =
  1.4153 +      std::find_if(test_cases_.begin(), test_cases_.end(),
  1.4154 +                   TestCaseNameIs(test_case_name));
  1.4155 +
  1.4156 +  if (test_case != test_cases_.end())
  1.4157 +    return *test_case;
  1.4158 +
  1.4159 +  // No.  Let's create one.
  1.4160 +  TestCase* const new_test_case =
  1.4161 +      new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc);
  1.4162 +
  1.4163 +  // Is this a death test case?
  1.4164 +  if (internal::UnitTestOptions::MatchesFilter(String(test_case_name),
  1.4165 +                                               kDeathTestCaseFilter)) {
  1.4166 +    // Yes.  Inserts the test case after the last death test case
  1.4167 +    // defined so far.  This only works when the test cases haven't
  1.4168 +    // been shuffled.  Otherwise we may end up running a death test
  1.4169 +    // after a non-death test.
  1.4170 +    ++last_death_test_case_;
  1.4171 +    test_cases_.insert(test_cases_.begin() + last_death_test_case_,
  1.4172 +                       new_test_case);
  1.4173 +  } else {
  1.4174 +    // No.  Appends to the end of the list.
  1.4175 +    test_cases_.push_back(new_test_case);
  1.4176 +  }
  1.4177 +
  1.4178 +  test_case_indices_.push_back(static_cast<int>(test_case_indices_.size()));
  1.4179 +  return new_test_case;
  1.4180 +}
  1.4181 +
  1.4182 +// Helpers for setting up / tearing down the given environment.  They
  1.4183 +// are for use in the ForEach() function.
  1.4184 +static void SetUpEnvironment(Environment* env) { env->SetUp(); }
  1.4185 +static void TearDownEnvironment(Environment* env) { env->TearDown(); }
  1.4186 +
  1.4187 +// Runs all tests in this UnitTest object, prints the result, and
  1.4188 +// returns true if all tests are successful.  If any exception is
  1.4189 +// thrown during a test, the test is considered to be failed, but the
  1.4190 +// rest of the tests will still be run.
  1.4191 +//
  1.4192 +// When parameterized tests are enabled, it expands and registers
  1.4193 +// parameterized tests first in RegisterParameterizedTests().
  1.4194 +// All other functions called from RunAllTests() may safely assume that
  1.4195 +// parameterized tests are ready to be counted and run.
  1.4196 +bool UnitTestImpl::RunAllTests() {
  1.4197 +  // Makes sure InitGoogleTest() was called.
  1.4198 +  if (!GTestIsInitialized()) {
  1.4199 +    printf("%s",
  1.4200 +           "\nThis test program did NOT call ::testing::InitGoogleTest "
  1.4201 +           "before calling RUN_ALL_TESTS().  Please fix it.\n");
  1.4202 +    return false;
  1.4203 +  }
  1.4204 +
  1.4205 +  // Do not run any test if the --help flag was specified.
  1.4206 +  if (g_help_flag)
  1.4207 +    return true;
  1.4208 +
  1.4209 +  // Repeats the call to the post-flag parsing initialization in case the
  1.4210 +  // user didn't call InitGoogleTest.
  1.4211 +  PostFlagParsingInit();
  1.4212 +
  1.4213 +  // Even if sharding is not on, test runners may want to use the
  1.4214 +  // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
  1.4215 +  // protocol.
  1.4216 +  internal::WriteToShardStatusFileIfNeeded();
  1.4217 +
  1.4218 +  // True iff we are in a subprocess for running a thread-safe-style
  1.4219 +  // death test.
  1.4220 +  bool in_subprocess_for_death_test = false;
  1.4221 +
  1.4222 +#if GTEST_HAS_DEATH_TEST
  1.4223 +  in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL);
  1.4224 +#endif  // GTEST_HAS_DEATH_TEST
  1.4225 +
  1.4226 +  const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
  1.4227 +                                        in_subprocess_for_death_test);
  1.4228 +
  1.4229 +  // Compares the full test names with the filter to decide which
  1.4230 +  // tests to run.
  1.4231 +  const bool has_tests_to_run = FilterTests(should_shard
  1.4232 +                                              ? HONOR_SHARDING_PROTOCOL
  1.4233 +                                              : IGNORE_SHARDING_PROTOCOL) > 0;
  1.4234 +
  1.4235 +  // Lists the tests and exits if the --gtest_list_tests flag was specified.
  1.4236 +  if (GTEST_FLAG(list_tests)) {
  1.4237 +    // This must be called *after* FilterTests() has been called.
  1.4238 +    ListTestsMatchingFilter();
  1.4239 +    return true;
  1.4240 +  }
  1.4241 +
  1.4242 +  random_seed_ = GTEST_FLAG(shuffle) ?
  1.4243 +      GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;
  1.4244 +
  1.4245 +  // True iff at least one test has failed.
  1.4246 +  bool failed = false;
  1.4247 +
  1.4248 +  TestEventListener* repeater = listeners()->repeater();
  1.4249 +
  1.4250 +  start_timestamp_ = GetTimeInMillis();
  1.4251 +  repeater->OnTestProgramStart(*parent_);
  1.4252 +
  1.4253 +  // How many times to repeat the tests?  We don't want to repeat them
  1.4254 +  // when we are inside the subprocess of a death test.
  1.4255 +  const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);
  1.4256 +  // Repeats forever if the repeat count is negative.
  1.4257 +  const bool forever = repeat < 0;
  1.4258 +  for (int i = 0; forever || i != repeat; i++) {
  1.4259 +    // We want to preserve failures generated by ad-hoc test
  1.4260 +    // assertions executed before RUN_ALL_TESTS().
  1.4261 +    ClearNonAdHocTestResult();
  1.4262 +
  1.4263 +    const TimeInMillis start = GetTimeInMillis();
  1.4264 +
  1.4265 +    // Shuffles test cases and tests if requested.
  1.4266 +    if (has_tests_to_run && GTEST_FLAG(shuffle)) {
  1.4267 +      random()->Reseed(random_seed_);
  1.4268 +      // This should be done before calling OnTestIterationStart(),
  1.4269 +      // such that a test event listener can see the actual test order
  1.4270 +      // in the event.
  1.4271 +      ShuffleTests();
  1.4272 +    }
  1.4273 +
  1.4274 +    // Tells the unit test event listeners that the tests are about to start.
  1.4275 +    repeater->OnTestIterationStart(*parent_, i);
  1.4276 +
  1.4277 +    // Runs each test case if there is at least one test to run.
  1.4278 +    if (has_tests_to_run) {
  1.4279 +      // Sets up all environments beforehand.
  1.4280 +      repeater->OnEnvironmentsSetUpStart(*parent_);
  1.4281 +      ForEach(environments_, SetUpEnvironment);
  1.4282 +      repeater->OnEnvironmentsSetUpEnd(*parent_);
  1.4283 +
  1.4284 +      // Runs the tests only if there was no fatal failure during global
  1.4285 +      // set-up.
  1.4286 +      if (!Test::HasFatalFailure()) {
  1.4287 +        for (int test_index = 0; test_index < total_test_case_count();
  1.4288 +             test_index++) {
  1.4289 +          GetMutableTestCase(test_index)->Run();
  1.4290 +        }
  1.4291 +      }
  1.4292 +
  1.4293 +      // Tears down all environments in reverse order afterwards.
  1.4294 +      repeater->OnEnvironmentsTearDownStart(*parent_);
  1.4295 +      std::for_each(environments_.rbegin(), environments_.rend(),
  1.4296 +                    TearDownEnvironment);
  1.4297 +      repeater->OnEnvironmentsTearDownEnd(*parent_);
  1.4298 +    }
  1.4299 +
  1.4300 +    elapsed_time_ = GetTimeInMillis() - start;
  1.4301 +
  1.4302 +    // Tells the unit test event listener that the tests have just finished.
  1.4303 +    repeater->OnTestIterationEnd(*parent_, i);
  1.4304 +
  1.4305 +    // Gets the result and clears it.
  1.4306 +    if (!Passed()) {
  1.4307 +      failed = true;
  1.4308 +    }
  1.4309 +
  1.4310 +    // Restores the original test order after the iteration.  This
  1.4311 +    // allows the user to quickly repro a failure that happens in the
  1.4312 +    // N-th iteration without repeating the first (N - 1) iterations.
  1.4313 +    // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in
  1.4314 +    // case the user somehow changes the value of the flag somewhere
  1.4315 +    // (it's always safe to unshuffle the tests).
  1.4316 +    UnshuffleTests();
  1.4317 +
  1.4318 +    if (GTEST_FLAG(shuffle)) {
  1.4319 +      // Picks a new random seed for each iteration.
  1.4320 +      random_seed_ = GetNextRandomSeed(random_seed_);
  1.4321 +    }
  1.4322 +  }
  1.4323 +
  1.4324 +  repeater->OnTestProgramEnd(*parent_);
  1.4325 +
  1.4326 +  return !failed;
  1.4327 +}
  1.4328 +
  1.4329 +// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
  1.4330 +// if the variable is present. If a file already exists at this location, this
  1.4331 +// function will write over it. If the variable is present, but the file cannot
  1.4332 +// be created, prints an error and exits.
  1.4333 +void WriteToShardStatusFileIfNeeded() {
  1.4334 +  const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);
  1.4335 +  if (test_shard_file != NULL) {
  1.4336 +    FILE* const file = posix::FOpen(test_shard_file, "w");
  1.4337 +    if (file == NULL) {
  1.4338 +      ColoredPrintf(COLOR_RED,
  1.4339 +                    "Could not write to the test shard status file \"%s\" "
  1.4340 +                    "specified by the %s environment variable.\n",
  1.4341 +                    test_shard_file, kTestShardStatusFile);
  1.4342 +      fflush(stdout);
  1.4343 +      exit(EXIT_FAILURE);
  1.4344 +    }
  1.4345 +    fclose(file);
  1.4346 +  }
  1.4347 +}
  1.4348 +
  1.4349 +// Checks whether sharding is enabled by examining the relevant
  1.4350 +// environment variable values. If the variables are present,
  1.4351 +// but inconsistent (i.e., shard_index >= total_shards), prints
  1.4352 +// an error and exits. If in_subprocess_for_death_test, sharding is
  1.4353 +// disabled because it must only be applied to the original test
  1.4354 +// process. Otherwise, we could filter out death tests we intended to execute.
  1.4355 +bool ShouldShard(const char* total_shards_env,
  1.4356 +                 const char* shard_index_env,
  1.4357 +                 bool in_subprocess_for_death_test) {
  1.4358 +  if (in_subprocess_for_death_test) {
  1.4359 +    return false;
  1.4360 +  }
  1.4361 +
  1.4362 +  const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1);
  1.4363 +  const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1);
  1.4364 +
  1.4365 +  if (total_shards == -1 && shard_index == -1) {
  1.4366 +    return false;
  1.4367 +  } else if (total_shards == -1 && shard_index != -1) {
  1.4368 +    const Message msg = Message()
  1.4369 +      << "Invalid environment variables: you have "
  1.4370 +      << kTestShardIndex << " = " << shard_index
  1.4371 +      << ", but have left " << kTestTotalShards << " unset.\n";
  1.4372 +    ColoredPrintf(COLOR_RED, msg.GetString().c_str());
  1.4373 +    fflush(stdout);
  1.4374 +    exit(EXIT_FAILURE);
  1.4375 +  } else if (total_shards != -1 && shard_index == -1) {
  1.4376 +    const Message msg = Message()
  1.4377 +      << "Invalid environment variables: you have "
  1.4378 +      << kTestTotalShards << " = " << total_shards
  1.4379 +      << ", but have left " << kTestShardIndex << " unset.\n";
  1.4380 +    ColoredPrintf(COLOR_RED, msg.GetString().c_str());
  1.4381 +    fflush(stdout);
  1.4382 +    exit(EXIT_FAILURE);
  1.4383 +  } else if (shard_index < 0 || shard_index >= total_shards) {
  1.4384 +    const Message msg = Message()
  1.4385 +      << "Invalid environment variables: we require 0 <= "
  1.4386 +      << kTestShardIndex << " < " << kTestTotalShards
  1.4387 +      << ", but you have " << kTestShardIndex << "=" << shard_index
  1.4388 +      << ", " << kTestTotalShards << "=" << total_shards << ".\n";
  1.4389 +    ColoredPrintf(COLOR_RED, msg.GetString().c_str());
  1.4390 +    fflush(stdout);
  1.4391 +    exit(EXIT_FAILURE);
  1.4392 +  }
  1.4393 +
  1.4394 +  return total_shards > 1;
  1.4395 +}
  1.4396 +
  1.4397 +// Parses the environment variable var as an Int32. If it is unset,
  1.4398 +// returns default_val. If it is not an Int32, prints an error
  1.4399 +// and aborts.
  1.4400 +Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) {
  1.4401 +  const char* str_val = posix::GetEnv(var);
  1.4402 +  if (str_val == NULL) {
  1.4403 +    return default_val;
  1.4404 +  }
  1.4405 +
  1.4406 +  Int32 result;
  1.4407 +  if (!ParseInt32(Message() << "The value of environment variable " << var,
  1.4408 +                  str_val, &result)) {
  1.4409 +    exit(EXIT_FAILURE);
  1.4410 +  }
  1.4411 +  return result;
  1.4412 +}
  1.4413 +
  1.4414 +// Given the total number of shards, the shard index, and the test id,
  1.4415 +// returns true iff the test should be run on this shard. The test id is
  1.4416 +// some arbitrary but unique non-negative integer assigned to each test
  1.4417 +// method. Assumes that 0 <= shard_index < total_shards.
  1.4418 +bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
  1.4419 +  return (test_id % total_shards) == shard_index;
  1.4420 +}
  1.4421 +
  1.4422 +// Compares the name of each test with the user-specified filter to
  1.4423 +// decide whether the test should be run, then records the result in
  1.4424 +// each TestCase and TestInfo object.
  1.4425 +// If shard_tests == true, further filters tests based on sharding
  1.4426 +// variables in the environment - see
  1.4427 +// http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide.
  1.4428 +// Returns the number of tests that should run.
  1.4429 +int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
  1.4430 +  const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?
  1.4431 +      Int32FromEnvOrDie(kTestTotalShards, -1) : -1;
  1.4432 +  const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?
  1.4433 +      Int32FromEnvOrDie(kTestShardIndex, -1) : -1;
  1.4434 +
  1.4435 +  // num_runnable_tests are the number of tests that will
  1.4436 +  // run across all shards (i.e., match filter and are not disabled).
  1.4437 +  // num_selected_tests are the number of tests to be run on
  1.4438 +  // this shard.
  1.4439 +  int num_runnable_tests = 0;
  1.4440 +  int num_selected_tests = 0;
  1.4441 +  for (size_t i = 0; i < test_cases_.size(); i++) {
  1.4442 +    TestCase* const test_case = test_cases_[i];
  1.4443 +    const String &test_case_name = test_case->name();
  1.4444 +    test_case->set_should_run(false);
  1.4445 +
  1.4446 +    for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
  1.4447 +      TestInfo* const test_info = test_case->test_info_list()[j];
  1.4448 +      const String test_name(test_info->name());
  1.4449 +      // A test is disabled if test case name or test name matches
  1.4450 +      // kDisableTestFilter.
  1.4451 +      const bool is_disabled =
  1.4452 +          internal::UnitTestOptions::MatchesFilter(test_case_name,
  1.4453 +                                                   kDisableTestFilter) ||
  1.4454 +          internal::UnitTestOptions::MatchesFilter(test_name,
  1.4455 +                                                   kDisableTestFilter);
  1.4456 +      test_info->is_disabled_ = is_disabled;
  1.4457 +
  1.4458 +      const bool matches_filter =
  1.4459 +          internal::UnitTestOptions::FilterMatchesTest(test_case_name,
  1.4460 +                                                       test_name);
  1.4461 +      test_info->matches_filter_ = matches_filter;
  1.4462 +
  1.4463 +      const bool is_runnable =
  1.4464 +          (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
  1.4465 +          matches_filter;
  1.4466 +
  1.4467 +      const bool is_selected = is_runnable &&
  1.4468 +          (shard_tests == IGNORE_SHARDING_PROTOCOL ||
  1.4469 +           ShouldRunTestOnShard(total_shards, shard_index,
  1.4470 +                                num_runnable_tests));
  1.4471 +
  1.4472 +      num_runnable_tests += is_runnable;
  1.4473 +      num_selected_tests += is_selected;
  1.4474 +
  1.4475 +      test_info->should_run_ = is_selected;
  1.4476 +      test_case->set_should_run(test_case->should_run() || is_selected);
  1.4477 +    }
  1.4478 +  }
  1.4479 +  return num_selected_tests;
  1.4480 +}
  1.4481 +
  1.4482 +// Prints the names of the tests matching the user-specified filter flag.
  1.4483 +void UnitTestImpl::ListTestsMatchingFilter() {
  1.4484 +  for (size_t i = 0; i < test_cases_.size(); i++) {
  1.4485 +    const TestCase* const test_case = test_cases_[i];
  1.4486 +    bool printed_test_case_name = false;
  1.4487 +
  1.4488 +    for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
  1.4489 +      const TestInfo* const test_info =
  1.4490 +          test_case->test_info_list()[j];
  1.4491 +      if (test_info->matches_filter_) {
  1.4492 +        if (!printed_test_case_name) {
  1.4493 +          printed_test_case_name = true;
  1.4494 +          printf("%s.\n", test_case->name());
  1.4495 +        }
  1.4496 +        printf("  %s\n", test_info->name());
  1.4497 +      }
  1.4498 +    }
  1.4499 +  }
  1.4500 +  fflush(stdout);
  1.4501 +}
  1.4502 +
  1.4503 +// Sets the OS stack trace getter.
  1.4504 +//
  1.4505 +// Does nothing if the input and the current OS stack trace getter are
  1.4506 +// the same; otherwise, deletes the old getter and makes the input the
  1.4507 +// current getter.
  1.4508 +void UnitTestImpl::set_os_stack_trace_getter(
  1.4509 +    OsStackTraceGetterInterface* getter) {
  1.4510 +  if (os_stack_trace_getter_ != getter) {
  1.4511 +    delete os_stack_trace_getter_;
  1.4512 +    os_stack_trace_getter_ = getter;
  1.4513 +  }
  1.4514 +}
  1.4515 +
  1.4516 +// Returns the current OS stack trace getter if it is not NULL;
  1.4517 +// otherwise, creates an OsStackTraceGetter, makes it the current
  1.4518 +// getter, and returns it.
  1.4519 +OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
  1.4520 +  if (os_stack_trace_getter_ == NULL) {
  1.4521 +    os_stack_trace_getter_ = new OsStackTraceGetter;
  1.4522 +  }
  1.4523 +
  1.4524 +  return os_stack_trace_getter_;
  1.4525 +}
  1.4526 +
  1.4527 +// Returns the TestResult for the test that's currently running, or
  1.4528 +// the TestResult for the ad hoc test if no test is running.
  1.4529 +TestResult* UnitTestImpl::current_test_result() {
  1.4530 +  return current_test_info_ ?
  1.4531 +      &(current_test_info_->result_) : &ad_hoc_test_result_;
  1.4532 +}
  1.4533 +
  1.4534 +// Shuffles all test cases, and the tests within each test case,
  1.4535 +// making sure that death tests are still run first.
  1.4536 +void UnitTestImpl::ShuffleTests() {
  1.4537 +  // Shuffles the death test cases.
  1.4538 +  ShuffleRange(random(), 0, last_death_test_case_ + 1, &test_case_indices_);
  1.4539 +
  1.4540 +  // Shuffles the non-death test cases.
  1.4541 +  ShuffleRange(random(), last_death_test_case_ + 1,
  1.4542 +               static_cast<int>(test_cases_.size()), &test_case_indices_);
  1.4543 +
  1.4544 +  // Shuffles the tests inside each test case.
  1.4545 +  for (size_t i = 0; i < test_cases_.size(); i++) {
  1.4546 +    test_cases_[i]->ShuffleTests(random());
  1.4547 +  }
  1.4548 +}
  1.4549 +
  1.4550 +// Restores the test cases and tests to their order before the first shuffle.
  1.4551 +void UnitTestImpl::UnshuffleTests() {
  1.4552 +  for (size_t i = 0; i < test_cases_.size(); i++) {
  1.4553 +    // Unshuffles the tests in each test case.
  1.4554 +    test_cases_[i]->UnshuffleTests();
  1.4555 +    // Resets the index of each test case.
  1.4556 +    test_case_indices_[i] = static_cast<int>(i);
  1.4557 +  }
  1.4558 +}
  1.4559 +
  1.4560 +// Returns the current OS stack trace as a String.
  1.4561 +//
  1.4562 +// The maximum number of stack frames to be included is specified by
  1.4563 +// the gtest_stack_trace_depth flag.  The skip_count parameter
  1.4564 +// specifies the number of top frames to be skipped, which doesn't
  1.4565 +// count against the number of frames to be included.
  1.4566 +//
  1.4567 +// For example, if Foo() calls Bar(), which in turn calls
  1.4568 +// GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
  1.4569 +// the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
  1.4570 +String GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/,
  1.4571 +                                       int skip_count) {
  1.4572 +  // We pass skip_count + 1 to skip this wrapper function in addition
  1.4573 +  // to what the user really wants to skip.
  1.4574 +  return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
  1.4575 +}
  1.4576 +
  1.4577 +// Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to
  1.4578 +// suppress unreachable code warnings.
  1.4579 +namespace {
  1.4580 +class ClassUniqueToAlwaysTrue {};
  1.4581 +}
  1.4582 +
  1.4583 +bool IsTrue(bool condition) { return condition; }
  1.4584 +
  1.4585 +bool AlwaysTrue() {
  1.4586 +#if GTEST_HAS_EXCEPTIONS
  1.4587 +  // This condition is always false so AlwaysTrue() never actually throws,
  1.4588 +  // but it makes the compiler think that it may throw.
  1.4589 +  if (IsTrue(false))
  1.4590 +    throw ClassUniqueToAlwaysTrue();
  1.4591 +#endif  // GTEST_HAS_EXCEPTIONS
  1.4592 +  return true;
  1.4593 +}
  1.4594 +
  1.4595 +// If *pstr starts with the given prefix, modifies *pstr to be right
  1.4596 +// past the prefix and returns true; otherwise leaves *pstr unchanged
  1.4597 +// and returns false.  None of pstr, *pstr, and prefix can be NULL.
  1.4598 +bool SkipPrefix(const char* prefix, const char** pstr) {
  1.4599 +  const size_t prefix_len = strlen(prefix);
  1.4600 +  if (strncmp(*pstr, prefix, prefix_len) == 0) {
  1.4601 +    *pstr += prefix_len;
  1.4602 +    return true;
  1.4603 +  }
  1.4604 +  return false;
  1.4605 +}
  1.4606 +
  1.4607 +// Parses a string as a command line flag.  The string should have
  1.4608 +// the format "--flag=value".  When def_optional is true, the "=value"
  1.4609 +// part can be omitted.
  1.4610 +//
  1.4611 +// Returns the value of the flag, or NULL if the parsing failed.
  1.4612 +const char* ParseFlagValue(const char* str,
  1.4613 +                           const char* flag,
  1.4614 +                           bool def_optional) {
  1.4615 +  // str and flag must not be NULL.
  1.4616 +  if (str == NULL || flag == NULL) return NULL;
  1.4617 +
  1.4618 +  // The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
  1.4619 +  const String flag_str = String::Format("--%s%s", GTEST_FLAG_PREFIX_, flag);
  1.4620 +  const size_t flag_len = flag_str.length();
  1.4621 +  if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;
  1.4622 +
  1.4623 +  // Skips the flag name.
  1.4624 +  const char* flag_end = str + flag_len;
  1.4625 +
  1.4626 +  // When def_optional is true, it's OK to not have a "=value" part.
  1.4627 +  if (def_optional && (flag_end[0] == '\0')) {
  1.4628 +    return flag_end;
  1.4629 +  }
  1.4630 +
  1.4631 +  // If def_optional is true and there are more characters after the
  1.4632 +  // flag name, or if def_optional is false, there must be a '=' after
  1.4633 +  // the flag name.
  1.4634 +  if (flag_end[0] != '=') return NULL;
  1.4635 +
  1.4636 +  // Returns the string after "=".
  1.4637 +  return flag_end + 1;
  1.4638 +}
  1.4639 +
  1.4640 +// Parses a string for a bool flag, in the form of either
  1.4641 +// "--flag=value" or "--flag".
  1.4642 +//
  1.4643 +// In the former case, the value is taken as true as long as it does
  1.4644 +// not start with '0', 'f', or 'F'.
  1.4645 +//
  1.4646 +// In the latter case, the value is taken as true.
  1.4647 +//
  1.4648 +// On success, stores the value of the flag in *value, and returns
  1.4649 +// true.  On failure, returns false without changing *value.
  1.4650 +bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
  1.4651 +  // Gets the value of the flag as a string.
  1.4652 +  const char* const value_str = ParseFlagValue(str, flag, true);
  1.4653 +
  1.4654 +  // Aborts if the parsing failed.
  1.4655 +  if (value_str == NULL) return false;
  1.4656 +
  1.4657 +  // Converts the string value to a bool.
  1.4658 +  *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
  1.4659 +  return true;
  1.4660 +}
  1.4661 +
  1.4662 +// Parses a string for an Int32 flag, in the form of
  1.4663 +// "--flag=value".
  1.4664 +//
  1.4665 +// On success, stores the value of the flag in *value, and returns
  1.4666 +// true.  On failure, returns false without changing *value.
  1.4667 +bool ParseInt32Flag(const char* str, const char* flag, Int32* value) {
  1.4668 +  // Gets the value of the flag as a string.
  1.4669 +  const char* const value_str = ParseFlagValue(str, flag, false);
  1.4670 +
  1.4671 +  // Aborts if the parsing failed.
  1.4672 +  if (value_str == NULL) return false;
  1.4673 +
  1.4674 +  // Sets *value to the value of the flag.
  1.4675 +  return ParseInt32(Message() << "The value of flag --" << flag,
  1.4676 +                    value_str, value);
  1.4677 +}
  1.4678 +
  1.4679 +// Parses a string for a string flag, in the form of
  1.4680 +// "--flag=value".
  1.4681 +//
  1.4682 +// On success, stores the value of the flag in *value, and returns
  1.4683 +// true.  On failure, returns false without changing *value.
  1.4684 +bool ParseStringFlag(const char* str, const char* flag, String* value) {
  1.4685 +  // Gets the value of the flag as a string.
  1.4686 +  const char* const value_str = ParseFlagValue(str, flag, false);
  1.4687 +
  1.4688 +  // Aborts if the parsing failed.
  1.4689 +  if (value_str == NULL) return false;
  1.4690 +
  1.4691 +  // Sets *value to the value of the flag.
  1.4692 +  *value = value_str;
  1.4693 +  return true;
  1.4694 +}
  1.4695 +
  1.4696 +// Determines whether a string has a prefix that Google Test uses for its
  1.4697 +// flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.
  1.4698 +// If Google Test detects that a command line flag has its prefix but is not
  1.4699 +// recognized, it will print its help message. Flags starting with
  1.4700 +// GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
  1.4701 +// internal flags and do not trigger the help message.
  1.4702 +static bool HasGoogleTestFlagPrefix(const char* str) {
  1.4703 +  return (SkipPrefix("--", &str) ||
  1.4704 +          SkipPrefix("-", &str) ||
  1.4705 +          SkipPrefix("/", &str)) &&
  1.4706 +         !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
  1.4707 +         (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
  1.4708 +          SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str));
  1.4709 +}
  1.4710 +
  1.4711 +// Prints a string containing code-encoded text.  The following escape
  1.4712 +// sequences can be used in the string to control the text color:
  1.4713 +//
  1.4714 +//   @@    prints a single '@' character.
  1.4715 +//   @R    changes the color to red.
  1.4716 +//   @G    changes the color to green.
  1.4717 +//   @Y    changes the color to yellow.
  1.4718 +//   @D    changes to the default terminal text color.
  1.4719 +//
  1.4720 +// TODO(wan@google.com): Write tests for this once we add stdout
  1.4721 +// capturing to Google Test.
  1.4722 +static void PrintColorEncoded(const char* str) {
  1.4723 +  GTestColor color = COLOR_DEFAULT;  // The current color.
  1.4724 +
  1.4725 +  // Conceptually, we split the string into segments divided by escape
  1.4726 +  // sequences.  Then we print one segment at a time.  At the end of
  1.4727 +  // each iteration, the str pointer advances to the beginning of the
  1.4728 +  // next segment.
  1.4729 +  for (;;) {
  1.4730 +    const char* p = strchr(str, '@');
  1.4731 +    if (p == NULL) {
  1.4732 +      ColoredPrintf(color, "%s", str);
  1.4733 +      return;
  1.4734 +    }
  1.4735 +
  1.4736 +    ColoredPrintf(color, "%s", String(str, p - str).c_str());
  1.4737 +
  1.4738 +    const char ch = p[1];
  1.4739 +    str = p + 2;
  1.4740 +    if (ch == '@') {
  1.4741 +      ColoredPrintf(color, "@");
  1.4742 +    } else if (ch == 'D') {
  1.4743 +      color = COLOR_DEFAULT;
  1.4744 +    } else if (ch == 'R') {
  1.4745 +      color = COLOR_RED;
  1.4746 +    } else if (ch == 'G') {
  1.4747 +      color = COLOR_GREEN;
  1.4748 +    } else if (ch == 'Y') {
  1.4749 +      color = COLOR_YELLOW;
  1.4750 +    } else {
  1.4751 +      --str;
  1.4752 +    }
  1.4753 +  }
  1.4754 +}
  1.4755 +
  1.4756 +static const char kColorEncodedHelpMessage[] =
  1.4757 +"This program contains tests written using " GTEST_NAME_ ". You can use the\n"
  1.4758 +"following command line flags to control its behavior:\n"
  1.4759 +"\n"
  1.4760 +"Test Selection:\n"
  1.4761 +"  @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n"
  1.4762 +"      List the names of all tests instead of running them. The name of\n"
  1.4763 +"      TEST(Foo, Bar) is \"Foo.Bar\".\n"
  1.4764 +"  @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS"
  1.4765 +    "[@G-@YNEGATIVE_PATTERNS]@D\n"
  1.4766 +"      Run only the tests whose name matches one of the positive patterns but\n"
  1.4767 +"      none of the negative patterns. '?' matches any single character; '*'\n"
  1.4768 +"      matches any substring; ':' separates two patterns.\n"
  1.4769 +"  @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n"
  1.4770 +"      Run all disabled tests too.\n"
  1.4771 +"\n"
  1.4772 +"Test Execution:\n"
  1.4773 +"  @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n"
  1.4774 +"      Run the tests repeatedly; use a negative count to repeat forever.\n"
  1.4775 +"  @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n"
  1.4776 +"      Randomize tests' orders on every iteration.\n"
  1.4777 +"  @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n"
  1.4778 +"      Random number seed to use for shuffling test orders (between 1 and\n"
  1.4779 +"      99999, or 0 to use a seed based on the current time).\n"
  1.4780 +"\n"
  1.4781 +"Test Output:\n"
  1.4782 +"  @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
  1.4783 +"      Enable/disable colored output. The default is @Gauto@D.\n"
  1.4784 +"  -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n"
  1.4785 +"      Don't print the elapsed time of each test.\n"
  1.4786 +"  @G--" GTEST_FLAG_PREFIX_ "output=xml@Y[@G:@YDIRECTORY_PATH@G"
  1.4787 +    GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n"
  1.4788 +"      Generate an XML report in the given directory or with the given file\n"
  1.4789 +"      name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n"
  1.4790 +#if GTEST_CAN_STREAM_RESULTS_
  1.4791 +"  @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n"
  1.4792 +"      Stream test results to the given server.\n"
  1.4793 +#endif  // GTEST_CAN_STREAM_RESULTS_
  1.4794 +"\n"
  1.4795 +"Assertion Behavior:\n"
  1.4796 +#if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
  1.4797 +"  @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
  1.4798 +"      Set the default death test style.\n"
  1.4799 +#endif  // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
  1.4800 +"  @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n"
  1.4801 +"      Turn assertion failures into debugger break-points.\n"
  1.4802 +"  @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n"
  1.4803 +"      Turn assertion failures into C++ exceptions.\n"
  1.4804 +"  @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n"
  1.4805 +"      Do not report exceptions as test failures. Instead, allow them\n"
  1.4806 +"      to crash the program or throw a pop-up (on Windows).\n"
  1.4807 +"\n"
  1.4808 +"Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set "
  1.4809 +    "the corresponding\n"
  1.4810 +"environment variable of a flag (all letters in upper-case). For example, to\n"
  1.4811 +"disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_
  1.4812 +    "color=no@D or set\n"
  1.4813 +"the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n"
  1.4814 +"\n"
  1.4815 +"For more information, please read the " GTEST_NAME_ " documentation at\n"
  1.4816 +"@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n"
  1.4817 +"(not one in your own code or tests), please report it to\n"
  1.4818 +"@G<" GTEST_DEV_EMAIL_ ">@D.\n";
  1.4819 +
  1.4820 +// Parses the command line for Google Test flags, without initializing
  1.4821 +// other parts of Google Test.  The type parameter CharType can be
  1.4822 +// instantiated to either char or wchar_t.
  1.4823 +template <typename CharType>
  1.4824 +void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
  1.4825 +  for (int i = 1; i < *argc; i++) {
  1.4826 +    const String arg_string = StreamableToString(argv[i]);
  1.4827 +    const char* const arg = arg_string.c_str();
  1.4828 +
  1.4829 +    using internal::ParseBoolFlag;
  1.4830 +    using internal::ParseInt32Flag;
  1.4831 +    using internal::ParseStringFlag;
  1.4832 +
  1.4833 +    // Do we see a Google Test flag?
  1.4834 +    if (ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,
  1.4835 +                      &GTEST_FLAG(also_run_disabled_tests)) ||
  1.4836 +        ParseBoolFlag(arg, kBreakOnFailureFlag,
  1.4837 +                      &GTEST_FLAG(break_on_failure)) ||
  1.4838 +        ParseBoolFlag(arg, kCatchExceptionsFlag,
  1.4839 +                      &GTEST_FLAG(catch_exceptions)) ||
  1.4840 +        ParseStringFlag(arg, kColorFlag, &GTEST_FLAG(color)) ||
  1.4841 +        ParseStringFlag(arg, kDeathTestStyleFlag,
  1.4842 +                        &GTEST_FLAG(death_test_style)) ||
  1.4843 +        ParseBoolFlag(arg, kDeathTestUseFork,
  1.4844 +                      &GTEST_FLAG(death_test_use_fork)) ||
  1.4845 +        ParseStringFlag(arg, kFilterFlag, &GTEST_FLAG(filter)) ||
  1.4846 +        ParseStringFlag(arg, kInternalRunDeathTestFlag,
  1.4847 +                        &GTEST_FLAG(internal_run_death_test)) ||
  1.4848 +        ParseBoolFlag(arg, kListTestsFlag, &GTEST_FLAG(list_tests)) ||
  1.4849 +        ParseStringFlag(arg, kOutputFlag, &GTEST_FLAG(output)) ||
  1.4850 +        ParseBoolFlag(arg, kPrintTimeFlag, &GTEST_FLAG(print_time)) ||
  1.4851 +        ParseInt32Flag(arg, kRandomSeedFlag, &GTEST_FLAG(random_seed)) ||
  1.4852 +        ParseInt32Flag(arg, kRepeatFlag, &GTEST_FLAG(repeat)) ||
  1.4853 +        ParseBoolFlag(arg, kShuffleFlag, &GTEST_FLAG(shuffle)) ||
  1.4854 +        ParseInt32Flag(arg, kStackTraceDepthFlag,
  1.4855 +                       &GTEST_FLAG(stack_trace_depth)) ||
  1.4856 +        ParseStringFlag(arg, kStreamResultToFlag,
  1.4857 +                        &GTEST_FLAG(stream_result_to)) ||
  1.4858 +        ParseBoolFlag(arg, kThrowOnFailureFlag,
  1.4859 +                      &GTEST_FLAG(throw_on_failure))
  1.4860 +        ) {
  1.4861 +      // Yes.  Shift the remainder of the argv list left by one.  Note
  1.4862 +      // that argv has (*argc + 1) elements, the last one always being
  1.4863 +      // NULL.  The following loop moves the trailing NULL element as
  1.4864 +      // well.
  1.4865 +      for (int j = i; j != *argc; j++) {
  1.4866 +        argv[j] = argv[j + 1];
  1.4867 +      }
  1.4868 +
  1.4869 +      // Decrements the argument count.
  1.4870 +      (*argc)--;
  1.4871 +
  1.4872 +      // We also need to decrement the iterator as we just removed
  1.4873 +      // an element.
  1.4874 +      i--;
  1.4875 +    } else if (arg_string == "--help" || arg_string == "-h" ||
  1.4876 +               arg_string == "-?" || arg_string == "/?" ||
  1.4877 +               HasGoogleTestFlagPrefix(arg)) {
  1.4878 +      // Both help flag and unrecognized Google Test flags (excluding
  1.4879 +      // internal ones) trigger help display.
  1.4880 +      g_help_flag = true;
  1.4881 +    }
  1.4882 +  }
  1.4883 +
  1.4884 +  if (g_help_flag) {
  1.4885 +    // We print the help here instead of in RUN_ALL_TESTS(), as the
  1.4886 +    // latter may not be called at all if the user is using Google
  1.4887 +    // Test with another testing framework.
  1.4888 +    PrintColorEncoded(kColorEncodedHelpMessage);
  1.4889 +  }
  1.4890 +}
  1.4891 +
  1.4892 +// Parses the command line for Google Test flags, without initializing
  1.4893 +// other parts of Google Test.
  1.4894 +void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
  1.4895 +  ParseGoogleTestFlagsOnlyImpl(argc, argv);
  1.4896 +}
  1.4897 +void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {
  1.4898 +  ParseGoogleTestFlagsOnlyImpl(argc, argv);
  1.4899 +}
  1.4900 +
  1.4901 +// The internal implementation of InitGoogleTest().
  1.4902 +//
  1.4903 +// The type parameter CharType can be instantiated to either char or
  1.4904 +// wchar_t.
  1.4905 +template <typename CharType>
  1.4906 +void InitGoogleTestImpl(int* argc, CharType** argv) {
  1.4907 +  g_init_gtest_count++;
  1.4908 +
  1.4909 +  // We don't want to run the initialization code twice.
  1.4910 +  if (g_init_gtest_count != 1) return;
  1.4911 +
  1.4912 +  if (*argc <= 0) return;
  1.4913 +
  1.4914 +  internal::g_executable_path = internal::StreamableToString(argv[0]);
  1.4915 +
  1.4916 +#if GTEST_HAS_DEATH_TEST
  1.4917 +
  1.4918 +  g_argvs.clear();
  1.4919 +  for (int i = 0; i != *argc; i++) {
  1.4920 +    g_argvs.push_back(StreamableToString(argv[i]));
  1.4921 +  }
  1.4922 +
  1.4923 +#endif  // GTEST_HAS_DEATH_TEST
  1.4924 +
  1.4925 +  ParseGoogleTestFlagsOnly(argc, argv);
  1.4926 +  GetUnitTestImpl()->PostFlagParsingInit();
  1.4927 +}
  1.4928 +
  1.4929 +}  // namespace internal
  1.4930 +
  1.4931 +// Initializes Google Test.  This must be called before calling
  1.4932 +// RUN_ALL_TESTS().  In particular, it parses a command line for the
  1.4933 +// flags that Google Test recognizes.  Whenever a Google Test flag is
  1.4934 +// seen, it is removed from argv, and *argc is decremented.
  1.4935 +//
  1.4936 +// No value is returned.  Instead, the Google Test flag variables are
  1.4937 +// updated.
  1.4938 +//
  1.4939 +// Calling the function for the second time has no user-visible effect.
  1.4940 +void InitGoogleTest(int* argc, char** argv) {
  1.4941 +  internal::InitGoogleTestImpl(argc, argv);
  1.4942 +}
  1.4943 +
  1.4944 +// This overloaded version can be used in Windows programs compiled in
  1.4945 +// UNICODE mode.
  1.4946 +void InitGoogleTest(int* argc, wchar_t** argv) {
  1.4947 +  internal::InitGoogleTestImpl(argc, argv);
  1.4948 +}
  1.4949 +
  1.4950 +}  // namespace testing

mercurial