gtest.cc revision 0ddac1f3791efefb2cffdb425f0c600feb7a47e6
162ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// Copyright 2005, Google Inc.
262ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// All rights reserved.
362ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch//
462ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// Redistribution and use in source and binary forms, with or without
562ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// modification, are permitted provided that the following conditions are
662ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// met:
762ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch//
862ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch//     * Redistributions of source code must retain the above copyright
962ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// notice, this list of conditions and the following disclaimer.
1062ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch//     * Redistributions in binary form must reproduce the above
1162ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// copyright notice, this list of conditions and the following disclaimer
1262ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// in the documentation and/or other materials provided with the
1362ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// distribution.
1462ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch//     * Neither the name of Google Inc. nor the names of its
1562ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// contributors may be used to endorse or promote products derived from
1662ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// this software without specific prior written permission.
1762ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch//
1862ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
1962ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
2062ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
2162ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
2262ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
2362ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
2462ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
2562ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
2662ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
2762ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2862ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2962ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch//
3062ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// Author: wan@google.com (Zhanyong Wan)
3162ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch//
3262ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// The Google C++ Testing Framework (Google Test)
3362ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
3462ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#include <gtest/gtest.h>
3562ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#include <gtest/gtest-spi.h>
3662ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
3762ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#include <ctype.h>
3862ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#include <math.h>
3962ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#include <stdarg.h>
4062ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#include <stdio.h>
4162ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#include <stdlib.h>
4262ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#include <wchar.h>
4362ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#include <wctype.h>
4462ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
4562ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#include <algorithm>
4662ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#include <ostream>
4762ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#include <sstream>
4862ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#include <vector>
4962ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
5062ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#if GTEST_OS_LINUX
5162ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
5262ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// TODO(kenton@google.com): Use autoconf to detect availability of
5362ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// gettimeofday().
5462ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#define GTEST_HAS_GETTIMEOFDAY_ 1
5562ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
5662ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#include <fcntl.h>
5762ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#include <limits.h>
5862ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#include <sched.h>
5962ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// Declares vsnprintf().  This header is not available on Windows.
6062ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#include <strings.h>
6162ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#include <sys/mman.h>
6262ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#include <sys/time.h>
6362ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#include <unistd.h>
6462ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#include <string>
6562ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#include <vector>
6662ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
6762ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#elif GTEST_OS_SYMBIAN
6862ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#define GTEST_HAS_GETTIMEOFDAY_ 1
6962ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#include <sys/time.h>  // NOLINT
7062ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
7162ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#elif GTEST_OS_ZOS
7262ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#define GTEST_HAS_GETTIMEOFDAY_ 1
7362ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#include <sys/time.h>  // NOLINT
7462ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
7562ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// On z/OS we additionally need strings.h for strcasecmp.
7662ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#include <strings.h>  // NOLINT
7762ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
7862ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#elif GTEST_OS_WINDOWS_MOBILE  // We are on Windows CE.
7962ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
8062ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#include <windows.h>  // NOLINT
8162ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
8262ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#elif GTEST_OS_WINDOWS  // We are on Windows proper.
8362ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
8462ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#include <io.h>  // NOLINT
8562ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#include <sys/timeb.h>  // NOLINT
8662ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#include <sys/types.h>  // NOLINT
8762ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#include <sys/stat.h>  // NOLINT
8862ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
8962ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#if GTEST_OS_WINDOWS_MINGW
9062ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// MinGW has gettimeofday() but not _ftime64().
9162ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// TODO(kenton@google.com): Use autoconf to detect availability of
9262ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch//   gettimeofday().
9362ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// TODO(kenton@google.com): There are other ways to get the time on
9462ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch//   Windows, like GetTickCount() or GetSystemTimeAsFileTime().  MinGW
9562ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch//   supports these.  consider using them instead.
9662ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#define GTEST_HAS_GETTIMEOFDAY_ 1
9762ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#include <sys/time.h>  // NOLINT
9862ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#endif  // GTEST_OS_WINDOWS_MINGW
9962ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
10062ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// cpplint thinks that the header is already included, so we want to
10162ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// silence it.
10262ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#include <windows.h>  // NOLINT
10362ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
10462ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#else
10562ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
10662ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// Assume other platforms have gettimeofday().
10762ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// TODO(kenton@google.com): Use autoconf to detect availability of
10862ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch//   gettimeofday().
10962ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#define GTEST_HAS_GETTIMEOFDAY_ 1
11062ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
11162ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// cpplint thinks that the header is already included, so we want to
11262ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// silence it.
11362ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#include <sys/time.h>  // NOLINT
11462ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#include <unistd.h>  // NOLINT
11562ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
11662ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#endif  // GTEST_OS_LINUX
11762ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
11862ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#if GTEST_HAS_EXCEPTIONS
11962ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#include <stdexcept>
12062ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#endif
12162ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
12262ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// Indicates that this translation unit is part of Google Test's
12362ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// implementation.  It must come before gtest-internal-inl.h is
12462ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// included, or there will be a compiler error.  This trick is to
12562ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// prevent a user from accidentally including gtest-internal-inl.h in
12662ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// his code.
12762ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#define GTEST_IMPLEMENTATION_ 1
12862ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#include "src/gtest-internal-inl.h"
12962ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#undef GTEST_IMPLEMENTATION_
13062ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
13162ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#if GTEST_OS_WINDOWS
13262ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#define vsnprintf _vsnprintf
13362ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch#endif  // GTEST_OS_WINDOWS
13462ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
13562ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdochnamespace testing {
13662ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
13762ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdochusing internal::CountIf;
13862ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdochusing internal::ForEach;
13962ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdochusing internal::GetElementOr;
14062ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdochusing internal::Shuffle;
14162ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
14262ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// Constants.
14362ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
14462ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// A test whose test case name or test name matches this filter is
14562ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// disabled and not run.
14662ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdochstatic const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
14762ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
14862ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// A test case whose name matches this filter is considered a death
14962ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// test case and will be run before test cases whose name doesn't
15062ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// match this filter.
15162ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdochstatic const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*";
15262ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
15362ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// A test filter that matches everything.
15462ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdochstatic const char kUniversalFilter[] = "*";
15562ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
15662ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// The default output file for XML output.
15762ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdochstatic const char kDefaultOutputFile[] = "test_detail.xml";
15862ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
15962ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// The environment variable name for the test shard index.
16062ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdochstatic const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
16162ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// The environment variable name for the total number of test shards.
16262ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdochstatic const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
16362ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// The environment variable name for the test shard status file.
16462ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdochstatic const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
16562ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
16662ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdochnamespace internal {
16762ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
16862ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// The text used in failure messages to indicate the start of the
16962ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// stack trace.
17062ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdochconst char kStackTraceMarker[] = "\nStack trace:\n";
17162ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
17262ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// g_help_flag is true iff the --help flag or an equivalent form is
17362ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// specified on the command line.
17462ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdochbool g_help_flag = false;
17562ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
17662ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch}  // namespace internal
17762ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
17862ed631aa0ff23db68a47fd423efa9c019ff2c9eBen MurdochGTEST_DEFINE_bool_(
17962ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    also_run_disabled_tests,
18062ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    internal::BoolFromGTestEnv("also_run_disabled_tests", false),
18162ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    "Run disabled tests too, in addition to the tests normally being run.");
18262ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
18362ed631aa0ff23db68a47fd423efa9c019ff2c9eBen MurdochGTEST_DEFINE_bool_(
18462ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    break_on_failure,
18562ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    internal::BoolFromGTestEnv("break_on_failure", false),
18662ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    "True iff a failed assertion should be a debugger break-point.");
18762ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
18862ed631aa0ff23db68a47fd423efa9c019ff2c9eBen MurdochGTEST_DEFINE_bool_(
18962ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    catch_exceptions,
19062ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    internal::BoolFromGTestEnv("catch_exceptions", false),
19162ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    "True iff " GTEST_NAME_
19262ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    " should catch exceptions and treat them as test failures.");
19362ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
19462ed631aa0ff23db68a47fd423efa9c019ff2c9eBen MurdochGTEST_DEFINE_string_(
19562ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    color,
19662ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    internal::StringFromGTestEnv("color", "auto"),
19762ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    "Whether to use colors in the output.  Valid values: yes, no, "
19862ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    "and auto.  'auto' means to use colors if the output is "
19962ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    "being sent to a terminal and the TERM environment variable "
20062ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    "is set to xterm, xterm-color, xterm-256color, linux or cygwin.");
20162ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
20262ed631aa0ff23db68a47fd423efa9c019ff2c9eBen MurdochGTEST_DEFINE_string_(
20362ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    filter,
20462ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    internal::StringFromGTestEnv("filter", kUniversalFilter),
20562ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    "A colon-separated list of glob (not regex) patterns "
20662ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    "for filtering the tests to run, optionally followed by a "
20762ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    "'-' and a : separated list of negative patterns (tests to "
20862ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    "exclude).  A test is run if it matches one of the positive "
20962ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    "patterns and does not match any of the negative patterns.");
21062ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
21162ed631aa0ff23db68a47fd423efa9c019ff2c9eBen MurdochGTEST_DEFINE_bool_(list_tests, false,
21262ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch                   "List all tests without running them.");
21362ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
21462ed631aa0ff23db68a47fd423efa9c019ff2c9eBen MurdochGTEST_DEFINE_string_(
21562ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    output,
21662ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    internal::StringFromGTestEnv("output", ""),
21762ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    "A format (currently must be \"xml\"), optionally followed "
21862ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    "by a colon and an output file name or directory. A directory "
21962ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    "is indicated by a trailing pathname separator. "
22062ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
22162ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    "If a directory is specified, output files will be created "
22262ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    "within that directory, with file-names based on the test "
22362ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    "executable's name and, if necessary, made unique by adding "
22462ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    "digits.");
22562ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
22662ed631aa0ff23db68a47fd423efa9c019ff2c9eBen MurdochGTEST_DEFINE_bool_(
22762ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    print_time,
22862ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    internal::BoolFromGTestEnv("print_time", true),
22962ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    "True iff " GTEST_NAME_
23062ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    " should display elapsed time in text output.");
23162ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
23262ed631aa0ff23db68a47fd423efa9c019ff2c9eBen MurdochGTEST_DEFINE_int32_(
23362ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    random_seed,
23462ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    internal::Int32FromGTestEnv("random_seed", 0),
23562ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    "Random number seed to use when shuffling test orders.  Must be in range "
23662ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    "[1, 99999], or 0 to use a seed based on the current time.");
23762ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
23862ed631aa0ff23db68a47fd423efa9c019ff2c9eBen MurdochGTEST_DEFINE_int32_(
23962ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    repeat,
24062ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    internal::Int32FromGTestEnv("repeat", 1),
24162ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    "How many times to repeat each test.  Specify a negative number "
24262ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    "for repeating forever.  Useful for shaking out flaky tests.");
24362ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
24462ed631aa0ff23db68a47fd423efa9c019ff2c9eBen MurdochGTEST_DEFINE_bool_(
24562ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    show_internal_stack_frames, false,
24662ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    "True iff " GTEST_NAME_ " should include internal stack frames when "
24762ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    "printing test failure stack traces.");
24862ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
24962ed631aa0ff23db68a47fd423efa9c019ff2c9eBen MurdochGTEST_DEFINE_bool_(
25062ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    shuffle,
25162ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    internal::BoolFromGTestEnv("shuffle", false),
25262ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    "True iff " GTEST_NAME_
25362ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    " should randomize tests' order on every run.");
25462ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
25562ed631aa0ff23db68a47fd423efa9c019ff2c9eBen MurdochGTEST_DEFINE_int32_(
25662ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    stack_trace_depth,
25762ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
25862ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    "The maximum number of stack frames to print when an "
25962ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    "assertion fails.  The valid range is 0 through 100, inclusive.");
26062ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
26162ed631aa0ff23db68a47fd423efa9c019ff2c9eBen MurdochGTEST_DEFINE_bool_(
26262ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    throw_on_failure,
26362ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    internal::BoolFromGTestEnv("throw_on_failure", false),
26462ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    "When this flag is specified, a failed assertion will throw an exception "
26562ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    "if exceptions are enabled or exit the program with a non-zero code "
26662ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    "otherwise.");
26762ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
26862ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdochnamespace internal {
26962ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
27062ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// Generates a random number from [0, range), using a Linear
27162ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// Congruential Generator (LCG).  Crashes if 'range' is 0 or greater
27262ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// than kMaxRange.
27362ed631aa0ff23db68a47fd423efa9c019ff2c9eBen MurdochUInt32 Random::Generate(UInt32 range) {
27462ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch  // These constants are the same as are used in glibc's rand(3).
27562ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch  state_ = (1103515245U*state_ + 12345U) % kMaxRange;
27662ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
27762ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch  GTEST_CHECK_(range > 0)
27862ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch      << "Cannot generate a number in the range [0, 0).";
27962ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch  GTEST_CHECK_(range <= kMaxRange)
28062ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch      << "Generation of a number in [0, " << range << ") was requested, "
28162ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch      << "but this can only generate numbers in [0, " << kMaxRange << ").";
28262ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
28362ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch  // Converting via modulus introduces a bit of downward bias, but
28462ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch  // it's simple, and a linear congruential generator isn't too good
28562ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch  // to begin with.
28662ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch  return state_ % range;
28762ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch}
28862ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
28962ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// GTestIsInitialized() returns true iff the user has initialized
29062ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// Google Test.  Useful for catching the user mistake of not initializing
29162ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// Google Test before calling RUN_ALL_TESTS().
29262ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch//
29362ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// A user must call testing::InitGoogleTest() to initialize Google
29462ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// Test.  g_init_gtest_count is set to the number of times
29562ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// InitGoogleTest() has been called.  We don't protect this variable
29662ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// under a mutex as it is only accessed in the main thread.
29762ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdochint g_init_gtest_count = 0;
29862ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdochstatic bool GTestIsInitialized() { return g_init_gtest_count != 0; }
29962ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
30062ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// Iterates over a vector of TestCases, keeping a running sum of the
30162ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// results of calling a given int-returning method on each.
30262ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// Returns the sum.
30362ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdochstatic int SumOverTestCaseList(const std::vector<TestCase*>& case_list,
30462ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch                               int (TestCase::*method)() const) {
30562ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch  int sum = 0;
30662ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch  for (size_t i = 0; i < case_list.size(); i++) {
30762ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch    sum += (case_list[i]->*method)();
30862ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch  }
30962ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch  return sum;
31062ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch}
31162ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
31262ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// Returns true iff the test case passed.
31362ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdochstatic bool TestCasePassed(const TestCase* test_case) {
31462ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch  return test_case->should_run() && test_case->Passed();
31562ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch}
31662ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
31762ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// Returns true iff the test case failed.
31862ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdochstatic bool TestCaseFailed(const TestCase* test_case) {
31962ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch  return test_case->should_run() && test_case->Failed();
32062ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch}
32162ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch
32262ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// Returns true iff test_case contains at least one test that should
32362ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch// run.
32462ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdochstatic bool ShouldRunTestCase(const TestCase* test_case) {
32562ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch  return test_case->should_run();
32662ed631aa0ff23db68a47fd423efa9c019ff2c9eBen Murdoch}
327
328// AssertHelper constructor.
329AssertHelper::AssertHelper(TestPartResult::Type type,
330                           const char* file,
331                           int line,
332                           const char* message)
333    : data_(new AssertHelperData(type, file, line, message)) {
334}
335
336AssertHelper::~AssertHelper() {
337  delete data_;
338}
339
340// Message assignment, for assertion streaming support.
341void AssertHelper::operator=(const Message& message) const {
342  UnitTest::GetInstance()->
343    AddTestPartResult(data_->type, data_->file, data_->line,
344                      AppendUserMessage(data_->message, message),
345                      UnitTest::GetInstance()->impl()
346                      ->CurrentOsStackTraceExceptTop(1)
347                      // Skips the stack frame for this function itself.
348                      );  // NOLINT
349}
350
351// Mutex for linked pointers.
352GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex);
353
354// Application pathname gotten in InitGoogleTest.
355String g_executable_path;
356
357// Returns the current application's name, removing directory path if that
358// is present.
359FilePath GetCurrentExecutableName() {
360  FilePath result;
361
362#if GTEST_OS_WINDOWS
363  result.Set(FilePath(g_executable_path).RemoveExtension("exe"));
364#else
365  result.Set(FilePath(g_executable_path));
366#endif  // GTEST_OS_WINDOWS
367
368  return result.RemoveDirectoryName();
369}
370
371// Functions for processing the gtest_output flag.
372
373// Returns the output format, or "" for normal printed output.
374String UnitTestOptions::GetOutputFormat() {
375  const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
376  if (gtest_output_flag == NULL) return String("");
377
378  const char* const colon = strchr(gtest_output_flag, ':');
379  return (colon == NULL) ?
380      String(gtest_output_flag) :
381      String(gtest_output_flag, colon - gtest_output_flag);
382}
383
384// Returns the name of the requested output file, or the default if none
385// was explicitly specified.
386String UnitTestOptions::GetAbsolutePathToOutputFile() {
387  const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
388  if (gtest_output_flag == NULL)
389    return String("");
390
391  const char* const colon = strchr(gtest_output_flag, ':');
392  if (colon == NULL)
393    return String(internal::FilePath::ConcatPaths(
394               internal::FilePath(
395                   UnitTest::GetInstance()->original_working_dir()),
396               internal::FilePath(kDefaultOutputFile)).ToString() );
397
398  internal::FilePath output_name(colon + 1);
399  if (!output_name.IsAbsolutePath())
400    // TODO(wan@google.com): on Windows \some\path is not an absolute
401    // path (as its meaning depends on the current drive), yet the
402    // following logic for turning it into an absolute path is wrong.
403    // Fix it.
404    output_name = internal::FilePath::ConcatPaths(
405        internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
406        internal::FilePath(colon + 1));
407
408  if (!output_name.IsDirectory())
409    return output_name.ToString();
410
411  internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
412      output_name, internal::GetCurrentExecutableName(),
413      GetOutputFormat().c_str()));
414  return result.ToString();
415}
416
417// Returns true iff the wildcard pattern matches the string.  The
418// first ':' or '\0' character in pattern marks the end of it.
419//
420// This recursive algorithm isn't very efficient, but is clear and
421// works well enough for matching test names, which are short.
422bool UnitTestOptions::PatternMatchesString(const char *pattern,
423                                           const char *str) {
424  switch (*pattern) {
425    case '\0':
426    case ':':  // Either ':' or '\0' marks the end of the pattern.
427      return *str == '\0';
428    case '?':  // Matches any single character.
429      return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);
430    case '*':  // Matches any string (possibly empty) of characters.
431      return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||
432          PatternMatchesString(pattern + 1, str);
433    default:  // Non-special character.  Matches itself.
434      return *pattern == *str &&
435          PatternMatchesString(pattern + 1, str + 1);
436  }
437}
438
439bool UnitTestOptions::MatchesFilter(const String& name, const char* filter) {
440  const char *cur_pattern = filter;
441  for (;;) {
442    if (PatternMatchesString(cur_pattern, name.c_str())) {
443      return true;
444    }
445
446    // Finds the next pattern in the filter.
447    cur_pattern = strchr(cur_pattern, ':');
448
449    // Returns if no more pattern can be found.
450    if (cur_pattern == NULL) {
451      return false;
452    }
453
454    // Skips the pattern separater (the ':' character).
455    cur_pattern++;
456  }
457}
458
459// TODO(keithray): move String function implementations to gtest-string.cc.
460
461// Returns true iff the user-specified filter matches the test case
462// name and the test name.
463bool UnitTestOptions::FilterMatchesTest(const String &test_case_name,
464                                        const String &test_name) {
465  const String& full_name = String::Format("%s.%s",
466                                           test_case_name.c_str(),
467                                           test_name.c_str());
468
469  // Split --gtest_filter at '-', if there is one, to separate into
470  // positive filter and negative filter portions
471  const char* const p = GTEST_FLAG(filter).c_str();
472  const char* const dash = strchr(p, '-');
473  String positive;
474  String negative;
475  if (dash == NULL) {
476    positive = GTEST_FLAG(filter).c_str();  // Whole string is a positive filter
477    negative = String("");
478  } else {
479    positive = String(p, dash - p);  // Everything up to the dash
480    negative = String(dash+1);       // Everything after the dash
481    if (positive.empty()) {
482      // Treat '-test1' as the same as '*-test1'
483      positive = kUniversalFilter;
484    }
485  }
486
487  // A filter is a colon-separated list of patterns.  It matches a
488  // test if any pattern in it matches the test.
489  return (MatchesFilter(full_name, positive.c_str()) &&
490          !MatchesFilter(full_name, negative.c_str()));
491}
492
493#if GTEST_OS_WINDOWS
494// Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
495// given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
496// This function is useful as an __except condition.
497int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
498  // Google Test should handle an exception if:
499  //   1. the user wants it to, AND
500  //   2. this is not a breakpoint exception.
501  return (GTEST_FLAG(catch_exceptions) &&
502          exception_code != EXCEPTION_BREAKPOINT) ?
503      EXCEPTION_EXECUTE_HANDLER :
504      EXCEPTION_CONTINUE_SEARCH;
505}
506#endif  // GTEST_OS_WINDOWS
507
508}  // namespace internal
509
510// The c'tor sets this object as the test part result reporter used by
511// Google Test.  The 'result' parameter specifies where to report the
512// results. Intercepts only failures from the current thread.
513ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
514    TestPartResultArray* result)
515    : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
516      result_(result) {
517  Init();
518}
519
520// The c'tor sets this object as the test part result reporter used by
521// Google Test.  The 'result' parameter specifies where to report the
522// results.
523ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
524    InterceptMode intercept_mode, TestPartResultArray* result)
525    : intercept_mode_(intercept_mode),
526      result_(result) {
527  Init();
528}
529
530void ScopedFakeTestPartResultReporter::Init() {
531  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
532  if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
533    old_reporter_ = impl->GetGlobalTestPartResultReporter();
534    impl->SetGlobalTestPartResultReporter(this);
535  } else {
536    old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
537    impl->SetTestPartResultReporterForCurrentThread(this);
538  }
539}
540
541// The d'tor restores the test part result reporter used by Google Test
542// before.
543ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
544  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
545  if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
546    impl->SetGlobalTestPartResultReporter(old_reporter_);
547  } else {
548    impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
549  }
550}
551
552// Increments the test part result count and remembers the result.
553// This method is from the TestPartResultReporterInterface interface.
554void ScopedFakeTestPartResultReporter::ReportTestPartResult(
555    const TestPartResult& result) {
556  result_->Append(result);
557}
558
559namespace internal {
560
561// Returns the type ID of ::testing::Test.  We should always call this
562// instead of GetTypeId< ::testing::Test>() to get the type ID of
563// testing::Test.  This is to work around a suspected linker bug when
564// using Google Test as a framework on Mac OS X.  The bug causes
565// GetTypeId< ::testing::Test>() to return different values depending
566// on whether the call is from the Google Test framework itself or
567// from user test code.  GetTestTypeId() is guaranteed to always
568// return the same value, as it always calls GetTypeId<>() from the
569// gtest.cc, which is within the Google Test framework.
570TypeId GetTestTypeId() {
571  return GetTypeId<Test>();
572}
573
574// The value of GetTestTypeId() as seen from within the Google Test
575// library.  This is solely for testing GetTestTypeId().
576extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
577
578// This predicate-formatter checks that 'results' contains a test part
579// failure of the given type and that the failure message contains the
580// given substring.
581AssertionResult HasOneFailure(const char* /* results_expr */,
582                              const char* /* type_expr */,
583                              const char* /* substr_expr */,
584                              const TestPartResultArray& results,
585                              TestPartResult::Type type,
586                              const char* substr) {
587  const String expected(type == TestPartResult::kFatalFailure ?
588                        "1 fatal failure" :
589                        "1 non-fatal failure");
590  Message msg;
591  if (results.size() != 1) {
592    msg << "Expected: " << expected << "\n"
593        << "  Actual: " << results.size() << " failures";
594    for (int i = 0; i < results.size(); i++) {
595      msg << "\n" << results.GetTestPartResult(i);
596    }
597    return AssertionFailure(msg);
598  }
599
600  const TestPartResult& r = results.GetTestPartResult(0);
601  if (r.type() != type) {
602    msg << "Expected: " << expected << "\n"
603        << "  Actual:\n"
604        << r;
605    return AssertionFailure(msg);
606  }
607
608  if (strstr(r.message(), substr) == NULL) {
609    msg << "Expected: " << expected << " containing \""
610        << substr << "\"\n"
611        << "  Actual:\n"
612        << r;
613    return AssertionFailure(msg);
614  }
615
616  return AssertionSuccess();
617}
618
619// The constructor of SingleFailureChecker remembers where to look up
620// test part results, what type of failure we expect, and what
621// substring the failure message should contain.
622SingleFailureChecker:: SingleFailureChecker(
623    const TestPartResultArray* results,
624    TestPartResult::Type type,
625    const char* substr)
626    : results_(results),
627      type_(type),
628      substr_(substr) {}
629
630// The destructor of SingleFailureChecker verifies that the given
631// TestPartResultArray contains exactly one failure that has the given
632// type and contains the given substring.  If that's not the case, a
633// non-fatal failure will be generated.
634SingleFailureChecker::~SingleFailureChecker() {
635  EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_.c_str());
636}
637
638DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
639    UnitTestImpl* unit_test) : unit_test_(unit_test) {}
640
641void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
642    const TestPartResult& result) {
643  unit_test_->current_test_result()->AddTestPartResult(result);
644  unit_test_->listeners()->repeater()->OnTestPartResult(result);
645}
646
647DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
648    UnitTestImpl* unit_test) : unit_test_(unit_test) {}
649
650void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
651    const TestPartResult& result) {
652  unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
653}
654
655// Returns the global test part result reporter.
656TestPartResultReporterInterface*
657UnitTestImpl::GetGlobalTestPartResultReporter() {
658  internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
659  return global_test_part_result_repoter_;
660}
661
662// Sets the global test part result reporter.
663void UnitTestImpl::SetGlobalTestPartResultReporter(
664    TestPartResultReporterInterface* reporter) {
665  internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
666  global_test_part_result_repoter_ = reporter;
667}
668
669// Returns the test part result reporter for the current thread.
670TestPartResultReporterInterface*
671UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
672  return per_thread_test_part_result_reporter_.get();
673}
674
675// Sets the test part result reporter for the current thread.
676void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
677    TestPartResultReporterInterface* reporter) {
678  per_thread_test_part_result_reporter_.set(reporter);
679}
680
681// Gets the number of successful test cases.
682int UnitTestImpl::successful_test_case_count() const {
683  return CountIf(test_cases_, TestCasePassed);
684}
685
686// Gets the number of failed test cases.
687int UnitTestImpl::failed_test_case_count() const {
688  return CountIf(test_cases_, TestCaseFailed);
689}
690
691// Gets the number of all test cases.
692int UnitTestImpl::total_test_case_count() const {
693  return static_cast<int>(test_cases_.size());
694}
695
696// Gets the number of all test cases that contain at least one test
697// that should run.
698int UnitTestImpl::test_case_to_run_count() const {
699  return CountIf(test_cases_, ShouldRunTestCase);
700}
701
702// Gets the number of successful tests.
703int UnitTestImpl::successful_test_count() const {
704  return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count);
705}
706
707// Gets the number of failed tests.
708int UnitTestImpl::failed_test_count() const {
709  return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count);
710}
711
712// Gets the number of disabled tests.
713int UnitTestImpl::disabled_test_count() const {
714  return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count);
715}
716
717// Gets the number of all tests.
718int UnitTestImpl::total_test_count() const {
719  return SumOverTestCaseList(test_cases_, &TestCase::total_test_count);
720}
721
722// Gets the number of tests that should run.
723int UnitTestImpl::test_to_run_count() const {
724  return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count);
725}
726
727// Returns the current OS stack trace as a String.
728//
729// The maximum number of stack frames to be included is specified by
730// the gtest_stack_trace_depth flag.  The skip_count parameter
731// specifies the number of top frames to be skipped, which doesn't
732// count against the number of frames to be included.
733//
734// For example, if Foo() calls Bar(), which in turn calls
735// CurrentOsStackTraceExceptTop(1), Foo() will be included in the
736// trace but Bar() and CurrentOsStackTraceExceptTop() won't.
737String UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
738  (void)skip_count;
739  return String("");
740}
741
742// Returns the current time in milliseconds.
743TimeInMillis GetTimeInMillis() {
744#if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__)
745  // Difference between 1970-01-01 and 1601-01-01 in milliseconds.
746  // http://analogous.blogspot.com/2005/04/epoch.html
747  const TimeInMillis kJavaEpochToWinFileTimeDelta =
748    static_cast<TimeInMillis>(116444736UL) * 100000UL;
749  const DWORD kTenthMicrosInMilliSecond = 10000;
750
751  SYSTEMTIME now_systime;
752  FILETIME now_filetime;
753  ULARGE_INTEGER now_int64;
754  // TODO(kenton@google.com): Shouldn't this just use
755  //   GetSystemTimeAsFileTime()?
756  GetSystemTime(&now_systime);
757  if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
758    now_int64.LowPart = now_filetime.dwLowDateTime;
759    now_int64.HighPart = now_filetime.dwHighDateTime;
760    now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
761      kJavaEpochToWinFileTimeDelta;
762    return now_int64.QuadPart;
763  }
764  return 0;
765#elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_
766  __timeb64 now;
767#ifdef _MSC_VER
768  // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996
769  // (deprecated function) there.
770  // TODO(kenton@google.com): Use GetTickCount()?  Or use
771  //   SystemTimeToFileTime()
772#pragma warning(push)          // Saves the current warning state.
773#pragma warning(disable:4996)  // Temporarily disables warning 4996.
774  _ftime64(&now);
775#pragma warning(pop)           // Restores the warning state.
776#else
777  _ftime64(&now);
778#endif  // _MSC_VER
779  return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
780#elif GTEST_HAS_GETTIMEOFDAY_
781  struct timeval now;
782  gettimeofday(&now, NULL);
783  return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
784#else
785#error "Don't know how to get the current time on your system."
786#endif
787}
788
789// Utilities
790
791// class String
792
793// Returns the input enclosed in double quotes if it's not NULL;
794// otherwise returns "(null)".  For example, "\"Hello\"" is returned
795// for input "Hello".
796//
797// This is useful for printing a C string in the syntax of a literal.
798//
799// Known issue: escape sequences are not handled yet.
800String String::ShowCStringQuoted(const char* c_str) {
801  return c_str ? String::Format("\"%s\"", c_str) : String("(null)");
802}
803
804// Copies at most length characters from str into a newly-allocated
805// piece of memory of size length+1.  The memory is allocated with new[].
806// A terminating null byte is written to the memory, and a pointer to it
807// is returned.  If str is NULL, NULL is returned.
808static char* CloneString(const char* str, size_t length) {
809  if (str == NULL) {
810    return NULL;
811  } else {
812    char* const clone = new char[length + 1];
813    posix::StrNCpy(clone, str, length);
814    clone[length] = '\0';
815    return clone;
816  }
817}
818
819// Clones a 0-terminated C string, allocating memory using new.  The
820// caller is responsible for deleting[] the return value.  Returns the
821// cloned string, or NULL if the input is NULL.
822const char * String::CloneCString(const char* c_str) {
823  return (c_str == NULL) ?
824                    NULL : CloneString(c_str, strlen(c_str));
825}
826
827#if GTEST_OS_WINDOWS_MOBILE
828// Creates a UTF-16 wide string from the given ANSI string, allocating
829// memory using new. The caller is responsible for deleting the return
830// value using delete[]. Returns the wide string, or NULL if the
831// input is NULL.
832LPCWSTR String::AnsiToUtf16(const char* ansi) {
833  if (!ansi) return NULL;
834  const int length = strlen(ansi);
835  const int unicode_length =
836      MultiByteToWideChar(CP_ACP, 0, ansi, length,
837                          NULL, 0);
838  WCHAR* unicode = new WCHAR[unicode_length + 1];
839  MultiByteToWideChar(CP_ACP, 0, ansi, length,
840                      unicode, unicode_length);
841  unicode[unicode_length] = 0;
842  return unicode;
843}
844
845// Creates an ANSI string from the given wide string, allocating
846// memory using new. The caller is responsible for deleting the return
847// value using delete[]. Returns the ANSI string, or NULL if the
848// input is NULL.
849const char* String::Utf16ToAnsi(LPCWSTR utf16_str)  {
850  if (!utf16_str) return NULL;
851  const int ansi_length =
852      WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
853                          NULL, 0, NULL, NULL);
854  char* ansi = new char[ansi_length + 1];
855  WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
856                      ansi, ansi_length, NULL, NULL);
857  ansi[ansi_length] = 0;
858  return ansi;
859}
860
861#endif  // GTEST_OS_WINDOWS_MOBILE
862
863// Compares two C strings.  Returns true iff they have the same content.
864//
865// Unlike strcmp(), this function can handle NULL argument(s).  A NULL
866// C string is considered different to any non-NULL C string,
867// including the empty string.
868bool String::CStringEquals(const char * lhs, const char * rhs) {
869  if ( lhs == NULL ) return rhs == NULL;
870
871  if ( rhs == NULL ) return false;
872
873  return strcmp(lhs, rhs) == 0;
874}
875
876#if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
877
878// Converts an array of wide chars to a narrow string using the UTF-8
879// encoding, and streams the result to the given Message object.
880static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
881                                     Message* msg) {
882  // TODO(wan): consider allowing a testing::String object to
883  // contain '\0'.  This will make it behave more like std::string,
884  // and will allow ToUtf8String() to return the correct encoding
885  // for '\0' s.t. we can get rid of the conditional here (and in
886  // several other places).
887  for (size_t i = 0; i != length; ) {  // NOLINT
888    if (wstr[i] != L'\0') {
889      *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
890      while (i != length && wstr[i] != L'\0')
891        i++;
892    } else {
893      *msg << '\0';
894      i++;
895    }
896  }
897}
898
899#endif  // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
900
901}  // namespace internal
902
903#if GTEST_HAS_STD_WSTRING
904// Converts the given wide string to a narrow string using the UTF-8
905// encoding, and streams the result to this Message object.
906Message& Message::operator <<(const ::std::wstring& wstr) {
907  internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
908  return *this;
909}
910#endif  // GTEST_HAS_STD_WSTRING
911
912#if GTEST_HAS_GLOBAL_WSTRING
913// Converts the given wide string to a narrow string using the UTF-8
914// encoding, and streams the result to this Message object.
915Message& Message::operator <<(const ::wstring& wstr) {
916  internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
917  return *this;
918}
919#endif  // GTEST_HAS_GLOBAL_WSTRING
920
921namespace internal {
922
923// Formats a value to be used in a failure message.
924
925// For a char value, we print it as a C++ char literal and as an
926// unsigned integer (both in decimal and in hexadecimal).
927String FormatForFailureMessage(char ch) {
928  const unsigned int ch_as_uint = ch;
929  // A String object cannot contain '\0', so we print "\\0" when ch is
930  // '\0'.
931  return String::Format("'%s' (%u, 0x%X)",
932                        ch ? String::Format("%c", ch).c_str() : "\\0",
933                        ch_as_uint, ch_as_uint);
934}
935
936// For a wchar_t value, we print it as a C++ wchar_t literal and as an
937// unsigned integer (both in decimal and in hexidecimal).
938String FormatForFailureMessage(wchar_t wchar) {
939  // The C++ standard doesn't specify the exact size of the wchar_t
940  // type.  It just says that it shall have the same size as another
941  // integral type, called its underlying type.
942  //
943  // Therefore, in order to print a wchar_t value in the numeric form,
944  // we first convert it to the largest integral type (UInt64) and
945  // then print the converted value.
946  //
947  // We use streaming to print the value as "%llu" doesn't work
948  // correctly with MSVC 7.1.
949  const UInt64 wchar_as_uint64 = wchar;
950  Message msg;
951  // A String object cannot contain '\0', so we print "\\0" when wchar is
952  // L'\0'.
953  char buffer[32];  // CodePointToUtf8 requires a buffer that big.
954  msg << "L'"
955      << (wchar ? CodePointToUtf8(static_cast<UInt32>(wchar), buffer) : "\\0")
956      << "' (" << wchar_as_uint64 << ", 0x" << ::std::setbase(16)
957      << wchar_as_uint64 << ")";
958  return msg.GetString();
959}
960
961}  // namespace internal
962
963// AssertionResult constructors.
964// Used in EXPECT_TRUE/FALSE(assertion_result).
965AssertionResult::AssertionResult(const AssertionResult& other)
966    : success_(other.success_),
967      message_(other.message_.get() != NULL ?
968               new internal::String(*other.message_) :
969               static_cast<internal::String*>(NULL)) {
970}
971
972// Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
973AssertionResult AssertionResult::operator!() const {
974  AssertionResult negation(!success_);
975  if (message_.get() != NULL)
976    negation << *message_;
977  return negation;
978}
979
980// Makes a successful assertion result.
981AssertionResult AssertionSuccess() {
982  return AssertionResult(true);
983}
984
985// Makes a failed assertion result.
986AssertionResult AssertionFailure() {
987  return AssertionResult(false);
988}
989
990// Makes a failed assertion result with the given failure message.
991// Deprecated; use AssertionFailure() << message.
992AssertionResult AssertionFailure(const Message& message) {
993  return AssertionFailure() << message;
994}
995
996namespace internal {
997
998// Constructs and returns the message for an equality assertion
999// (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
1000//
1001// The first four parameters are the expressions used in the assertion
1002// and their values, as strings.  For example, for ASSERT_EQ(foo, bar)
1003// where foo is 5 and bar is 6, we have:
1004//
1005//   expected_expression: "foo"
1006//   actual_expression:   "bar"
1007//   expected_value:      "5"
1008//   actual_value:        "6"
1009//
1010// The ignoring_case parameter is true iff the assertion is a
1011// *_STRCASEEQ*.  When it's true, the string " (ignoring case)" will
1012// be inserted into the message.
1013AssertionResult EqFailure(const char* expected_expression,
1014                          const char* actual_expression,
1015                          const String& expected_value,
1016                          const String& actual_value,
1017                          bool ignoring_case) {
1018  Message msg;
1019  msg << "Value of: " << actual_expression;
1020  if (actual_value != actual_expression) {
1021    msg << "\n  Actual: " << actual_value;
1022  }
1023
1024  msg << "\nExpected: " << expected_expression;
1025  if (ignoring_case) {
1026    msg << " (ignoring case)";
1027  }
1028  if (expected_value != expected_expression) {
1029    msg << "\nWhich is: " << expected_value;
1030  }
1031
1032  return AssertionFailure(msg);
1033}
1034
1035// Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
1036String GetBoolAssertionFailureMessage(const AssertionResult& assertion_result,
1037                                      const char* expression_text,
1038                                      const char* actual_predicate_value,
1039                                      const char* expected_predicate_value) {
1040  const char* actual_message = assertion_result.message();
1041  Message msg;
1042  msg << "Value of: " << expression_text
1043      << "\n  Actual: " << actual_predicate_value;
1044  if (actual_message[0] != '\0')
1045    msg << " (" << actual_message << ")";
1046  msg << "\nExpected: " << expected_predicate_value;
1047  return msg.GetString();
1048}
1049
1050// Helper function for implementing ASSERT_NEAR.
1051AssertionResult DoubleNearPredFormat(const char* expr1,
1052                                     const char* expr2,
1053                                     const char* abs_error_expr,
1054                                     double val1,
1055                                     double val2,
1056                                     double abs_error) {
1057  const double diff = fabs(val1 - val2);
1058  if (diff <= abs_error) return AssertionSuccess();
1059
1060  // TODO(wan): do not print the value of an expression if it's
1061  // already a literal.
1062  Message msg;
1063  msg << "The difference between " << expr1 << " and " << expr2
1064      << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"
1065      << expr1 << " evaluates to " << val1 << ",\n"
1066      << expr2 << " evaluates to " << val2 << ", and\n"
1067      << abs_error_expr << " evaluates to " << abs_error << ".";
1068  return AssertionFailure(msg);
1069}
1070
1071
1072// Helper template for implementing FloatLE() and DoubleLE().
1073template <typename RawType>
1074AssertionResult FloatingPointLE(const char* expr1,
1075                                const char* expr2,
1076                                RawType val1,
1077                                RawType val2) {
1078  // Returns success if val1 is less than val2,
1079  if (val1 < val2) {
1080    return AssertionSuccess();
1081  }
1082
1083  // or if val1 is almost equal to val2.
1084  const FloatingPoint<RawType> lhs(val1), rhs(val2);
1085  if (lhs.AlmostEquals(rhs)) {
1086    return AssertionSuccess();
1087  }
1088
1089  // Note that the above two checks will both fail if either val1 or
1090  // val2 is NaN, as the IEEE floating-point standard requires that
1091  // any predicate involving a NaN must return false.
1092
1093  StrStream val1_ss;
1094  val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
1095          << val1;
1096
1097  StrStream val2_ss;
1098  val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
1099          << val2;
1100
1101  Message msg;
1102  msg << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
1103      << "  Actual: " << StrStreamToString(&val1_ss) << " vs "
1104      << StrStreamToString(&val2_ss);
1105
1106  return AssertionFailure(msg);
1107}
1108
1109}  // namespace internal
1110
1111// Asserts that val1 is less than, or almost equal to, val2.  Fails
1112// otherwise.  In particular, it fails if either val1 or val2 is NaN.
1113AssertionResult FloatLE(const char* expr1, const char* expr2,
1114                        float val1, float val2) {
1115  return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
1116}
1117
1118// Asserts that val1 is less than, or almost equal to, val2.  Fails
1119// otherwise.  In particular, it fails if either val1 or val2 is NaN.
1120AssertionResult DoubleLE(const char* expr1, const char* expr2,
1121                         double val1, double val2) {
1122  return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
1123}
1124
1125namespace internal {
1126
1127// The helper function for {ASSERT|EXPECT}_EQ with int or enum
1128// arguments.
1129AssertionResult CmpHelperEQ(const char* expected_expression,
1130                            const char* actual_expression,
1131                            BiggestInt expected,
1132                            BiggestInt actual) {
1133  if (expected == actual) {
1134    return AssertionSuccess();
1135  }
1136
1137  return EqFailure(expected_expression,
1138                   actual_expression,
1139                   FormatForComparisonFailureMessage(expected, actual),
1140                   FormatForComparisonFailureMessage(actual, expected),
1141                   false);
1142}
1143
1144// A macro for implementing the helper functions needed to implement
1145// ASSERT_?? and EXPECT_?? with integer or enum arguments.  It is here
1146// just to avoid copy-and-paste of similar code.
1147#define GTEST_IMPL_CMP_HELPER_(op_name, op)\
1148AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
1149                                   BiggestInt val1, BiggestInt val2) {\
1150  if (val1 op val2) {\
1151    return AssertionSuccess();\
1152  } else {\
1153    Message msg;\
1154    msg << "Expected: (" << expr1 << ") " #op " (" << expr2\
1155        << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
1156        << " vs " << FormatForComparisonFailureMessage(val2, val1);\
1157    return AssertionFailure(msg);\
1158  }\
1159}
1160
1161// Implements the helper function for {ASSERT|EXPECT}_NE with int or
1162// enum arguments.
1163GTEST_IMPL_CMP_HELPER_(NE, !=)
1164// Implements the helper function for {ASSERT|EXPECT}_LE with int or
1165// enum arguments.
1166GTEST_IMPL_CMP_HELPER_(LE, <=)
1167// Implements the helper function for {ASSERT|EXPECT}_LT with int or
1168// enum arguments.
1169GTEST_IMPL_CMP_HELPER_(LT, < )
1170// Implements the helper function for {ASSERT|EXPECT}_GE with int or
1171// enum arguments.
1172GTEST_IMPL_CMP_HELPER_(GE, >=)
1173// Implements the helper function for {ASSERT|EXPECT}_GT with int or
1174// enum arguments.
1175GTEST_IMPL_CMP_HELPER_(GT, > )
1176
1177#undef GTEST_IMPL_CMP_HELPER_
1178
1179// The helper function for {ASSERT|EXPECT}_STREQ.
1180AssertionResult CmpHelperSTREQ(const char* expected_expression,
1181                               const char* actual_expression,
1182                               const char* expected,
1183                               const char* actual) {
1184  if (String::CStringEquals(expected, actual)) {
1185    return AssertionSuccess();
1186  }
1187
1188  return EqFailure(expected_expression,
1189                   actual_expression,
1190                   String::ShowCStringQuoted(expected),
1191                   String::ShowCStringQuoted(actual),
1192                   false);
1193}
1194
1195// The helper function for {ASSERT|EXPECT}_STRCASEEQ.
1196AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression,
1197                                   const char* actual_expression,
1198                                   const char* expected,
1199                                   const char* actual) {
1200  if (String::CaseInsensitiveCStringEquals(expected, actual)) {
1201    return AssertionSuccess();
1202  }
1203
1204  return EqFailure(expected_expression,
1205                   actual_expression,
1206                   String::ShowCStringQuoted(expected),
1207                   String::ShowCStringQuoted(actual),
1208                   true);
1209}
1210
1211// The helper function for {ASSERT|EXPECT}_STRNE.
1212AssertionResult CmpHelperSTRNE(const char* s1_expression,
1213                               const char* s2_expression,
1214                               const char* s1,
1215                               const char* s2) {
1216  if (!String::CStringEquals(s1, s2)) {
1217    return AssertionSuccess();
1218  } else {
1219    Message msg;
1220    msg << "Expected: (" << s1_expression << ") != ("
1221        << s2_expression << "), actual: \""
1222        << s1 << "\" vs \"" << s2 << "\"";
1223    return AssertionFailure(msg);
1224  }
1225}
1226
1227// The helper function for {ASSERT|EXPECT}_STRCASENE.
1228AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
1229                                   const char* s2_expression,
1230                                   const char* s1,
1231                                   const char* s2) {
1232  if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
1233    return AssertionSuccess();
1234  } else {
1235    Message msg;
1236    msg << "Expected: (" << s1_expression << ") != ("
1237        << s2_expression << ") (ignoring case), actual: \""
1238        << s1 << "\" vs \"" << s2 << "\"";
1239    return AssertionFailure(msg);
1240  }
1241}
1242
1243}  // namespace internal
1244
1245namespace {
1246
1247// Helper functions for implementing IsSubString() and IsNotSubstring().
1248
1249// This group of overloaded functions return true iff needle is a
1250// substring of haystack.  NULL is considered a substring of itself
1251// only.
1252
1253bool IsSubstringPred(const char* needle, const char* haystack) {
1254  if (needle == NULL || haystack == NULL)
1255    return needle == haystack;
1256
1257  return strstr(haystack, needle) != NULL;
1258}
1259
1260bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
1261  if (needle == NULL || haystack == NULL)
1262    return needle == haystack;
1263
1264  return wcsstr(haystack, needle) != NULL;
1265}
1266
1267// StringType here can be either ::std::string or ::std::wstring.
1268template <typename StringType>
1269bool IsSubstringPred(const StringType& needle,
1270                     const StringType& haystack) {
1271  return haystack.find(needle) != StringType::npos;
1272}
1273
1274// This function implements either IsSubstring() or IsNotSubstring(),
1275// depending on the value of the expected_to_be_substring parameter.
1276// StringType here can be const char*, const wchar_t*, ::std::string,
1277// or ::std::wstring.
1278template <typename StringType>
1279AssertionResult IsSubstringImpl(
1280    bool expected_to_be_substring,
1281    const char* needle_expr, const char* haystack_expr,
1282    const StringType& needle, const StringType& haystack) {
1283  if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
1284    return AssertionSuccess();
1285
1286  const bool is_wide_string = sizeof(needle[0]) > 1;
1287  const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
1288  return AssertionFailure(
1289      Message()
1290      << "Value of: " << needle_expr << "\n"
1291      << "  Actual: " << begin_string_quote << needle << "\"\n"
1292      << "Expected: " << (expected_to_be_substring ? "" : "not ")
1293      << "a substring of " << haystack_expr << "\n"
1294      << "Which is: " << begin_string_quote << haystack << "\"");
1295}
1296
1297}  // namespace
1298
1299// IsSubstring() and IsNotSubstring() check whether needle is a
1300// substring of haystack (NULL is considered a substring of itself
1301// only), and return an appropriate error message when they fail.
1302
1303AssertionResult IsSubstring(
1304    const char* needle_expr, const char* haystack_expr,
1305    const char* needle, const char* haystack) {
1306  return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1307}
1308
1309AssertionResult IsSubstring(
1310    const char* needle_expr, const char* haystack_expr,
1311    const wchar_t* needle, const wchar_t* haystack) {
1312  return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1313}
1314
1315AssertionResult IsNotSubstring(
1316    const char* needle_expr, const char* haystack_expr,
1317    const char* needle, const char* haystack) {
1318  return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1319}
1320
1321AssertionResult IsNotSubstring(
1322    const char* needle_expr, const char* haystack_expr,
1323    const wchar_t* needle, const wchar_t* haystack) {
1324  return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1325}
1326
1327AssertionResult IsSubstring(
1328    const char* needle_expr, const char* haystack_expr,
1329    const ::std::string& needle, const ::std::string& haystack) {
1330  return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1331}
1332
1333AssertionResult IsNotSubstring(
1334    const char* needle_expr, const char* haystack_expr,
1335    const ::std::string& needle, const ::std::string& haystack) {
1336  return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1337}
1338
1339#if GTEST_HAS_STD_WSTRING
1340AssertionResult IsSubstring(
1341    const char* needle_expr, const char* haystack_expr,
1342    const ::std::wstring& needle, const ::std::wstring& haystack) {
1343  return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1344}
1345
1346AssertionResult IsNotSubstring(
1347    const char* needle_expr, const char* haystack_expr,
1348    const ::std::wstring& needle, const ::std::wstring& haystack) {
1349  return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1350}
1351#endif  // GTEST_HAS_STD_WSTRING
1352
1353namespace internal {
1354
1355#if GTEST_OS_WINDOWS
1356
1357namespace {
1358
1359// Helper function for IsHRESULT{SuccessFailure} predicates
1360AssertionResult HRESULTFailureHelper(const char* expr,
1361                                     const char* expected,
1362                                     long hr) {  // NOLINT
1363#if GTEST_OS_WINDOWS_MOBILE
1364  // Windows CE doesn't support FormatMessage.
1365  const char error_text[] = "";
1366#else
1367  // Looks up the human-readable system message for the HRESULT code
1368  // and since we're not passing any params to FormatMessage, we don't
1369  // want inserts expanded.
1370  const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
1371                       FORMAT_MESSAGE_IGNORE_INSERTS;
1372  const DWORD kBufSize = 4096;  // String::Format can't exceed this length.
1373  // Gets the system's human readable message string for this HRESULT.
1374  char error_text[kBufSize] = { '\0' };
1375  DWORD message_length = ::FormatMessageA(kFlags,
1376                                          0,  // no source, we're asking system
1377                                          hr,  // the error
1378                                          0,  // no line width restrictions
1379                                          error_text,  // output buffer
1380                                          kBufSize,  // buf size
1381                                          NULL);  // no arguments for inserts
1382  // Trims tailing white space (FormatMessage leaves a trailing cr-lf)
1383  for (; message_length && isspace(error_text[message_length - 1]);
1384          --message_length) {
1385    error_text[message_length - 1] = '\0';
1386  }
1387#endif  // GTEST_OS_WINDOWS_MOBILE
1388
1389  const String error_hex(String::Format("0x%08X ", hr));
1390  Message msg;
1391  msg << "Expected: " << expr << " " << expected << ".\n"
1392      << "  Actual: " << error_hex << error_text << "\n";
1393
1394  return ::testing::AssertionFailure(msg);
1395}
1396
1397}  // namespace
1398
1399AssertionResult IsHRESULTSuccess(const char* expr, long hr) {  // NOLINT
1400  if (SUCCEEDED(hr)) {
1401    return AssertionSuccess();
1402  }
1403  return HRESULTFailureHelper(expr, "succeeds", hr);
1404}
1405
1406AssertionResult IsHRESULTFailure(const char* expr, long hr) {  // NOLINT
1407  if (FAILED(hr)) {
1408    return AssertionSuccess();
1409  }
1410  return HRESULTFailureHelper(expr, "fails", hr);
1411}
1412
1413#endif  // GTEST_OS_WINDOWS
1414
1415// Utility functions for encoding Unicode text (wide strings) in
1416// UTF-8.
1417
1418// A Unicode code-point can have upto 21 bits, and is encoded in UTF-8
1419// like this:
1420//
1421// Code-point length   Encoding
1422//   0 -  7 bits       0xxxxxxx
1423//   8 - 11 bits       110xxxxx 10xxxxxx
1424//  12 - 16 bits       1110xxxx 10xxxxxx 10xxxxxx
1425//  17 - 21 bits       11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
1426
1427// The maximum code-point a one-byte UTF-8 sequence can represent.
1428const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) <<  7) - 1;
1429
1430// The maximum code-point a two-byte UTF-8 sequence can represent.
1431const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1;
1432
1433// The maximum code-point a three-byte UTF-8 sequence can represent.
1434const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2*6)) - 1;
1435
1436// The maximum code-point a four-byte UTF-8 sequence can represent.
1437const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3*6)) - 1;
1438
1439// Chops off the n lowest bits from a bit pattern.  Returns the n
1440// lowest bits.  As a side effect, the original bit pattern will be
1441// shifted to the right by n bits.
1442inline UInt32 ChopLowBits(UInt32* bits, int n) {
1443  const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1);
1444  *bits >>= n;
1445  return low_bits;
1446}
1447
1448// Converts a Unicode code point to a narrow string in UTF-8 encoding.
1449// code_point parameter is of type UInt32 because wchar_t may not be
1450// wide enough to contain a code point.
1451// The output buffer str must containt at least 32 characters.
1452// The function returns the address of the output buffer.
1453// If the code_point is not a valid Unicode code point
1454// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be output
1455// as '(Invalid Unicode 0xXXXXXXXX)'.
1456char* CodePointToUtf8(UInt32 code_point, char* str) {
1457  if (code_point <= kMaxCodePoint1) {
1458    str[1] = '\0';
1459    str[0] = static_cast<char>(code_point);                          // 0xxxxxxx
1460  } else if (code_point <= kMaxCodePoint2) {
1461    str[2] = '\0';
1462    str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
1463    str[0] = static_cast<char>(0xC0 | code_point);                   // 110xxxxx
1464  } else if (code_point <= kMaxCodePoint3) {
1465    str[3] = '\0';
1466    str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
1467    str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
1468    str[0] = static_cast<char>(0xE0 | code_point);                   // 1110xxxx
1469  } else if (code_point <= kMaxCodePoint4) {
1470    str[4] = '\0';
1471    str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
1472    str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
1473    str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
1474    str[0] = static_cast<char>(0xF0 | code_point);                   // 11110xxx
1475  } else {
1476    // The longest string String::Format can produce when invoked
1477    // with these parameters is 28 character long (not including
1478    // the terminating nul character). We are asking for 32 character
1479    // buffer just in case. This is also enough for strncpy to
1480    // null-terminate the destination string.
1481    posix::StrNCpy(
1482        str, String::Format("(Invalid Unicode 0x%X)", code_point).c_str(), 32);
1483    str[31] = '\0';  // Makes sure no change in the format to strncpy leaves
1484                     // the result unterminated.
1485  }
1486  return str;
1487}
1488
1489// The following two functions only make sense if the the system
1490// uses UTF-16 for wide string encoding. All supported systems
1491// with 16 bit wchar_t (Windows, Cygwin, Symbian OS) do use UTF-16.
1492
1493// Determines if the arguments constitute UTF-16 surrogate pair
1494// and thus should be combined into a single Unicode code point
1495// using CreateCodePointFromUtf16SurrogatePair.
1496inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
1497  return sizeof(wchar_t) == 2 &&
1498      (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;
1499}
1500
1501// Creates a Unicode code point from UTF16 surrogate pair.
1502inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first,
1503                                                    wchar_t second) {
1504  const UInt32 mask = (1 << 10) - 1;
1505  return (sizeof(wchar_t) == 2) ?
1506      (((first & mask) << 10) | (second & mask)) + 0x10000 :
1507      // This function should not be called when the condition is
1508      // false, but we provide a sensible default in case it is.
1509      static_cast<UInt32>(first);
1510}
1511
1512// Converts a wide string to a narrow string in UTF-8 encoding.
1513// The wide string is assumed to have the following encoding:
1514//   UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
1515//   UTF-32 if sizeof(wchar_t) == 4 (on Linux)
1516// Parameter str points to a null-terminated wide string.
1517// Parameter num_chars may additionally limit the number
1518// of wchar_t characters processed. -1 is used when the entire string
1519// should be processed.
1520// If the string contains code points that are not valid Unicode code points
1521// (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
1522// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
1523// and contains invalid UTF-16 surrogate pairs, values in those pairs
1524// will be encoded as individual Unicode characters from Basic Normal Plane.
1525String WideStringToUtf8(const wchar_t* str, int num_chars) {
1526  if (num_chars == -1)
1527    num_chars = static_cast<int>(wcslen(str));
1528
1529  StrStream stream;
1530  for (int i = 0; i < num_chars; ++i) {
1531    UInt32 unicode_code_point;
1532
1533    if (str[i] == L'\0') {
1534      break;
1535    } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
1536      unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i],
1537                                                                 str[i + 1]);
1538      i++;
1539    } else {
1540      unicode_code_point = static_cast<UInt32>(str[i]);
1541    }
1542
1543    char buffer[32];  // CodePointToUtf8 requires a buffer this big.
1544    stream << CodePointToUtf8(unicode_code_point, buffer);
1545  }
1546  return StrStreamToString(&stream);
1547}
1548
1549// Converts a wide C string to a String using the UTF-8 encoding.
1550// NULL will be converted to "(null)".
1551String String::ShowWideCString(const wchar_t * wide_c_str) {
1552  if (wide_c_str == NULL) return String("(null)");
1553
1554  return String(internal::WideStringToUtf8(wide_c_str, -1).c_str());
1555}
1556
1557// Similar to ShowWideCString(), except that this function encloses
1558// the converted string in double quotes.
1559String String::ShowWideCStringQuoted(const wchar_t* wide_c_str) {
1560  if (wide_c_str == NULL) return String("(null)");
1561
1562  return String::Format("L\"%s\"",
1563                        String::ShowWideCString(wide_c_str).c_str());
1564}
1565
1566// Compares two wide C strings.  Returns true iff they have the same
1567// content.
1568//
1569// Unlike wcscmp(), this function can handle NULL argument(s).  A NULL
1570// C string is considered different to any non-NULL C string,
1571// including the empty string.
1572bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {
1573  if (lhs == NULL) return rhs == NULL;
1574
1575  if (rhs == NULL) return false;
1576
1577  return wcscmp(lhs, rhs) == 0;
1578}
1579
1580// Helper function for *_STREQ on wide strings.
1581AssertionResult CmpHelperSTREQ(const char* expected_expression,
1582                               const char* actual_expression,
1583                               const wchar_t* expected,
1584                               const wchar_t* actual) {
1585  if (String::WideCStringEquals(expected, actual)) {
1586    return AssertionSuccess();
1587  }
1588
1589  return EqFailure(expected_expression,
1590                   actual_expression,
1591                   String::ShowWideCStringQuoted(expected),
1592                   String::ShowWideCStringQuoted(actual),
1593                   false);
1594}
1595
1596// Helper function for *_STRNE on wide strings.
1597AssertionResult CmpHelperSTRNE(const char* s1_expression,
1598                               const char* s2_expression,
1599                               const wchar_t* s1,
1600                               const wchar_t* s2) {
1601  if (!String::WideCStringEquals(s1, s2)) {
1602    return AssertionSuccess();
1603  }
1604
1605  Message msg;
1606  msg << "Expected: (" << s1_expression << ") != ("
1607      << s2_expression << "), actual: "
1608      << String::ShowWideCStringQuoted(s1)
1609      << " vs " << String::ShowWideCStringQuoted(s2);
1610  return AssertionFailure(msg);
1611}
1612
1613// Compares two C strings, ignoring case.  Returns true iff they have
1614// the same content.
1615//
1616// Unlike strcasecmp(), this function can handle NULL argument(s).  A
1617// NULL C string is considered different to any non-NULL C string,
1618// including the empty string.
1619bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) {
1620  if (lhs == NULL)
1621    return rhs == NULL;
1622  if (rhs == NULL)
1623    return false;
1624  return posix::StrCaseCmp(lhs, rhs) == 0;
1625}
1626
1627  // Compares two wide C strings, ignoring case.  Returns true iff they
1628  // have the same content.
1629  //
1630  // Unlike wcscasecmp(), this function can handle NULL argument(s).
1631  // A NULL C string is considered different to any non-NULL wide C string,
1632  // including the empty string.
1633  // NB: The implementations on different platforms slightly differ.
1634  // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
1635  // environment variable. On GNU platform this method uses wcscasecmp
1636  // which compares according to LC_CTYPE category of the current locale.
1637  // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
1638  // current locale.
1639bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
1640                                              const wchar_t* rhs) {
1641  if ( lhs == NULL ) return rhs == NULL;
1642
1643  if ( rhs == NULL ) return false;
1644
1645#if GTEST_OS_WINDOWS
1646  return _wcsicmp(lhs, rhs) == 0;
1647#elif GTEST_OS_LINUX
1648  return wcscasecmp(lhs, rhs) == 0;
1649#else
1650  // Mac OS X and Cygwin don't define wcscasecmp.  Other unknown OSes
1651  // may not define it either.
1652  wint_t left, right;
1653  do {
1654    left = towlower(*lhs++);
1655    right = towlower(*rhs++);
1656  } while (left && left == right);
1657  return left == right;
1658#endif  // OS selector
1659}
1660
1661// Compares this with another String.
1662// Returns < 0 if this is less than rhs, 0 if this is equal to rhs, or > 0
1663// if this is greater than rhs.
1664int String::Compare(const String & rhs) const {
1665  const char* const lhs_c_str = c_str();
1666  const char* const rhs_c_str = rhs.c_str();
1667
1668  if (lhs_c_str == NULL) {
1669    return rhs_c_str == NULL ? 0 : -1;  // NULL < anything except NULL
1670  } else if (rhs_c_str == NULL) {
1671    return 1;
1672  }
1673
1674  const size_t shorter_str_len =
1675      length() <= rhs.length() ? length() : rhs.length();
1676  for (size_t i = 0; i != shorter_str_len; i++) {
1677    if (lhs_c_str[i] < rhs_c_str[i]) {
1678      return -1;
1679    } else if (lhs_c_str[i] > rhs_c_str[i]) {
1680      return 1;
1681    }
1682  }
1683  return (length() < rhs.length()) ? -1 :
1684      (length() > rhs.length()) ? 1 : 0;
1685}
1686
1687// Returns true iff this String ends with the given suffix.  *Any*
1688// String is considered to end with a NULL or empty suffix.
1689bool String::EndsWith(const char* suffix) const {
1690  if (suffix == NULL || CStringEquals(suffix, "")) return true;
1691
1692  if (c_str() == NULL) return false;
1693
1694  const size_t this_len = strlen(c_str());
1695  const size_t suffix_len = strlen(suffix);
1696  return (this_len >= suffix_len) &&
1697         CStringEquals(c_str() + this_len - suffix_len, suffix);
1698}
1699
1700// Returns true iff this String ends with the given suffix, ignoring case.
1701// Any String is considered to end with a NULL or empty suffix.
1702bool String::EndsWithCaseInsensitive(const char* suffix) const {
1703  if (suffix == NULL || CStringEquals(suffix, "")) return true;
1704
1705  if (c_str() == NULL) return false;
1706
1707  const size_t this_len = strlen(c_str());
1708  const size_t suffix_len = strlen(suffix);
1709  return (this_len >= suffix_len) &&
1710         CaseInsensitiveCStringEquals(c_str() + this_len - suffix_len, suffix);
1711}
1712
1713// Formats a list of arguments to a String, using the same format
1714// spec string as for printf.
1715//
1716// We do not use the StringPrintf class as it is not universally
1717// available.
1718//
1719// The result is limited to 4096 characters (including the tailing 0).
1720// If 4096 characters are not enough to format the input, or if
1721// there's an error, "<formatting error or buffer exceeded>" is
1722// returned.
1723String String::Format(const char * format, ...) {
1724  va_list args;
1725  va_start(args, format);
1726
1727  char buffer[4096];
1728  const int kBufferSize = sizeof(buffer)/sizeof(buffer[0]);
1729
1730  // MSVC 8 deprecates vsnprintf(), so we want to suppress warning
1731  // 4996 (deprecated function) there.
1732#ifdef _MSC_VER  // We are using MSVC.
1733#pragma warning(push)          // Saves the current warning state.
1734#pragma warning(disable:4996)  // Temporarily disables warning 4996.
1735  const int size = vsnprintf(buffer, kBufferSize, format, args);
1736#pragma warning(pop)           // Restores the warning state.
1737#else  // We are not using MSVC.
1738  const int size = vsnprintf(buffer, kBufferSize, format, args);
1739#endif  // _MSC_VER
1740  va_end(args);
1741
1742  // vsnprintf()'s behavior is not portable.  When the buffer is not
1743  // big enough, it returns a negative value in MSVC, and returns the
1744  // needed buffer size on Linux.  When there is an output error, it
1745  // always returns a negative value.  For simplicity, we lump the two
1746  // error cases together.
1747  if (size < 0 || size >= kBufferSize) {
1748    return String("<formatting error or buffer exceeded>");
1749  } else {
1750    return String(buffer, size);
1751  }
1752}
1753
1754// Converts the buffer in a StrStream to a String, converting NUL
1755// bytes to "\\0" along the way.
1756String StrStreamToString(StrStream* ss) {
1757  const ::std::string& str = ss->str();
1758  const char* const start = str.c_str();
1759  const char* const end = start + str.length();
1760
1761  // We need to use a helper StrStream to do this transformation
1762  // because String doesn't support push_back().
1763  StrStream helper;
1764  for (const char* ch = start; ch != end; ++ch) {
1765    if (*ch == '\0') {
1766      helper << "\\0";  // Replaces NUL with "\\0";
1767    } else {
1768      helper.put(*ch);
1769    }
1770  }
1771
1772  return String(helper.str().c_str());
1773}
1774
1775// Appends the user-supplied message to the Google-Test-generated message.
1776String AppendUserMessage(const String& gtest_msg,
1777                         const Message& user_msg) {
1778  // Appends the user message if it's non-empty.
1779  const String user_msg_string = user_msg.GetString();
1780  if (user_msg_string.empty()) {
1781    return gtest_msg;
1782  }
1783
1784  Message msg;
1785  msg << gtest_msg << "\n" << user_msg_string;
1786
1787  return msg.GetString();
1788}
1789
1790}  // namespace internal
1791
1792// class TestResult
1793
1794// Creates an empty TestResult.
1795TestResult::TestResult()
1796    : death_test_count_(0),
1797      elapsed_time_(0) {
1798}
1799
1800// D'tor.
1801TestResult::~TestResult() {
1802}
1803
1804// Returns the i-th test part result among all the results. i can
1805// range from 0 to total_part_count() - 1. If i is not in that range,
1806// aborts the program.
1807const TestPartResult& TestResult::GetTestPartResult(int i) const {
1808  if (i < 0 || i >= total_part_count())
1809    internal::posix::Abort();
1810  return test_part_results_.at(i);
1811}
1812
1813// Returns the i-th test property. i can range from 0 to
1814// test_property_count() - 1. If i is not in that range, aborts the
1815// program.
1816const TestProperty& TestResult::GetTestProperty(int i) const {
1817  if (i < 0 || i >= test_property_count())
1818    internal::posix::Abort();
1819  return test_properties_.at(i);
1820}
1821
1822// Clears the test part results.
1823void TestResult::ClearTestPartResults() {
1824  test_part_results_.clear();
1825}
1826
1827// Adds a test part result to the list.
1828void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
1829  test_part_results_.push_back(test_part_result);
1830}
1831
1832// Adds a test property to the list. If a property with the same key as the
1833// supplied property is already represented, the value of this test_property
1834// replaces the old value for that key.
1835void TestResult::RecordProperty(const TestProperty& test_property) {
1836  if (!ValidateTestProperty(test_property)) {
1837    return;
1838  }
1839  internal::MutexLock lock(&test_properites_mutex_);
1840  const std::vector<TestProperty>::iterator property_with_matching_key =
1841      std::find_if(test_properties_.begin(), test_properties_.end(),
1842                   internal::TestPropertyKeyIs(test_property.key()));
1843  if (property_with_matching_key == test_properties_.end()) {
1844    test_properties_.push_back(test_property);
1845    return;
1846  }
1847  property_with_matching_key->SetValue(test_property.value());
1848}
1849
1850// Adds a failure if the key is a reserved attribute of Google Test
1851// testcase tags.  Returns true if the property is valid.
1852bool TestResult::ValidateTestProperty(const TestProperty& test_property) {
1853  internal::String key(test_property.key());
1854  if (key == "name" || key == "status" || key == "time" || key == "classname") {
1855    ADD_FAILURE()
1856        << "Reserved key used in RecordProperty(): "
1857        << key
1858        << " ('name', 'status', 'time', and 'classname' are reserved by "
1859        << GTEST_NAME_ << ")";
1860    return false;
1861  }
1862  return true;
1863}
1864
1865// Clears the object.
1866void TestResult::Clear() {
1867  test_part_results_.clear();
1868  test_properties_.clear();
1869  death_test_count_ = 0;
1870  elapsed_time_ = 0;
1871}
1872
1873// Returns true iff the test failed.
1874bool TestResult::Failed() const {
1875  for (int i = 0; i < total_part_count(); ++i) {
1876    if (GetTestPartResult(i).failed())
1877      return true;
1878  }
1879  return false;
1880}
1881
1882// Returns true iff the test part fatally failed.
1883static bool TestPartFatallyFailed(const TestPartResult& result) {
1884  return result.fatally_failed();
1885}
1886
1887// Returns true iff the test fatally failed.
1888bool TestResult::HasFatalFailure() const {
1889  return CountIf(test_part_results_, TestPartFatallyFailed) > 0;
1890}
1891
1892// Returns true iff the test part non-fatally failed.
1893static bool TestPartNonfatallyFailed(const TestPartResult& result) {
1894  return result.nonfatally_failed();
1895}
1896
1897// Returns true iff the test has a non-fatal failure.
1898bool TestResult::HasNonfatalFailure() const {
1899  return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0;
1900}
1901
1902// Gets the number of all test parts.  This is the sum of the number
1903// of successful test parts and the number of failed test parts.
1904int TestResult::total_part_count() const {
1905  return static_cast<int>(test_part_results_.size());
1906}
1907
1908// Returns the number of the test properties.
1909int TestResult::test_property_count() const {
1910  return static_cast<int>(test_properties_.size());
1911}
1912
1913// class Test
1914
1915// Creates a Test object.
1916
1917// The c'tor saves the values of all Google Test flags.
1918Test::Test()
1919    : gtest_flag_saver_(new internal::GTestFlagSaver) {
1920}
1921
1922// The d'tor restores the values of all Google Test flags.
1923Test::~Test() {
1924  delete gtest_flag_saver_;
1925}
1926
1927// Sets up the test fixture.
1928//
1929// A sub-class may override this.
1930void Test::SetUp() {
1931}
1932
1933// Tears down the test fixture.
1934//
1935// A sub-class may override this.
1936void Test::TearDown() {
1937}
1938
1939// Allows user supplied key value pairs to be recorded for later output.
1940void Test::RecordProperty(const char* key, const char* value) {
1941  UnitTest::GetInstance()->RecordPropertyForCurrentTest(key, value);
1942}
1943
1944// Allows user supplied key value pairs to be recorded for later output.
1945void Test::RecordProperty(const char* key, int value) {
1946  Message value_message;
1947  value_message << value;
1948  RecordProperty(key, value_message.GetString().c_str());
1949}
1950
1951namespace internal {
1952
1953void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
1954                                    const String& message) {
1955  // This function is a friend of UnitTest and as such has access to
1956  // AddTestPartResult.
1957  UnitTest::GetInstance()->AddTestPartResult(
1958      result_type,
1959      NULL,  // No info about the source file where the exception occurred.
1960      -1,    // We have no info on which line caused the exception.
1961      message,
1962      String());  // No stack trace, either.
1963}
1964
1965}  // namespace internal
1966
1967#if GTEST_OS_WINDOWS
1968// We are on Windows.
1969
1970// Adds an "exception thrown" fatal failure to the current test.
1971static void AddExceptionThrownFailure(DWORD exception_code,
1972                                      const char* location) {
1973  Message message;
1974  message << "Exception thrown with code 0x" << std::setbase(16) <<
1975    exception_code << std::setbase(10) << " in " << location << ".";
1976
1977  internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
1978                                           message.GetString());
1979}
1980
1981#endif  // GTEST_OS_WINDOWS
1982
1983// Google Test requires all tests in the same test case to use the same test
1984// fixture class.  This function checks if the current test has the
1985// same fixture class as the first test in the current test case.  If
1986// yes, it returns true; otherwise it generates a Google Test failure and
1987// returns false.
1988bool Test::HasSameFixtureClass() {
1989  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
1990  const TestCase* const test_case = impl->current_test_case();
1991
1992  // Info about the first test in the current test case.
1993  const internal::TestInfoImpl* const first_test_info =
1994      test_case->test_info_list()[0]->impl();
1995  const internal::TypeId first_fixture_id = first_test_info->fixture_class_id();
1996  const char* const first_test_name = first_test_info->name();
1997
1998  // Info about the current test.
1999  const internal::TestInfoImpl* const this_test_info =
2000      impl->current_test_info()->impl();
2001  const internal::TypeId this_fixture_id = this_test_info->fixture_class_id();
2002  const char* const this_test_name = this_test_info->name();
2003
2004  if (this_fixture_id != first_fixture_id) {
2005    // Is the first test defined using TEST?
2006    const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();
2007    // Is this test defined using TEST?
2008    const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();
2009
2010    if (first_is_TEST || this_is_TEST) {
2011      // The user mixed TEST and TEST_F in this test case - we'll tell
2012      // him/her how to fix it.
2013
2014      // Gets the name of the TEST and the name of the TEST_F.  Note
2015      // that first_is_TEST and this_is_TEST cannot both be true, as
2016      // the fixture IDs are different for the two tests.
2017      const char* const TEST_name =
2018          first_is_TEST ? first_test_name : this_test_name;
2019      const char* const TEST_F_name =
2020          first_is_TEST ? this_test_name : first_test_name;
2021
2022      ADD_FAILURE()
2023          << "All tests in the same test case must use the same test fixture\n"
2024          << "class, so mixing TEST_F and TEST in the same test case is\n"
2025          << "illegal.  In test case " << this_test_info->test_case_name()
2026          << ",\n"
2027          << "test " << TEST_F_name << " is defined using TEST_F but\n"
2028          << "test " << TEST_name << " is defined using TEST.  You probably\n"
2029          << "want to change the TEST to TEST_F or move it to another test\n"
2030          << "case.";
2031    } else {
2032      // The user defined two fixture classes with the same name in
2033      // two namespaces - we'll tell him/her how to fix it.
2034      ADD_FAILURE()
2035          << "All tests in the same test case must use the same test fixture\n"
2036          << "class.  However, in test case "
2037          << this_test_info->test_case_name() << ",\n"
2038          << "you defined test " << first_test_name
2039          << " and test " << this_test_name << "\n"
2040          << "using two different test fixture classes.  This can happen if\n"
2041          << "the two classes are from different namespaces or translation\n"
2042          << "units and have the same name.  You should probably rename one\n"
2043          << "of the classes to put the tests into different test cases.";
2044    }
2045    return false;
2046  }
2047
2048  return true;
2049}
2050
2051// Runs the test and updates the test result.
2052void Test::Run() {
2053  if (!HasSameFixtureClass()) return;
2054
2055  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2056#if GTEST_HAS_SEH
2057  // Catch SEH-style exceptions.
2058  impl->os_stack_trace_getter()->UponLeavingGTest();
2059  __try {
2060    SetUp();
2061  } __except(internal::UnitTestOptions::GTestShouldProcessSEH(
2062      GetExceptionCode())) {
2063    AddExceptionThrownFailure(GetExceptionCode(), "SetUp()");
2064  }
2065
2066  // We will run the test only if SetUp() had no fatal failure.
2067  if (!HasFatalFailure()) {
2068    impl->os_stack_trace_getter()->UponLeavingGTest();
2069    __try {
2070      TestBody();
2071    } __except(internal::UnitTestOptions::GTestShouldProcessSEH(
2072        GetExceptionCode())) {
2073      AddExceptionThrownFailure(GetExceptionCode(), "the test body");
2074    }
2075  }
2076
2077  // However, we want to clean up as much as possible.  Hence we will
2078  // always call TearDown(), even if SetUp() or the test body has
2079  // failed.
2080  impl->os_stack_trace_getter()->UponLeavingGTest();
2081  __try {
2082    TearDown();
2083  } __except(internal::UnitTestOptions::GTestShouldProcessSEH(
2084      GetExceptionCode())) {
2085    AddExceptionThrownFailure(GetExceptionCode(), "TearDown()");
2086  }
2087
2088#else  // We are on a compiler or platform that doesn't support SEH.
2089  impl->os_stack_trace_getter()->UponLeavingGTest();
2090  SetUp();
2091
2092  // We will run the test only if SetUp() was successful.
2093  if (!HasFatalFailure()) {
2094    impl->os_stack_trace_getter()->UponLeavingGTest();
2095    TestBody();
2096  }
2097
2098  // However, we want to clean up as much as possible.  Hence we will
2099  // always call TearDown(), even if SetUp() or the test body has
2100  // failed.
2101  impl->os_stack_trace_getter()->UponLeavingGTest();
2102  TearDown();
2103#endif  // GTEST_HAS_SEH
2104}
2105
2106
2107// Returns true iff the current test has a fatal failure.
2108bool Test::HasFatalFailure() {
2109  return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
2110}
2111
2112// Returns true iff the current test has a non-fatal failure.
2113bool Test::HasNonfatalFailure() {
2114  return internal::GetUnitTestImpl()->current_test_result()->
2115      HasNonfatalFailure();
2116}
2117
2118// class TestInfo
2119
2120// Constructs a TestInfo object. It assumes ownership of the test factory
2121// object via impl_.
2122TestInfo::TestInfo(const char* a_test_case_name,
2123                   const char* a_name,
2124                   const char* a_test_case_comment,
2125                   const char* a_comment,
2126                   internal::TypeId fixture_class_id,
2127                   internal::TestFactoryBase* factory) {
2128  impl_ = new internal::TestInfoImpl(this, a_test_case_name, a_name,
2129                                     a_test_case_comment, a_comment,
2130                                     fixture_class_id, factory);
2131}
2132
2133// Destructs a TestInfo object.
2134TestInfo::~TestInfo() {
2135  delete impl_;
2136}
2137
2138namespace internal {
2139
2140// Creates a new TestInfo object and registers it with Google Test;
2141// returns the created object.
2142//
2143// Arguments:
2144//
2145//   test_case_name:   name of the test case
2146//   name:             name of the test
2147//   test_case_comment: a comment on the test case that will be included in
2148//                      the test output
2149//   comment:          a comment on the test that will be included in the
2150//                     test output
2151//   fixture_class_id: ID of the test fixture class
2152//   set_up_tc:        pointer to the function that sets up the test case
2153//   tear_down_tc:     pointer to the function that tears down the test case
2154//   factory:          pointer to the factory that creates a test object.
2155//                     The newly created TestInfo instance will assume
2156//                     ownership of the factory object.
2157TestInfo* MakeAndRegisterTestInfo(
2158    const char* test_case_name, const char* name,
2159    const char* test_case_comment, const char* comment,
2160    TypeId fixture_class_id,
2161    SetUpTestCaseFunc set_up_tc,
2162    TearDownTestCaseFunc tear_down_tc,
2163    TestFactoryBase* factory) {
2164  TestInfo* const test_info =
2165      new TestInfo(test_case_name, name, test_case_comment, comment,
2166                   fixture_class_id, factory);
2167  GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
2168  return test_info;
2169}
2170
2171#if GTEST_HAS_PARAM_TEST
2172void ReportInvalidTestCaseType(const char* test_case_name,
2173                               const char* file, int line) {
2174  Message errors;
2175  errors
2176      << "Attempted redefinition of test case " << test_case_name << ".\n"
2177      << "All tests in the same test case must use the same test fixture\n"
2178      << "class.  However, in test case " << test_case_name << ", you tried\n"
2179      << "to define a test using a fixture class different from the one\n"
2180      << "used earlier. This can happen if the two fixture classes are\n"
2181      << "from different namespaces and have the same name. You should\n"
2182      << "probably rename one of the classes to put the tests into different\n"
2183      << "test cases.";
2184
2185  fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
2186          errors.GetString().c_str());
2187}
2188#endif  // GTEST_HAS_PARAM_TEST
2189
2190}  // namespace internal
2191
2192// Returns the test case name.
2193const char* TestInfo::test_case_name() const {
2194  return impl_->test_case_name();
2195}
2196
2197// Returns the test name.
2198const char* TestInfo::name() const {
2199  return impl_->name();
2200}
2201
2202// Returns the test case comment.
2203const char* TestInfo::test_case_comment() const {
2204  return impl_->test_case_comment();
2205}
2206
2207// Returns the test comment.
2208const char* TestInfo::comment() const {
2209  return impl_->comment();
2210}
2211
2212// Returns true if this test should run.
2213bool TestInfo::should_run() const { return impl_->should_run(); }
2214
2215// Returns true if this test matches the user-specified filter.
2216bool TestInfo::matches_filter() const { return impl_->matches_filter(); }
2217
2218// Returns the result of the test.
2219const TestResult* TestInfo::result() const { return impl_->result(); }
2220
2221// Increments the number of death tests encountered in this test so
2222// far.
2223int TestInfo::increment_death_test_count() {
2224  return impl_->result()->increment_death_test_count();
2225}
2226
2227namespace {
2228
2229// A predicate that checks the test name of a TestInfo against a known
2230// value.
2231//
2232// This is used for implementation of the TestCase class only.  We put
2233// it in the anonymous namespace to prevent polluting the outer
2234// namespace.
2235//
2236// TestNameIs is copyable.
2237class TestNameIs {
2238 public:
2239  // Constructor.
2240  //
2241  // TestNameIs has NO default constructor.
2242  explicit TestNameIs(const char* name)
2243      : name_(name) {}
2244
2245  // Returns true iff the test name of test_info matches name_.
2246  bool operator()(const TestInfo * test_info) const {
2247    return test_info && internal::String(test_info->name()).Compare(name_) == 0;
2248  }
2249
2250 private:
2251  internal::String name_;
2252};
2253
2254}  // namespace
2255
2256namespace internal {
2257
2258// This method expands all parameterized tests registered with macros TEST_P
2259// and INSTANTIATE_TEST_CASE_P into regular tests and registers those.
2260// This will be done just once during the program runtime.
2261void UnitTestImpl::RegisterParameterizedTests() {
2262#if GTEST_HAS_PARAM_TEST
2263  if (!parameterized_tests_registered_) {
2264    parameterized_test_registry_.RegisterTests();
2265    parameterized_tests_registered_ = true;
2266  }
2267#endif
2268}
2269
2270// Creates the test object, runs it, records its result, and then
2271// deletes it.
2272void TestInfoImpl::Run() {
2273  if (!should_run_) return;
2274
2275  // Tells UnitTest where to store test result.
2276  UnitTestImpl* const impl = internal::GetUnitTestImpl();
2277  impl->set_current_test_info(parent_);
2278
2279  TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
2280
2281  // Notifies the unit test event listeners that a test is about to start.
2282  repeater->OnTestStart(*parent_);
2283
2284  const TimeInMillis start = GetTimeInMillis();
2285
2286  impl->os_stack_trace_getter()->UponLeavingGTest();
2287#if GTEST_HAS_SEH
2288  // Catch SEH-style exceptions.
2289  Test* test = NULL;
2290
2291  __try {
2292    // Creates the test object.
2293    test = factory_->CreateTest();
2294  } __except(internal::UnitTestOptions::GTestShouldProcessSEH(
2295      GetExceptionCode())) {
2296    AddExceptionThrownFailure(GetExceptionCode(),
2297                              "the test fixture's constructor");
2298    return;
2299  }
2300#else  // We are on a compiler or platform that doesn't support SEH.
2301
2302  // TODO(wan): If test->Run() throws, test won't be deleted.  This is
2303  // not a problem now as we don't use exceptions.  If we were to
2304  // enable exceptions, we should revise the following to be
2305  // exception-safe.
2306
2307  // Creates the test object.
2308  Test* test = factory_->CreateTest();
2309#endif  // GTEST_HAS_SEH
2310
2311  // Runs the test only if the constructor of the test fixture didn't
2312  // generate a fatal failure.
2313  if (!Test::HasFatalFailure()) {
2314    test->Run();
2315  }
2316
2317  // Deletes the test object.
2318  impl->os_stack_trace_getter()->UponLeavingGTest();
2319  delete test;
2320  test = NULL;
2321
2322  result_.set_elapsed_time(GetTimeInMillis() - start);
2323
2324  // Notifies the unit test event listener that a test has just finished.
2325  repeater->OnTestEnd(*parent_);
2326
2327  // Tells UnitTest to stop associating assertion results to this
2328  // test.
2329  impl->set_current_test_info(NULL);
2330}
2331
2332}  // namespace internal
2333
2334// class TestCase
2335
2336// Gets the number of successful tests in this test case.
2337int TestCase::successful_test_count() const {
2338  return CountIf(test_info_list_, TestPassed);
2339}
2340
2341// Gets the number of failed tests in this test case.
2342int TestCase::failed_test_count() const {
2343  return CountIf(test_info_list_, TestFailed);
2344}
2345
2346int TestCase::disabled_test_count() const {
2347  return CountIf(test_info_list_, TestDisabled);
2348}
2349
2350// Get the number of tests in this test case that should run.
2351int TestCase::test_to_run_count() const {
2352  return CountIf(test_info_list_, ShouldRunTest);
2353}
2354
2355// Gets the number of all tests.
2356int TestCase::total_test_count() const {
2357  return static_cast<int>(test_info_list_.size());
2358}
2359
2360// Creates a TestCase with the given name.
2361//
2362// Arguments:
2363//
2364//   name:         name of the test case
2365//   set_up_tc:    pointer to the function that sets up the test case
2366//   tear_down_tc: pointer to the function that tears down the test case
2367TestCase::TestCase(const char* a_name, const char* a_comment,
2368                   Test::SetUpTestCaseFunc set_up_tc,
2369                   Test::TearDownTestCaseFunc tear_down_tc)
2370    : name_(a_name),
2371      comment_(a_comment),
2372      set_up_tc_(set_up_tc),
2373      tear_down_tc_(tear_down_tc),
2374      should_run_(false),
2375      elapsed_time_(0) {
2376}
2377
2378// Destructor of TestCase.
2379TestCase::~TestCase() {
2380  // Deletes every Test in the collection.
2381  ForEach(test_info_list_, internal::Delete<TestInfo>);
2382}
2383
2384// Returns the i-th test among all the tests. i can range from 0 to
2385// total_test_count() - 1. If i is not in that range, returns NULL.
2386const TestInfo* TestCase::GetTestInfo(int i) const {
2387  const int index = GetElementOr(test_indices_, i, -1);
2388  return index < 0 ? NULL : test_info_list_[index];
2389}
2390
2391// Returns the i-th test among all the tests. i can range from 0 to
2392// total_test_count() - 1. If i is not in that range, returns NULL.
2393TestInfo* TestCase::GetMutableTestInfo(int i) {
2394  const int index = GetElementOr(test_indices_, i, -1);
2395  return index < 0 ? NULL : test_info_list_[index];
2396}
2397
2398// Adds a test to this test case.  Will delete the test upon
2399// destruction of the TestCase object.
2400void TestCase::AddTestInfo(TestInfo * test_info) {
2401  test_info_list_.push_back(test_info);
2402  test_indices_.push_back(static_cast<int>(test_indices_.size()));
2403}
2404
2405// Runs every test in this TestCase.
2406void TestCase::Run() {
2407  if (!should_run_) return;
2408
2409  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2410  impl->set_current_test_case(this);
2411
2412  TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
2413
2414  repeater->OnTestCaseStart(*this);
2415  impl->os_stack_trace_getter()->UponLeavingGTest();
2416  set_up_tc_();
2417
2418  const internal::TimeInMillis start = internal::GetTimeInMillis();
2419  for (int i = 0; i < total_test_count(); i++) {
2420    GetMutableTestInfo(i)->impl()->Run();
2421  }
2422  elapsed_time_ = internal::GetTimeInMillis() - start;
2423
2424  impl->os_stack_trace_getter()->UponLeavingGTest();
2425  tear_down_tc_();
2426  repeater->OnTestCaseEnd(*this);
2427  impl->set_current_test_case(NULL);
2428}
2429
2430// Clears the results of all tests in this test case.
2431void TestCase::ClearResult() {
2432  ForEach(test_info_list_, internal::TestInfoImpl::ClearTestResult);
2433}
2434
2435// Returns true iff test passed.
2436bool TestCase::TestPassed(const TestInfo * test_info) {
2437  const internal::TestInfoImpl* const impl = test_info->impl();
2438  return impl->should_run() && impl->result()->Passed();
2439}
2440
2441// Returns true iff test failed.
2442bool TestCase::TestFailed(const TestInfo * test_info) {
2443  const internal::TestInfoImpl* const impl = test_info->impl();
2444  return impl->should_run() && impl->result()->Failed();
2445}
2446
2447// Returns true iff test is disabled.
2448bool TestCase::TestDisabled(const TestInfo * test_info) {
2449  return test_info->impl()->is_disabled();
2450}
2451
2452// Returns true if the given test should run.
2453bool TestCase::ShouldRunTest(const TestInfo *test_info) {
2454  return test_info->impl()->should_run();
2455}
2456
2457// Shuffles the tests in this test case.
2458void TestCase::ShuffleTests(internal::Random* random) {
2459  Shuffle(random, &test_indices_);
2460}
2461
2462// Restores the test order to before the first shuffle.
2463void TestCase::UnshuffleTests() {
2464  for (size_t i = 0; i < test_indices_.size(); i++) {
2465    test_indices_[i] = static_cast<int>(i);
2466  }
2467}
2468
2469// Formats a countable noun.  Depending on its quantity, either the
2470// singular form or the plural form is used. e.g.
2471//
2472// FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
2473// FormatCountableNoun(5, "book", "books") returns "5 books".
2474static internal::String FormatCountableNoun(int count,
2475                                            const char * singular_form,
2476                                            const char * plural_form) {
2477  return internal::String::Format("%d %s", count,
2478                                  count == 1 ? singular_form : plural_form);
2479}
2480
2481// Formats the count of tests.
2482static internal::String FormatTestCount(int test_count) {
2483  return FormatCountableNoun(test_count, "test", "tests");
2484}
2485
2486// Formats the count of test cases.
2487static internal::String FormatTestCaseCount(int test_case_count) {
2488  return FormatCountableNoun(test_case_count, "test case", "test cases");
2489}
2490
2491// Converts a TestPartResult::Type enum to human-friendly string
2492// representation.  Both kNonFatalFailure and kFatalFailure are translated
2493// to "Failure", as the user usually doesn't care about the difference
2494// between the two when viewing the test result.
2495static const char * TestPartResultTypeToString(TestPartResult::Type type) {
2496  switch (type) {
2497    case TestPartResult::kSuccess:
2498      return "Success";
2499
2500    case TestPartResult::kNonFatalFailure:
2501    case TestPartResult::kFatalFailure:
2502#ifdef _MSC_VER
2503      return "error: ";
2504#else
2505      return "Failure\n";
2506#endif
2507  }
2508
2509  return "Unknown result type";
2510}
2511
2512// Prints a TestPartResult to a String.
2513static internal::String PrintTestPartResultToString(
2514    const TestPartResult& test_part_result) {
2515  return (Message()
2516          << internal::FormatFileLocation(test_part_result.file_name(),
2517                                          test_part_result.line_number())
2518          << " " << TestPartResultTypeToString(test_part_result.type())
2519          << test_part_result.message()).GetString();
2520}
2521
2522// Prints a TestPartResult.
2523static void PrintTestPartResult(const TestPartResult& test_part_result) {
2524  const internal::String& result =
2525      PrintTestPartResultToString(test_part_result);
2526  printf("%s\n", result.c_str());
2527  fflush(stdout);
2528  // If the test program runs in Visual Studio or a debugger, the
2529  // following statements add the test part result message to the Output
2530  // window such that the user can double-click on it to jump to the
2531  // corresponding source code location; otherwise they do nothing.
2532#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
2533  // We don't call OutputDebugString*() on Windows Mobile, as printing
2534  // to stdout is done by OutputDebugString() there already - we don't
2535  // want the same message printed twice.
2536  ::OutputDebugStringA(result.c_str());
2537  ::OutputDebugStringA("\n");
2538#endif
2539}
2540
2541// class PrettyUnitTestResultPrinter
2542
2543namespace internal {
2544
2545enum GTestColor {
2546  COLOR_DEFAULT,
2547  COLOR_RED,
2548  COLOR_GREEN,
2549  COLOR_YELLOW
2550};
2551
2552#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
2553
2554// Returns the character attribute for the given color.
2555WORD GetColorAttribute(GTestColor color) {
2556  switch (color) {
2557    case COLOR_RED:    return FOREGROUND_RED;
2558    case COLOR_GREEN:  return FOREGROUND_GREEN;
2559    case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
2560    default:           return 0;
2561  }
2562}
2563
2564#else
2565
2566// Returns the ANSI color code for the given color.  COLOR_DEFAULT is
2567// an invalid input.
2568const char* GetAnsiColorCode(GTestColor color) {
2569  switch (color) {
2570    case COLOR_RED:     return "1";
2571    case COLOR_GREEN:   return "2";
2572    case COLOR_YELLOW:  return "3";
2573    default:            return NULL;
2574  };
2575}
2576
2577#endif  // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
2578
2579// Returns true iff Google Test should use colors in the output.
2580bool ShouldUseColor(bool stdout_is_tty) {
2581  const char* const gtest_color = GTEST_FLAG(color).c_str();
2582
2583  if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
2584#if GTEST_OS_WINDOWS
2585    // On Windows the TERM variable is usually not set, but the
2586    // console there does support colors.
2587    return stdout_is_tty;
2588#else
2589    // On non-Windows platforms, we rely on the TERM variable.
2590    const char* const term = posix::GetEnv("TERM");
2591    const bool term_supports_color =
2592        String::CStringEquals(term, "xterm") ||
2593        String::CStringEquals(term, "xterm-color") ||
2594        String::CStringEquals(term, "xterm-256color") ||
2595        String::CStringEquals(term, "linux") ||
2596        String::CStringEquals(term, "cygwin");
2597    return stdout_is_tty && term_supports_color;
2598#endif  // GTEST_OS_WINDOWS
2599  }
2600
2601  return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
2602      String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
2603      String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
2604      String::CStringEquals(gtest_color, "1");
2605  // We take "yes", "true", "t", and "1" as meaning "yes".  If the
2606  // value is neither one of these nor "auto", we treat it as "no" to
2607  // be conservative.
2608}
2609
2610// Helpers for printing colored strings to stdout. Note that on Windows, we
2611// cannot simply emit special characters and have the terminal change colors.
2612// This routine must actually emit the characters rather than return a string
2613// that would be colored when printed, as can be done on Linux.
2614void ColoredPrintf(GTestColor color, const char* fmt, ...) {
2615  va_list args;
2616  va_start(args, fmt);
2617
2618#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
2619  const bool use_color = false;
2620#else
2621  static const bool in_color_mode =
2622      ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
2623  const bool use_color = in_color_mode && (color != COLOR_DEFAULT);
2624#endif  // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
2625  // The '!= 0' comparison is necessary to satisfy MSVC 7.1.
2626
2627  if (!use_color) {
2628    vprintf(fmt, args);
2629    va_end(args);
2630    return;
2631  }
2632
2633#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
2634  const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
2635
2636  // Gets the current text color.
2637  CONSOLE_SCREEN_BUFFER_INFO buffer_info;
2638  GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
2639  const WORD old_color_attrs = buffer_info.wAttributes;
2640
2641  // We need to flush the stream buffers into the console before each
2642  // SetConsoleTextAttribute call lest it affect the text that is already
2643  // printed but has not yet reached the console.
2644  fflush(stdout);
2645  SetConsoleTextAttribute(stdout_handle,
2646                          GetColorAttribute(color) | FOREGROUND_INTENSITY);
2647  vprintf(fmt, args);
2648
2649  fflush(stdout);
2650  // Restores the text color.
2651  SetConsoleTextAttribute(stdout_handle, old_color_attrs);
2652#else
2653  printf("\033[0;3%sm", GetAnsiColorCode(color));
2654  vprintf(fmt, args);
2655  printf("\033[m");  // Resets the terminal to default.
2656#endif  // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
2657  va_end(args);
2658}
2659
2660// This class implements the TestEventListener interface.
2661//
2662// Class PrettyUnitTestResultPrinter is copyable.
2663class PrettyUnitTestResultPrinter : public TestEventListener {
2664 public:
2665  PrettyUnitTestResultPrinter() {}
2666  static void PrintTestName(const char * test_case, const char * test) {
2667    printf("%s.%s", test_case, test);
2668  }
2669
2670  // The following methods override what's in the TestEventListener class.
2671  virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {}
2672  virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
2673  virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
2674  virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {}
2675  virtual void OnTestCaseStart(const TestCase& test_case);
2676  virtual void OnTestStart(const TestInfo& test_info);
2677  virtual void OnTestPartResult(const TestPartResult& result);
2678  virtual void OnTestEnd(const TestInfo& test_info);
2679  virtual void OnTestCaseEnd(const TestCase& test_case);
2680  virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
2681  virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {}
2682  virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
2683  virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {}
2684
2685 private:
2686  static void PrintFailedTests(const UnitTest& unit_test);
2687
2688  internal::String test_case_name_;
2689};
2690
2691  // Fired before each iteration of tests starts.
2692void PrettyUnitTestResultPrinter::OnTestIterationStart(
2693    const UnitTest& unit_test, int iteration) {
2694  if (GTEST_FLAG(repeat) != 1)
2695    printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
2696
2697  const char* const filter = GTEST_FLAG(filter).c_str();
2698
2699  // Prints the filter if it's not *.  This reminds the user that some
2700  // tests may be skipped.
2701  if (!internal::String::CStringEquals(filter, kUniversalFilter)) {
2702    ColoredPrintf(COLOR_YELLOW,
2703                  "Note: %s filter = %s\n", GTEST_NAME_, filter);
2704  }
2705
2706  if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
2707    ColoredPrintf(COLOR_YELLOW,
2708                  "Note: This is test shard %s of %s.\n",
2709                  internal::posix::GetEnv(kTestShardIndex),
2710                  internal::posix::GetEnv(kTestTotalShards));
2711  }
2712
2713  if (GTEST_FLAG(shuffle)) {
2714    ColoredPrintf(COLOR_YELLOW,
2715                  "Note: Randomizing tests' orders with a seed of %d .\n",
2716                  unit_test.random_seed());
2717  }
2718
2719  ColoredPrintf(COLOR_GREEN,  "[==========] ");
2720  printf("Running %s from %s.\n",
2721         FormatTestCount(unit_test.test_to_run_count()).c_str(),
2722         FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
2723  fflush(stdout);
2724}
2725
2726void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
2727    const UnitTest& /*unit_test*/) {
2728  ColoredPrintf(COLOR_GREEN,  "[----------] ");
2729  printf("Global test environment set-up.\n");
2730  fflush(stdout);
2731}
2732
2733void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {
2734  test_case_name_ = test_case.name();
2735  const internal::String counts =
2736      FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
2737  ColoredPrintf(COLOR_GREEN, "[----------] ");
2738  printf("%s from %s", counts.c_str(), test_case_name_.c_str());
2739  if (test_case.comment()[0] == '\0') {
2740    printf("\n");
2741  } else {
2742    printf(", where %s\n", test_case.comment());
2743  }
2744  fflush(stdout);
2745}
2746
2747void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
2748  ColoredPrintf(COLOR_GREEN,  "[ RUN      ] ");
2749  PrintTestName(test_case_name_.c_str(), test_info.name());
2750  if (test_info.comment()[0] == '\0') {
2751    printf("\n");
2752  } else {
2753    printf(", where %s\n", test_info.comment());
2754  }
2755  fflush(stdout);
2756}
2757
2758// Called after an assertion failure.
2759void PrettyUnitTestResultPrinter::OnTestPartResult(
2760    const TestPartResult& result) {
2761  // If the test part succeeded, we don't need to do anything.
2762  if (result.type() == TestPartResult::kSuccess)
2763    return;
2764
2765  // Print failure message from the assertion (e.g. expected this and got that).
2766  PrintTestPartResult(result);
2767  fflush(stdout);
2768}
2769
2770void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
2771  if (test_info.result()->Passed()) {
2772    ColoredPrintf(COLOR_GREEN, "[       OK ] ");
2773  } else {
2774    ColoredPrintf(COLOR_RED, "[  FAILED  ] ");
2775  }
2776  PrintTestName(test_case_name_.c_str(), test_info.name());
2777  if (GTEST_FLAG(print_time)) {
2778    printf(" (%s ms)\n", internal::StreamableToString(
2779           test_info.result()->elapsed_time()).c_str());
2780  } else {
2781    printf("\n");
2782  }
2783  fflush(stdout);
2784}
2785
2786void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {
2787  if (!GTEST_FLAG(print_time)) return;
2788
2789  test_case_name_ = test_case.name();
2790  const internal::String counts =
2791      FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
2792  ColoredPrintf(COLOR_GREEN, "[----------] ");
2793  printf("%s from %s (%s ms total)\n\n",
2794         counts.c_str(), test_case_name_.c_str(),
2795         internal::StreamableToString(test_case.elapsed_time()).c_str());
2796  fflush(stdout);
2797}
2798
2799void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
2800    const UnitTest& /*unit_test*/) {
2801  ColoredPrintf(COLOR_GREEN,  "[----------] ");
2802  printf("Global test environment tear-down\n");
2803  fflush(stdout);
2804}
2805
2806// Internal helper for printing the list of failed tests.
2807void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
2808  const int failed_test_count = unit_test.failed_test_count();
2809  if (failed_test_count == 0) {
2810    return;
2811  }
2812
2813  for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
2814    const TestCase& test_case = *unit_test.GetTestCase(i);
2815    if (!test_case.should_run() || (test_case.failed_test_count() == 0)) {
2816      continue;
2817    }
2818    for (int j = 0; j < test_case.total_test_count(); ++j) {
2819      const TestInfo& test_info = *test_case.GetTestInfo(j);
2820      if (!test_info.should_run() || test_info.result()->Passed()) {
2821        continue;
2822      }
2823      ColoredPrintf(COLOR_RED, "[  FAILED  ] ");
2824      printf("%s.%s", test_case.name(), test_info.name());
2825      if (test_case.comment()[0] != '\0' ||
2826          test_info.comment()[0] != '\0') {
2827        printf(", where %s", test_case.comment());
2828        if (test_case.comment()[0] != '\0' &&
2829            test_info.comment()[0] != '\0') {
2830          printf(" and ");
2831        }
2832      }
2833      printf("%s\n", test_info.comment());
2834    }
2835  }
2836}
2837
2838 void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
2839                                                      int /*iteration*/) {
2840  ColoredPrintf(COLOR_GREEN,  "[==========] ");
2841  printf("%s from %s ran.",
2842         FormatTestCount(unit_test.test_to_run_count()).c_str(),
2843         FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
2844  if (GTEST_FLAG(print_time)) {
2845    printf(" (%s ms total)",
2846           internal::StreamableToString(unit_test.elapsed_time()).c_str());
2847  }
2848  printf("\n");
2849  ColoredPrintf(COLOR_GREEN,  "[  PASSED  ] ");
2850  printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
2851
2852  int num_failures = unit_test.failed_test_count();
2853  if (!unit_test.Passed()) {
2854    const int failed_test_count = unit_test.failed_test_count();
2855    ColoredPrintf(COLOR_RED,  "[  FAILED  ] ");
2856    printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
2857    PrintFailedTests(unit_test);
2858    printf("\n%2d FAILED %s\n", num_failures,
2859                        num_failures == 1 ? "TEST" : "TESTS");
2860  }
2861
2862  int num_disabled = unit_test.disabled_test_count();
2863  if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
2864    if (!num_failures) {
2865      printf("\n");  // Add a spacer if no FAILURE banner is displayed.
2866    }
2867    ColoredPrintf(COLOR_YELLOW,
2868                  "  YOU HAVE %d DISABLED %s\n\n",
2869                  num_disabled,
2870                  num_disabled == 1 ? "TEST" : "TESTS");
2871  }
2872  // Ensure that Google Test output is printed before, e.g., heapchecker output.
2873  fflush(stdout);
2874}
2875
2876// End PrettyUnitTestResultPrinter
2877
2878// class TestEventRepeater
2879//
2880// This class forwards events to other event listeners.
2881class TestEventRepeater : public TestEventListener {
2882 public:
2883  TestEventRepeater() : forwarding_enabled_(true) {}
2884  virtual ~TestEventRepeater();
2885  void Append(TestEventListener *listener);
2886  TestEventListener* Release(TestEventListener* listener);
2887
2888  // Controls whether events will be forwarded to listeners_. Set to false
2889  // in death test child processes.
2890  bool forwarding_enabled() const { return forwarding_enabled_; }
2891  void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }
2892
2893  virtual void OnTestProgramStart(const UnitTest& unit_test);
2894  virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
2895  virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
2896  virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test);
2897  virtual void OnTestCaseStart(const TestCase& test_case);
2898  virtual void OnTestStart(const TestInfo& test_info);
2899  virtual void OnTestPartResult(const TestPartResult& result);
2900  virtual void OnTestEnd(const TestInfo& test_info);
2901  virtual void OnTestCaseEnd(const TestCase& test_case);
2902  virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
2903  virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test);
2904  virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
2905  virtual void OnTestProgramEnd(const UnitTest& unit_test);
2906
2907 private:
2908  // Controls whether events will be forwarded to listeners_. Set to false
2909  // in death test child processes.
2910  bool forwarding_enabled_;
2911  // The list of listeners that receive events.
2912  std::vector<TestEventListener*> listeners_;
2913
2914  GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater);
2915};
2916
2917TestEventRepeater::~TestEventRepeater() {
2918  ForEach(listeners_, Delete<TestEventListener>);
2919}
2920
2921void TestEventRepeater::Append(TestEventListener *listener) {
2922  listeners_.push_back(listener);
2923}
2924
2925// TODO(vladl@google.com): Factor the search functionality into Vector::Find.
2926TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {
2927  for (size_t i = 0; i < listeners_.size(); ++i) {
2928    if (listeners_[i] == listener) {
2929      listeners_.erase(listeners_.begin() + i);
2930      return listener;
2931    }
2932  }
2933
2934  return NULL;
2935}
2936
2937// Since most methods are very similar, use macros to reduce boilerplate.
2938// This defines a member that forwards the call to all listeners.
2939#define GTEST_REPEATER_METHOD_(Name, Type) \
2940void TestEventRepeater::Name(const Type& parameter) { \
2941  if (forwarding_enabled_) { \
2942    for (size_t i = 0; i < listeners_.size(); i++) { \
2943      listeners_[i]->Name(parameter); \
2944    } \
2945  } \
2946}
2947// This defines a member that forwards the call to all listeners in reverse
2948// order.
2949#define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
2950void TestEventRepeater::Name(const Type& parameter) { \
2951  if (forwarding_enabled_) { \
2952    for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \
2953      listeners_[i]->Name(parameter); \
2954    } \
2955  } \
2956}
2957
2958GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)
2959GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)
2960GTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase)
2961GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
2962GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)
2963GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)
2964GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)
2965GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)
2966GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)
2967GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestCase)
2968GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)
2969
2970#undef GTEST_REPEATER_METHOD_
2971#undef GTEST_REVERSE_REPEATER_METHOD_
2972
2973void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,
2974                                             int iteration) {
2975  if (forwarding_enabled_) {
2976    for (size_t i = 0; i < listeners_.size(); i++) {
2977      listeners_[i]->OnTestIterationStart(unit_test, iteration);
2978    }
2979  }
2980}
2981
2982void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,
2983                                           int iteration) {
2984  if (forwarding_enabled_) {
2985    for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) {
2986      listeners_[i]->OnTestIterationEnd(unit_test, iteration);
2987    }
2988  }
2989}
2990
2991// End TestEventRepeater
2992
2993// This class generates an XML output file.
2994class XmlUnitTestResultPrinter : public EmptyTestEventListener {
2995 public:
2996  explicit XmlUnitTestResultPrinter(const char* output_file);
2997
2998  virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
2999
3000 private:
3001  // Is c a whitespace character that is normalized to a space character
3002  // when it appears in an XML attribute value?
3003  static bool IsNormalizableWhitespace(char c) {
3004    return c == 0x9 || c == 0xA || c == 0xD;
3005  }
3006
3007  // May c appear in a well-formed XML document?
3008  static bool IsValidXmlCharacter(char c) {
3009    return IsNormalizableWhitespace(c) || c >= 0x20;
3010  }
3011
3012  // Returns an XML-escaped copy of the input string str.  If
3013  // is_attribute is true, the text is meant to appear as an attribute
3014  // value, and normalizable whitespace is preserved by replacing it
3015  // with character references.
3016  static String EscapeXml(const char* str, bool is_attribute);
3017
3018  // Returns the given string with all characters invalid in XML removed.
3019  static String RemoveInvalidXmlCharacters(const char* str);
3020
3021  // Convenience wrapper around EscapeXml when str is an attribute value.
3022  static String EscapeXmlAttribute(const char* str) {
3023    return EscapeXml(str, true);
3024  }
3025
3026  // Convenience wrapper around EscapeXml when str is not an attribute value.
3027  static String EscapeXmlText(const char* str) { return EscapeXml(str, false); }
3028
3029  // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
3030  static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
3031
3032  // Streams an XML representation of a TestInfo object.
3033  static void OutputXmlTestInfo(::std::ostream* stream,
3034                                const char* test_case_name,
3035                                const TestInfo& test_info);
3036
3037  // Prints an XML representation of a TestCase object
3038  static void PrintXmlTestCase(FILE* out, const TestCase& test_case);
3039
3040  // Prints an XML summary of unit_test to output stream out.
3041  static void PrintXmlUnitTest(FILE* out, const UnitTest& unit_test);
3042
3043  // Produces a string representing the test properties in a result as space
3044  // delimited XML attributes based on the property key="value" pairs.
3045  // When the String is not empty, it includes a space at the beginning,
3046  // to delimit this attribute from prior attributes.
3047  static String TestPropertiesAsXmlAttributes(const TestResult& result);
3048
3049  // The output file.
3050  const String output_file_;
3051
3052  GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);
3053};
3054
3055// Creates a new XmlUnitTestResultPrinter.
3056XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
3057    : output_file_(output_file) {
3058  if (output_file_.c_str() == NULL || output_file_.empty()) {
3059    fprintf(stderr, "XML output file may not be null\n");
3060    fflush(stderr);
3061    exit(EXIT_FAILURE);
3062  }
3063}
3064
3065// Called after the unit test ends.
3066void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
3067                                                  int /*iteration*/) {
3068  FILE* xmlout = NULL;
3069  FilePath output_file(output_file_);
3070  FilePath output_dir(output_file.RemoveFileName());
3071
3072  if (output_dir.CreateDirectoriesRecursively()) {
3073    xmlout = posix::FOpen(output_file_.c_str(), "w");
3074  }
3075  if (xmlout == NULL) {
3076    // TODO(wan): report the reason of the failure.
3077    //
3078    // We don't do it for now as:
3079    //
3080    //   1. There is no urgent need for it.
3081    //   2. It's a bit involved to make the errno variable thread-safe on
3082    //      all three operating systems (Linux, Windows, and Mac OS).
3083    //   3. To interpret the meaning of errno in a thread-safe way,
3084    //      we need the strerror_r() function, which is not available on
3085    //      Windows.
3086    fprintf(stderr,
3087            "Unable to open file \"%s\"\n",
3088            output_file_.c_str());
3089    fflush(stderr);
3090    exit(EXIT_FAILURE);
3091  }
3092  PrintXmlUnitTest(xmlout, unit_test);
3093  fclose(xmlout);
3094}
3095
3096// Returns an XML-escaped copy of the input string str.  If is_attribute
3097// is true, the text is meant to appear as an attribute value, and
3098// normalizable whitespace is preserved by replacing it with character
3099// references.
3100//
3101// Invalid XML characters in str, if any, are stripped from the output.
3102// It is expected that most, if not all, of the text processed by this
3103// module will consist of ordinary English text.
3104// If this module is ever modified to produce version 1.1 XML output,
3105// most invalid characters can be retained using character references.
3106// TODO(wan): It might be nice to have a minimally invasive, human-readable
3107// escaping scheme for invalid characters, rather than dropping them.
3108String XmlUnitTestResultPrinter::EscapeXml(const char* str, bool is_attribute) {
3109  Message m;
3110
3111  if (str != NULL) {
3112    for (const char* src = str; *src; ++src) {
3113      switch (*src) {
3114        case '<':
3115          m << "&lt;";
3116          break;
3117        case '>':
3118          m << "&gt;";
3119          break;
3120        case '&':
3121          m << "&amp;";
3122          break;
3123        case '\'':
3124          if (is_attribute)
3125            m << "&apos;";
3126          else
3127            m << '\'';
3128          break;
3129        case '"':
3130          if (is_attribute)
3131            m << "&quot;";
3132          else
3133            m << '"';
3134          break;
3135        default:
3136          if (IsValidXmlCharacter(*src)) {
3137            if (is_attribute && IsNormalizableWhitespace(*src))
3138              m << String::Format("&#x%02X;", unsigned(*src));
3139            else
3140              m << *src;
3141          }
3142          break;
3143      }
3144    }
3145  }
3146
3147  return m.GetString();
3148}
3149
3150// Returns the given string with all characters invalid in XML removed.
3151// Currently invalid characters are dropped from the string. An
3152// alternative is to replace them with certain characters such as . or ?.
3153String XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(const char* str) {
3154  char* const output = new char[strlen(str) + 1];
3155  char* appender = output;
3156  for (char ch = *str; ch != '\0'; ch = *++str)
3157    if (IsValidXmlCharacter(ch))
3158      *appender++ = ch;
3159  *appender = '\0';
3160
3161  String ret_value(output);
3162  delete[] output;
3163  return ret_value;
3164}
3165
3166// The following routines generate an XML representation of a UnitTest
3167// object.
3168//
3169// This is how Google Test concepts map to the DTD:
3170//
3171// <testsuites name="AllTests">        <-- corresponds to a UnitTest object
3172//   <testsuite name="testcase-name">  <-- corresponds to a TestCase object
3173//     <testcase name="test-name">     <-- corresponds to a TestInfo object
3174//       <failure message="...">...</failure>
3175//       <failure message="...">...</failure>
3176//       <failure message="...">...</failure>
3177//                                     <-- individual assertion failures
3178//     </testcase>
3179//   </testsuite>
3180// </testsuites>
3181
3182// Formats the given time in milliseconds as seconds.
3183std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {
3184  ::std::stringstream ss;
3185  ss << ms/1000.0;
3186  return ss.str();
3187}
3188
3189// Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
3190void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
3191                                                     const char* data) {
3192  const char* segment = data;
3193  *stream << "<![CDATA[";
3194  for (;;) {
3195    const char* const next_segment = strstr(segment, "]]>");
3196    if (next_segment != NULL) {
3197      stream->write(
3198          segment, static_cast<std::streamsize>(next_segment - segment));
3199      *stream << "]]>]]&gt;<![CDATA[";
3200      segment = next_segment + strlen("]]>");
3201    } else {
3202      *stream << segment;
3203      break;
3204    }
3205  }
3206  *stream << "]]>";
3207}
3208
3209// Prints an XML representation of a TestInfo object.
3210// TODO(wan): There is also value in printing properties with the plain printer.
3211void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
3212                                                 const char* test_case_name,
3213                                                 const TestInfo& test_info) {
3214  const TestResult& result = *test_info.result();
3215  *stream << "    <testcase name=\""
3216          << EscapeXmlAttribute(test_info.name()).c_str()
3217          << "\" status=\""
3218          << (test_info.should_run() ? "run" : "notrun")
3219          << "\" time=\""
3220          << FormatTimeInMillisAsSeconds(result.elapsed_time())
3221          << "\" classname=\"" << EscapeXmlAttribute(test_case_name).c_str()
3222          << "\"" << TestPropertiesAsXmlAttributes(result).c_str();
3223
3224  int failures = 0;
3225  for (int i = 0; i < result.total_part_count(); ++i) {
3226    const TestPartResult& part = result.GetTestPartResult(i);
3227    if (part.failed()) {
3228      if (++failures == 1)
3229        *stream << ">\n";
3230      *stream << "      <failure message=\""
3231              << EscapeXmlAttribute(part.summary()).c_str()
3232              << "\" type=\"\">";
3233      const String message = RemoveInvalidXmlCharacters(String::Format(
3234          "%s:%d\n%s",
3235          part.file_name(), part.line_number(),
3236          part.message()).c_str());
3237      OutputXmlCDataSection(stream, message.c_str());
3238      *stream << "</failure>\n";
3239    }
3240  }
3241
3242  if (failures == 0)
3243    *stream << " />\n";
3244  else
3245    *stream << "    </testcase>\n";
3246}
3247
3248// Prints an XML representation of a TestCase object
3249void XmlUnitTestResultPrinter::PrintXmlTestCase(FILE* out,
3250                                                const TestCase& test_case) {
3251  fprintf(out,
3252          "  <testsuite name=\"%s\" tests=\"%d\" failures=\"%d\" "
3253          "disabled=\"%d\" ",
3254          EscapeXmlAttribute(test_case.name()).c_str(),
3255          test_case.total_test_count(),
3256          test_case.failed_test_count(),
3257          test_case.disabled_test_count());
3258  fprintf(out,
3259          "errors=\"0\" time=\"%s\">\n",
3260          FormatTimeInMillisAsSeconds(test_case.elapsed_time()).c_str());
3261  for (int i = 0; i < test_case.total_test_count(); ++i) {
3262    StrStream stream;
3263    OutputXmlTestInfo(&stream, test_case.name(), *test_case.GetTestInfo(i));
3264    fprintf(out, "%s", StrStreamToString(&stream).c_str());
3265  }
3266  fprintf(out, "  </testsuite>\n");
3267}
3268
3269// Prints an XML summary of unit_test to output stream out.
3270void XmlUnitTestResultPrinter::PrintXmlUnitTest(FILE* out,
3271                                                const UnitTest& unit_test) {
3272  fprintf(out, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
3273  fprintf(out,
3274          "<testsuites tests=\"%d\" failures=\"%d\" disabled=\"%d\" "
3275          "errors=\"0\" time=\"%s\" ",
3276          unit_test.total_test_count(),
3277          unit_test.failed_test_count(),
3278          unit_test.disabled_test_count(),
3279          FormatTimeInMillisAsSeconds(unit_test.elapsed_time()).c_str());
3280  if (GTEST_FLAG(shuffle)) {
3281    fprintf(out, "random_seed=\"%d\" ", unit_test.random_seed());
3282  }
3283  fprintf(out, "name=\"AllTests\">\n");
3284  for (int i = 0; i < unit_test.total_test_case_count(); ++i)
3285    PrintXmlTestCase(out, *unit_test.GetTestCase(i));
3286  fprintf(out, "</testsuites>\n");
3287}
3288
3289// Produces a string representing the test properties in a result as space
3290// delimited XML attributes based on the property key="value" pairs.
3291String XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
3292    const TestResult& result) {
3293  Message attributes;
3294  for (int i = 0; i < result.test_property_count(); ++i) {
3295    const TestProperty& property = result.GetTestProperty(i);
3296    attributes << " " << property.key() << "="
3297        << "\"" << EscapeXmlAttribute(property.value()) << "\"";
3298  }
3299  return attributes.GetString();
3300}
3301
3302// End XmlUnitTestResultPrinter
3303
3304// Class ScopedTrace
3305
3306// Pushes the given source file location and message onto a per-thread
3307// trace stack maintained by Google Test.
3308// L < UnitTest::mutex_
3309ScopedTrace::ScopedTrace(const char* file, int line, const Message& message) {
3310  TraceInfo trace;
3311  trace.file = file;
3312  trace.line = line;
3313  trace.message = message.GetString();
3314
3315  UnitTest::GetInstance()->PushGTestTrace(trace);
3316}
3317
3318// Pops the info pushed by the c'tor.
3319// L < UnitTest::mutex_
3320ScopedTrace::~ScopedTrace() {
3321  UnitTest::GetInstance()->PopGTestTrace();
3322}
3323
3324
3325// class OsStackTraceGetter
3326
3327// Returns the current OS stack trace as a String.  Parameters:
3328//
3329//   max_depth  - the maximum number of stack frames to be included
3330//                in the trace.
3331//   skip_count - the number of top frames to be skipped; doesn't count
3332//                against max_depth.
3333//
3334// L < mutex_
3335// We use "L < mutex_" to denote that the function may acquire mutex_.
3336String OsStackTraceGetter::CurrentStackTrace(int, int) {
3337  return String("");
3338}
3339
3340// L < mutex_
3341void OsStackTraceGetter::UponLeavingGTest() {
3342}
3343
3344const char* const
3345OsStackTraceGetter::kElidedFramesMarker =
3346    "... " GTEST_NAME_ " internal frames ...";
3347
3348}  // namespace internal
3349
3350// class TestEventListeners
3351
3352TestEventListeners::TestEventListeners()
3353    : repeater_(new internal::TestEventRepeater()),
3354      default_result_printer_(NULL),
3355      default_xml_generator_(NULL) {
3356}
3357
3358TestEventListeners::~TestEventListeners() { delete repeater_; }
3359
3360// Returns the standard listener responsible for the default console
3361// output.  Can be removed from the listeners list to shut down default
3362// console output.  Note that removing this object from the listener list
3363// with Release transfers its ownership to the user.
3364void TestEventListeners::Append(TestEventListener* listener) {
3365  repeater_->Append(listener);
3366}
3367
3368// Removes the given event listener from the list and returns it.  It then
3369// becomes the caller's responsibility to delete the listener. Returns
3370// NULL if the listener is not found in the list.
3371TestEventListener* TestEventListeners::Release(TestEventListener* listener) {
3372  if (listener == default_result_printer_)
3373    default_result_printer_ = NULL;
3374  else if (listener == default_xml_generator_)
3375    default_xml_generator_ = NULL;
3376  return repeater_->Release(listener);
3377}
3378
3379// Returns repeater that broadcasts the TestEventListener events to all
3380// subscribers.
3381TestEventListener* TestEventListeners::repeater() { return repeater_; }
3382
3383// Sets the default_result_printer attribute to the provided listener.
3384// The listener is also added to the listener list and previous
3385// default_result_printer is removed from it and deleted. The listener can
3386// also be NULL in which case it will not be added to the list. Does
3387// nothing if the previous and the current listener objects are the same.
3388void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
3389  if (default_result_printer_ != listener) {
3390    // It is an error to pass this method a listener that is already in the
3391    // list.
3392    delete Release(default_result_printer_);
3393    default_result_printer_ = listener;
3394    if (listener != NULL)
3395      Append(listener);
3396  }
3397}
3398
3399// Sets the default_xml_generator attribute to the provided listener.  The
3400// listener is also added to the listener list and previous
3401// default_xml_generator is removed from it and deleted. The listener can
3402// also be NULL in which case it will not be added to the list. Does
3403// nothing if the previous and the current listener objects are the same.
3404void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
3405  if (default_xml_generator_ != listener) {
3406    // It is an error to pass this method a listener that is already in the
3407    // list.
3408    delete Release(default_xml_generator_);
3409    default_xml_generator_ = listener;
3410    if (listener != NULL)
3411      Append(listener);
3412  }
3413}
3414
3415// Controls whether events will be forwarded by the repeater to the
3416// listeners in the list.
3417bool TestEventListeners::EventForwardingEnabled() const {
3418  return repeater_->forwarding_enabled();
3419}
3420
3421void TestEventListeners::SuppressEventForwarding() {
3422  repeater_->set_forwarding_enabled(false);
3423}
3424
3425// class UnitTest
3426
3427// Gets the singleton UnitTest object.  The first time this method is
3428// called, a UnitTest object is constructed and returned.  Consecutive
3429// calls will return the same object.
3430//
3431// We don't protect this under mutex_ as a user is not supposed to
3432// call this before main() starts, from which point on the return
3433// value will never change.
3434UnitTest * UnitTest::GetInstance() {
3435  // When compiled with MSVC 7.1 in optimized mode, destroying the
3436  // UnitTest object upon exiting the program messes up the exit code,
3437  // causing successful tests to appear failed.  We have to use a
3438  // different implementation in this case to bypass the compiler bug.
3439  // This implementation makes the compiler happy, at the cost of
3440  // leaking the UnitTest object.
3441
3442  // CodeGear C++Builder insists on a public destructor for the
3443  // default implementation.  Use this implementation to keep good OO
3444  // design with private destructor.
3445
3446#if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
3447  static UnitTest* const instance = new UnitTest;
3448  return instance;
3449#else
3450  static UnitTest instance;
3451  return &instance;
3452#endif  // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
3453}
3454
3455// Gets the number of successful test cases.
3456int UnitTest::successful_test_case_count() const {
3457  return impl()->successful_test_case_count();
3458}
3459
3460// Gets the number of failed test cases.
3461int UnitTest::failed_test_case_count() const {
3462  return impl()->failed_test_case_count();
3463}
3464
3465// Gets the number of all test cases.
3466int UnitTest::total_test_case_count() const {
3467  return impl()->total_test_case_count();
3468}
3469
3470// Gets the number of all test cases that contain at least one test
3471// that should run.
3472int UnitTest::test_case_to_run_count() const {
3473  return impl()->test_case_to_run_count();
3474}
3475
3476// Gets the number of successful tests.
3477int UnitTest::successful_test_count() const {
3478  return impl()->successful_test_count();
3479}
3480
3481// Gets the number of failed tests.
3482int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
3483
3484// Gets the number of disabled tests.
3485int UnitTest::disabled_test_count() const {
3486  return impl()->disabled_test_count();
3487}
3488
3489// Gets the number of all tests.
3490int UnitTest::total_test_count() const { return impl()->total_test_count(); }
3491
3492// Gets the number of tests that should run.
3493int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
3494
3495// Gets the elapsed time, in milliseconds.
3496internal::TimeInMillis UnitTest::elapsed_time() const {
3497  return impl()->elapsed_time();
3498}
3499
3500// Returns true iff the unit test passed (i.e. all test cases passed).
3501bool UnitTest::Passed() const { return impl()->Passed(); }
3502
3503// Returns true iff the unit test failed (i.e. some test case failed
3504// or something outside of all tests failed).
3505bool UnitTest::Failed() const { return impl()->Failed(); }
3506
3507// Gets the i-th test case among all the test cases. i can range from 0 to
3508// total_test_case_count() - 1. If i is not in that range, returns NULL.
3509const TestCase* UnitTest::GetTestCase(int i) const {
3510  return impl()->GetTestCase(i);
3511}
3512
3513// Gets the i-th test case among all the test cases. i can range from 0 to
3514// total_test_case_count() - 1. If i is not in that range, returns NULL.
3515TestCase* UnitTest::GetMutableTestCase(int i) {
3516  return impl()->GetMutableTestCase(i);
3517}
3518
3519// Returns the list of event listeners that can be used to track events
3520// inside Google Test.
3521TestEventListeners& UnitTest::listeners() {
3522  return *impl()->listeners();
3523}
3524
3525// Registers and returns a global test environment.  When a test
3526// program is run, all global test environments will be set-up in the
3527// order they were registered.  After all tests in the program have
3528// finished, all global test environments will be torn-down in the
3529// *reverse* order they were registered.
3530//
3531// The UnitTest object takes ownership of the given environment.
3532//
3533// We don't protect this under mutex_, as we only support calling it
3534// from the main thread.
3535Environment* UnitTest::AddEnvironment(Environment* env) {
3536  if (env == NULL) {
3537    return NULL;
3538  }
3539
3540  impl_->environments().push_back(env);
3541  return env;
3542}
3543
3544#if GTEST_HAS_EXCEPTIONS
3545// A failed Google Test assertion will throw an exception of this type
3546// when exceptions are enabled.  We derive it from std::runtime_error,
3547// which is for errors presumably detectable only at run time.  Since
3548// std::runtime_error inherits from std::exception, many testing
3549// frameworks know how to extract and print the message inside it.
3550class GoogleTestFailureException : public ::std::runtime_error {
3551 public:
3552  explicit GoogleTestFailureException(const TestPartResult& failure)
3553      : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
3554};
3555#endif
3556
3557// Adds a TestPartResult to the current TestResult object.  All Google Test
3558// assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
3559// this to report their results.  The user code should use the
3560// assertion macros instead of calling this directly.
3561// L < mutex_
3562void UnitTest::AddTestPartResult(TestPartResult::Type result_type,
3563                                 const char* file_name,
3564                                 int line_number,
3565                                 const internal::String& message,
3566                                 const internal::String& os_stack_trace) {
3567  Message msg;
3568  msg << message;
3569
3570  internal::MutexLock lock(&mutex_);
3571  if (impl_->gtest_trace_stack().size() > 0) {
3572    msg << "\n" << GTEST_NAME_ << " trace:";
3573
3574    for (int i = static_cast<int>(impl_->gtest_trace_stack().size());
3575         i > 0; --i) {
3576      const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
3577      msg << "\n" << internal::FormatFileLocation(trace.file, trace.line)
3578          << " " << trace.message;
3579    }
3580  }
3581
3582  if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) {
3583    msg << internal::kStackTraceMarker << os_stack_trace;
3584  }
3585
3586  const TestPartResult result =
3587    TestPartResult(result_type, file_name, line_number,
3588                   msg.GetString().c_str());
3589  impl_->GetTestPartResultReporterForCurrentThread()->
3590      ReportTestPartResult(result);
3591
3592  if (result_type != TestPartResult::kSuccess) {
3593    // gtest_break_on_failure takes precedence over
3594    // gtest_throw_on_failure.  This allows a user to set the latter
3595    // in the code (perhaps in order to use Google Test assertions
3596    // with another testing framework) and specify the former on the
3597    // command line for debugging.
3598    if (GTEST_FLAG(break_on_failure)) {
3599#if GTEST_OS_WINDOWS
3600      // Using DebugBreak on Windows allows gtest to still break into a debugger
3601      // when a failure happens and both the --gtest_break_on_failure and
3602      // the --gtest_catch_exceptions flags are specified.
3603      DebugBreak();
3604#else
3605      *static_cast<int*>(NULL) = 1;
3606#endif  // GTEST_OS_WINDOWS
3607    } else if (GTEST_FLAG(throw_on_failure)) {
3608#if GTEST_HAS_EXCEPTIONS
3609      throw GoogleTestFailureException(result);
3610#else
3611      // We cannot call abort() as it generates a pop-up in debug mode
3612      // that cannot be suppressed in VC 7.1 or below.
3613      exit(1);
3614#endif
3615    }
3616  }
3617}
3618
3619// Creates and adds a property to the current TestResult. If a property matching
3620// the supplied value already exists, updates its value instead.
3621void UnitTest::RecordPropertyForCurrentTest(const char* key,
3622                                            const char* value) {
3623  const TestProperty test_property(key, value);
3624  impl_->current_test_result()->RecordProperty(test_property);
3625}
3626
3627// Runs all tests in this UnitTest object and prints the result.
3628// Returns 0 if successful, or 1 otherwise.
3629//
3630// We don't protect this under mutex_, as we only support calling it
3631// from the main thread.
3632int UnitTest::Run() {
3633#if GTEST_HAS_SEH
3634  // Catch SEH-style exceptions.
3635
3636  const bool in_death_test_child_process =
3637      internal::GTEST_FLAG(internal_run_death_test).length() > 0;
3638
3639  // Either the user wants Google Test to catch exceptions thrown by the
3640  // tests or this is executing in the context of death test child
3641  // process. In either case the user does not want to see pop-up dialogs
3642  // about crashes - they are expected..
3643  if (GTEST_FLAG(catch_exceptions) || in_death_test_child_process) {
3644#if !GTEST_OS_WINDOWS_MOBILE
3645    // SetErrorMode doesn't exist on CE.
3646    SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
3647                 SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
3648#endif  // !GTEST_OS_WINDOWS_MOBILE
3649
3650#if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
3651    // Death test children can be terminated with _abort().  On Windows,
3652    // _abort() can show a dialog with a warning message.  This forces the
3653    // abort message to go to stderr instead.
3654    _set_error_mode(_OUT_TO_STDERR);
3655#endif
3656
3657#if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
3658    // In the debug version, Visual Studio pops up a separate dialog
3659    // offering a choice to debug the aborted program. We need to suppress
3660    // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
3661    // executed. Google Test will notify the user of any unexpected
3662    // failure via stderr.
3663    //
3664    // VC++ doesn't define _set_abort_behavior() prior to the version 8.0.
3665    // Users of prior VC versions shall suffer the agony and pain of
3666    // clicking through the countless debug dialogs.
3667    // TODO(vladl@google.com): find a way to suppress the abort dialog() in the
3668    // debug mode when compiled with VC 7.1 or lower.
3669    if (!GTEST_FLAG(break_on_failure))
3670      _set_abort_behavior(
3671          0x0,                                    // Clear the following flags:
3672          _WRITE_ABORT_MSG | _CALL_REPORTFAULT);  // pop-up window, core dump.
3673#endif
3674  }
3675
3676  __try {
3677    return impl_->RunAllTests();
3678  } __except(internal::UnitTestOptions::GTestShouldProcessSEH(
3679      GetExceptionCode())) {
3680    printf("Exception thrown with code 0x%x.\nFAIL\n", GetExceptionCode());
3681    fflush(stdout);
3682    return 1;
3683  }
3684
3685#else  // We are on a compiler or platform that doesn't support SEH.
3686
3687  return impl_->RunAllTests();
3688#endif  // GTEST_HAS_SEH
3689}
3690
3691// Returns the working directory when the first TEST() or TEST_F() was
3692// executed.
3693const char* UnitTest::original_working_dir() const {
3694  return impl_->original_working_dir_.c_str();
3695}
3696
3697// Returns the TestCase object for the test that's currently running,
3698// or NULL if no test is running.
3699// L < mutex_
3700const TestCase* UnitTest::current_test_case() const {
3701  internal::MutexLock lock(&mutex_);
3702  return impl_->current_test_case();
3703}
3704
3705// Returns the TestInfo object for the test that's currently running,
3706// or NULL if no test is running.
3707// L < mutex_
3708const TestInfo* UnitTest::current_test_info() const {
3709  internal::MutexLock lock(&mutex_);
3710  return impl_->current_test_info();
3711}
3712
3713// Returns the random seed used at the start of the current test run.
3714int UnitTest::random_seed() const { return impl_->random_seed(); }
3715
3716#if GTEST_HAS_PARAM_TEST
3717// Returns ParameterizedTestCaseRegistry object used to keep track of
3718// value-parameterized tests and instantiate and register them.
3719// L < mutex_
3720internal::ParameterizedTestCaseRegistry&
3721    UnitTest::parameterized_test_registry() {
3722  return impl_->parameterized_test_registry();
3723}
3724#endif  // GTEST_HAS_PARAM_TEST
3725
3726// Creates an empty UnitTest.
3727UnitTest::UnitTest() {
3728  impl_ = new internal::UnitTestImpl(this);
3729}
3730
3731// Destructor of UnitTest.
3732UnitTest::~UnitTest() {
3733  delete impl_;
3734}
3735
3736// Pushes a trace defined by SCOPED_TRACE() on to the per-thread
3737// Google Test trace stack.
3738// L < mutex_
3739void UnitTest::PushGTestTrace(const internal::TraceInfo& trace) {
3740  internal::MutexLock lock(&mutex_);
3741  impl_->gtest_trace_stack().push_back(trace);
3742}
3743
3744// Pops a trace from the per-thread Google Test trace stack.
3745// L < mutex_
3746void UnitTest::PopGTestTrace() {
3747  internal::MutexLock lock(&mutex_);
3748  impl_->gtest_trace_stack().pop_back();
3749}
3750
3751namespace internal {
3752
3753UnitTestImpl::UnitTestImpl(UnitTest* parent)
3754    : parent_(parent),
3755#ifdef _MSC_VER
3756#pragma warning(push)                    // Saves the current warning state.
3757#pragma warning(disable:4355)            // Temporarily disables warning 4355
3758                                         // (using this in initializer).
3759      default_global_test_part_result_reporter_(this),
3760      default_per_thread_test_part_result_reporter_(this),
3761#pragma warning(pop)                     // Restores the warning state again.
3762#else
3763      default_global_test_part_result_reporter_(this),
3764      default_per_thread_test_part_result_reporter_(this),
3765#endif  // _MSC_VER
3766      global_test_part_result_repoter_(
3767          &default_global_test_part_result_reporter_),
3768      per_thread_test_part_result_reporter_(
3769          &default_per_thread_test_part_result_reporter_),
3770#if GTEST_HAS_PARAM_TEST
3771      parameterized_test_registry_(),
3772      parameterized_tests_registered_(false),
3773#endif  // GTEST_HAS_PARAM_TEST
3774      last_death_test_case_(-1),
3775      current_test_case_(NULL),
3776      current_test_info_(NULL),
3777      ad_hoc_test_result_(),
3778      os_stack_trace_getter_(NULL),
3779      post_flag_parse_init_performed_(false),
3780      random_seed_(0),  // Will be overridden by the flag before first use.
3781      random_(0),  // Will be reseeded before first use.
3782#if GTEST_HAS_DEATH_TEST
3783      elapsed_time_(0),
3784      internal_run_death_test_flag_(NULL),
3785      death_test_factory_(new DefaultDeathTestFactory) {
3786#else
3787      elapsed_time_(0) {
3788#endif  // GTEST_HAS_DEATH_TEST
3789  listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);
3790}
3791
3792UnitTestImpl::~UnitTestImpl() {
3793  // Deletes every TestCase.
3794  ForEach(test_cases_, internal::Delete<TestCase>);
3795
3796  // Deletes every Environment.
3797  ForEach(environments_, internal::Delete<Environment>);
3798
3799  delete os_stack_trace_getter_;
3800}
3801
3802#if GTEST_HAS_DEATH_TEST
3803// Disables event forwarding if the control is currently in a death test
3804// subprocess. Must not be called before InitGoogleTest.
3805void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
3806  if (internal_run_death_test_flag_.get() != NULL)
3807    listeners()->SuppressEventForwarding();
3808}
3809#endif  // GTEST_HAS_DEATH_TEST
3810
3811// Initializes event listeners performing XML output as specified by
3812// UnitTestOptions. Must not be called before InitGoogleTest.
3813void UnitTestImpl::ConfigureXmlOutput() {
3814  const String& output_format = UnitTestOptions::GetOutputFormat();
3815  if (output_format == "xml") {
3816    listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
3817        UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
3818  } else if (output_format != "") {
3819    printf("WARNING: unrecognized output format \"%s\" ignored.\n",
3820           output_format.c_str());
3821    fflush(stdout);
3822  }
3823}
3824
3825// Performs initialization dependent upon flag values obtained in
3826// ParseGoogleTestFlagsOnly.  Is called from InitGoogleTest after the call to
3827// ParseGoogleTestFlagsOnly.  In case a user neglects to call InitGoogleTest
3828// this function is also called from RunAllTests.  Since this function can be
3829// called more than once, it has to be idempotent.
3830void UnitTestImpl::PostFlagParsingInit() {
3831  // Ensures that this function does not execute more than once.
3832  if (!post_flag_parse_init_performed_) {
3833    post_flag_parse_init_performed_ = true;
3834
3835#if GTEST_HAS_DEATH_TEST
3836    InitDeathTestSubprocessControlInfo();
3837    SuppressTestEventsIfInSubprocess();
3838#endif  // GTEST_HAS_DEATH_TEST
3839
3840    // Registers parameterized tests. This makes parameterized tests
3841    // available to the UnitTest reflection API without running
3842    // RUN_ALL_TESTS.
3843    RegisterParameterizedTests();
3844
3845    // Configures listeners for XML output. This makes it possible for users
3846    // to shut down the default XML output before invoking RUN_ALL_TESTS.
3847    ConfigureXmlOutput();
3848  }
3849}
3850
3851// A predicate that checks the name of a TestCase against a known
3852// value.
3853//
3854// This is used for implementation of the UnitTest class only.  We put
3855// it in the anonymous namespace to prevent polluting the outer
3856// namespace.
3857//
3858// TestCaseNameIs is copyable.
3859class TestCaseNameIs {
3860 public:
3861  // Constructor.
3862  explicit TestCaseNameIs(const String& name)
3863      : name_(name) {}
3864
3865  // Returns true iff the name of test_case matches name_.
3866  bool operator()(const TestCase* test_case) const {
3867    return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0;
3868  }
3869
3870 private:
3871  String name_;
3872};
3873
3874// Finds and returns a TestCase with the given name.  If one doesn't
3875// exist, creates one and returns it.  It's the CALLER'S
3876// RESPONSIBILITY to ensure that this function is only called WHEN THE
3877// TESTS ARE NOT SHUFFLED.
3878//
3879// Arguments:
3880//
3881//   test_case_name: name of the test case
3882//   set_up_tc:      pointer to the function that sets up the test case
3883//   tear_down_tc:   pointer to the function that tears down the test case
3884TestCase* UnitTestImpl::GetTestCase(const char* test_case_name,
3885                                    const char* comment,
3886                                    Test::SetUpTestCaseFunc set_up_tc,
3887                                    Test::TearDownTestCaseFunc tear_down_tc) {
3888  // Can we find a TestCase with the given name?
3889  const std::vector<TestCase*>::const_iterator test_case =
3890      std::find_if(test_cases_.begin(), test_cases_.end(),
3891                   TestCaseNameIs(test_case_name));
3892
3893  if (test_case != test_cases_.end())
3894    return *test_case;
3895
3896  // No.  Let's create one.
3897  TestCase* const new_test_case =
3898      new TestCase(test_case_name, comment, set_up_tc, tear_down_tc);
3899
3900  // Is this a death test case?
3901  if (internal::UnitTestOptions::MatchesFilter(String(test_case_name),
3902                                               kDeathTestCaseFilter)) {
3903    // Yes.  Inserts the test case after the last death test case
3904    // defined so far.  This only works when the test cases haven't
3905    // been shuffled.  Otherwise we may end up running a death test
3906    // after a non-death test.
3907    ++last_death_test_case_;
3908    test_cases_.insert(test_cases_.begin() + last_death_test_case_,
3909                       new_test_case);
3910  } else {
3911    // No.  Appends to the end of the list.
3912    test_cases_.push_back(new_test_case);
3913  }
3914
3915  test_case_indices_.push_back(static_cast<int>(test_case_indices_.size()));
3916  return new_test_case;
3917}
3918
3919// Helpers for setting up / tearing down the given environment.  They
3920// are for use in the ForEach() function.
3921static void SetUpEnvironment(Environment* env) { env->SetUp(); }
3922static void TearDownEnvironment(Environment* env) { env->TearDown(); }
3923
3924// Runs all tests in this UnitTest object, prints the result, and
3925// returns 0 if all tests are successful, or 1 otherwise.  If any
3926// exception is thrown during a test on Windows, this test is
3927// considered to be failed, but the rest of the tests will still be
3928// run.  (We disable exceptions on Linux and Mac OS X, so the issue
3929// doesn't apply there.)
3930// When parameterized tests are enabled, it expands and registers
3931// parameterized tests first in RegisterParameterizedTests().
3932// All other functions called from RunAllTests() may safely assume that
3933// parameterized tests are ready to be counted and run.
3934int UnitTestImpl::RunAllTests() {
3935  // Makes sure InitGoogleTest() was called.
3936  if (!GTestIsInitialized()) {
3937    printf("%s",
3938           "\nThis test program did NOT call ::testing::InitGoogleTest "
3939           "before calling RUN_ALL_TESTS().  Please fix it.\n");
3940    return 1;
3941  }
3942
3943  // Do not run any test if the --help flag was specified.
3944  if (g_help_flag)
3945    return 0;
3946
3947  // Repeats the call to the post-flag parsing initialization in case the
3948  // user didn't call InitGoogleTest.
3949  PostFlagParsingInit();
3950
3951  // Even if sharding is not on, test runners may want to use the
3952  // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
3953  // protocol.
3954  internal::WriteToShardStatusFileIfNeeded();
3955
3956  // True iff we are in a subprocess for running a thread-safe-style
3957  // death test.
3958  bool in_subprocess_for_death_test = false;
3959
3960#if GTEST_HAS_DEATH_TEST
3961  in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL);
3962#endif  // GTEST_HAS_DEATH_TEST
3963
3964  const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
3965                                        in_subprocess_for_death_test);
3966
3967  // Compares the full test names with the filter to decide which
3968  // tests to run.
3969  const bool has_tests_to_run = FilterTests(should_shard
3970                                              ? HONOR_SHARDING_PROTOCOL
3971                                              : IGNORE_SHARDING_PROTOCOL) > 0;
3972
3973  // Lists the tests and exits if the --gtest_list_tests flag was specified.
3974  if (GTEST_FLAG(list_tests)) {
3975    // This must be called *after* FilterTests() has been called.
3976    ListTestsMatchingFilter();
3977    return 0;
3978  }
3979
3980  random_seed_ = GTEST_FLAG(shuffle) ?
3981      GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;
3982
3983  // True iff at least one test has failed.
3984  bool failed = false;
3985
3986  TestEventListener* repeater = listeners()->repeater();
3987
3988  repeater->OnTestProgramStart(*parent_);
3989
3990  // How many times to repeat the tests?  We don't want to repeat them
3991  // when we are inside the subprocess of a death test.
3992  const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);
3993  // Repeats forever if the repeat count is negative.
3994  const bool forever = repeat < 0;
3995  for (int i = 0; forever || i != repeat; i++) {
3996    ClearResult();
3997
3998    const TimeInMillis start = GetTimeInMillis();
3999
4000    // Shuffles test cases and tests if requested.
4001    if (has_tests_to_run && GTEST_FLAG(shuffle)) {
4002      random()->Reseed(random_seed_);
4003      // This should be done before calling OnTestIterationStart(),
4004      // such that a test event listener can see the actual test order
4005      // in the event.
4006      ShuffleTests();
4007    }
4008
4009    // Tells the unit test event listeners that the tests are about to start.
4010    repeater->OnTestIterationStart(*parent_, i);
4011
4012    // Runs each test case if there is at least one test to run.
4013    if (has_tests_to_run) {
4014      // Sets up all environments beforehand.
4015      repeater->OnEnvironmentsSetUpStart(*parent_);
4016      ForEach(environments_, SetUpEnvironment);
4017      repeater->OnEnvironmentsSetUpEnd(*parent_);
4018
4019      // Runs the tests only if there was no fatal failure during global
4020      // set-up.
4021      if (!Test::HasFatalFailure()) {
4022        for (int test_index = 0; test_index < total_test_case_count();
4023             test_index++) {
4024          GetMutableTestCase(test_index)->Run();
4025        }
4026      }
4027
4028      // Tears down all environments in reverse order afterwards.
4029      repeater->OnEnvironmentsTearDownStart(*parent_);
4030      std::for_each(environments_.rbegin(), environments_.rend(),
4031                    TearDownEnvironment);
4032      repeater->OnEnvironmentsTearDownEnd(*parent_);
4033    }
4034
4035    elapsed_time_ = GetTimeInMillis() - start;
4036
4037    // Tells the unit test event listener that the tests have just finished.
4038    repeater->OnTestIterationEnd(*parent_, i);
4039
4040    // Gets the result and clears it.
4041    if (!Passed()) {
4042      failed = true;
4043    }
4044
4045    // Restores the original test order after the iteration.  This
4046    // allows the user to quickly repro a failure that happens in the
4047    // N-th iteration without repeating the first (N - 1) iterations.
4048    // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in
4049    // case the user somehow changes the value of the flag somewhere
4050    // (it's always safe to unshuffle the tests).
4051    UnshuffleTests();
4052
4053    if (GTEST_FLAG(shuffle)) {
4054      // Picks a new random seed for each iteration.
4055      random_seed_ = GetNextRandomSeed(random_seed_);
4056    }
4057  }
4058
4059  repeater->OnTestProgramEnd(*parent_);
4060
4061  // Returns 0 if all tests passed, or 1 other wise.
4062  return failed ? 1 : 0;
4063}
4064
4065// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
4066// if the variable is present. If a file already exists at this location, this
4067// function will write over it. If the variable is present, but the file cannot
4068// be created, prints an error and exits.
4069void WriteToShardStatusFileIfNeeded() {
4070  const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);
4071  if (test_shard_file != NULL) {
4072    FILE* const file = posix::FOpen(test_shard_file, "w");
4073    if (file == NULL) {
4074      ColoredPrintf(COLOR_RED,
4075                    "Could not write to the test shard status file \"%s\" "
4076                    "specified by the %s environment variable.\n",
4077                    test_shard_file, kTestShardStatusFile);
4078      fflush(stdout);
4079      exit(EXIT_FAILURE);
4080    }
4081    fclose(file);
4082  }
4083}
4084
4085// Checks whether sharding is enabled by examining the relevant
4086// environment variable values. If the variables are present,
4087// but inconsistent (i.e., shard_index >= total_shards), prints
4088// an error and exits. If in_subprocess_for_death_test, sharding is
4089// disabled because it must only be applied to the original test
4090// process. Otherwise, we could filter out death tests we intended to execute.
4091bool ShouldShard(const char* total_shards_env,
4092                 const char* shard_index_env,
4093                 bool in_subprocess_for_death_test) {
4094  if (in_subprocess_for_death_test) {
4095    return false;
4096  }
4097
4098  const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1);
4099  const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1);
4100
4101  if (total_shards == -1 && shard_index == -1) {
4102    return false;
4103  } else if (total_shards == -1 && shard_index != -1) {
4104    const Message msg = Message()
4105      << "Invalid environment variables: you have "
4106      << kTestShardIndex << " = " << shard_index
4107      << ", but have left " << kTestTotalShards << " unset.\n";
4108    ColoredPrintf(COLOR_RED, msg.GetString().c_str());
4109    fflush(stdout);
4110    exit(EXIT_FAILURE);
4111  } else if (total_shards != -1 && shard_index == -1) {
4112    const Message msg = Message()
4113      << "Invalid environment variables: you have "
4114      << kTestTotalShards << " = " << total_shards
4115      << ", but have left " << kTestShardIndex << " unset.\n";
4116    ColoredPrintf(COLOR_RED, msg.GetString().c_str());
4117    fflush(stdout);
4118    exit(EXIT_FAILURE);
4119  } else if (shard_index < 0 || shard_index >= total_shards) {
4120    const Message msg = Message()
4121      << "Invalid environment variables: we require 0 <= "
4122      << kTestShardIndex << " < " << kTestTotalShards
4123      << ", but you have " << kTestShardIndex << "=" << shard_index
4124      << ", " << kTestTotalShards << "=" << total_shards << ".\n";
4125    ColoredPrintf(COLOR_RED, msg.GetString().c_str());
4126    fflush(stdout);
4127    exit(EXIT_FAILURE);
4128  }
4129
4130  return total_shards > 1;
4131}
4132
4133// Parses the environment variable var as an Int32. If it is unset,
4134// returns default_val. If it is not an Int32, prints an error
4135// and aborts.
4136Int32 Int32FromEnvOrDie(const char* const var, Int32 default_val) {
4137  const char* str_val = posix::GetEnv(var);
4138  if (str_val == NULL) {
4139    return default_val;
4140  }
4141
4142  Int32 result;
4143  if (!ParseInt32(Message() << "The value of environment variable " << var,
4144                  str_val, &result)) {
4145    exit(EXIT_FAILURE);
4146  }
4147  return result;
4148}
4149
4150// Given the total number of shards, the shard index, and the test id,
4151// returns true iff the test should be run on this shard. The test id is
4152// some arbitrary but unique non-negative integer assigned to each test
4153// method. Assumes that 0 <= shard_index < total_shards.
4154bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
4155  return (test_id % total_shards) == shard_index;
4156}
4157
4158// Compares the name of each test with the user-specified filter to
4159// decide whether the test should be run, then records the result in
4160// each TestCase and TestInfo object.
4161// If shard_tests == true, further filters tests based on sharding
4162// variables in the environment - see
4163// http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide.
4164// Returns the number of tests that should run.
4165int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
4166  const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?
4167      Int32FromEnvOrDie(kTestTotalShards, -1) : -1;
4168  const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?
4169      Int32FromEnvOrDie(kTestShardIndex, -1) : -1;
4170
4171  // num_runnable_tests are the number of tests that will
4172  // run across all shards (i.e., match filter and are not disabled).
4173  // num_selected_tests are the number of tests to be run on
4174  // this shard.
4175  int num_runnable_tests = 0;
4176  int num_selected_tests = 0;
4177  for (size_t i = 0; i < test_cases_.size(); i++) {
4178    TestCase* const test_case = test_cases_[i];
4179    const String &test_case_name = test_case->name();
4180    test_case->set_should_run(false);
4181
4182    for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
4183      TestInfo* const test_info = test_case->test_info_list()[j];
4184      const String test_name(test_info->name());
4185      // A test is disabled if test case name or test name matches
4186      // kDisableTestFilter.
4187      const bool is_disabled =
4188          internal::UnitTestOptions::MatchesFilter(test_case_name,
4189                                                   kDisableTestFilter) ||
4190          internal::UnitTestOptions::MatchesFilter(test_name,
4191                                                   kDisableTestFilter);
4192      test_info->impl()->set_is_disabled(is_disabled);
4193
4194      const bool matches_filter =
4195          internal::UnitTestOptions::FilterMatchesTest(test_case_name,
4196                                                       test_name);
4197      test_info->impl()->set_matches_filter(matches_filter);
4198
4199      const bool is_runnable =
4200          (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
4201          matches_filter;
4202
4203      const bool is_selected = is_runnable &&
4204          (shard_tests == IGNORE_SHARDING_PROTOCOL ||
4205           ShouldRunTestOnShard(total_shards, shard_index,
4206                                num_runnable_tests));
4207
4208      num_runnable_tests += is_runnable;
4209      num_selected_tests += is_selected;
4210
4211      test_info->impl()->set_should_run(is_selected);
4212      test_case->set_should_run(test_case->should_run() || is_selected);
4213    }
4214  }
4215  return num_selected_tests;
4216}
4217
4218// Prints the names of the tests matching the user-specified filter flag.
4219void UnitTestImpl::ListTestsMatchingFilter() {
4220  for (size_t i = 0; i < test_cases_.size(); i++) {
4221    const TestCase* const test_case = test_cases_[i];
4222    bool printed_test_case_name = false;
4223
4224    for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
4225      const TestInfo* const test_info =
4226          test_case->test_info_list()[j];
4227      if (test_info->matches_filter()) {
4228        if (!printed_test_case_name) {
4229          printed_test_case_name = true;
4230          printf("%s.\n", test_case->name());
4231        }
4232        printf("  %s\n", test_info->name());
4233      }
4234    }
4235  }
4236  fflush(stdout);
4237}
4238
4239// Sets the OS stack trace getter.
4240//
4241// Does nothing if the input and the current OS stack trace getter are
4242// the same; otherwise, deletes the old getter and makes the input the
4243// current getter.
4244void UnitTestImpl::set_os_stack_trace_getter(
4245    OsStackTraceGetterInterface* getter) {
4246  if (os_stack_trace_getter_ != getter) {
4247    delete os_stack_trace_getter_;
4248    os_stack_trace_getter_ = getter;
4249  }
4250}
4251
4252// Returns the current OS stack trace getter if it is not NULL;
4253// otherwise, creates an OsStackTraceGetter, makes it the current
4254// getter, and returns it.
4255OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
4256  if (os_stack_trace_getter_ == NULL) {
4257    os_stack_trace_getter_ = new OsStackTraceGetter;
4258  }
4259
4260  return os_stack_trace_getter_;
4261}
4262
4263// Returns the TestResult for the test that's currently running, or
4264// the TestResult for the ad hoc test if no test is running.
4265TestResult* UnitTestImpl::current_test_result() {
4266  return current_test_info_ ?
4267    current_test_info_->impl()->result() : &ad_hoc_test_result_;
4268}
4269
4270// Shuffles all test cases, and the tests within each test case,
4271// making sure that death tests are still run first.
4272void UnitTestImpl::ShuffleTests() {
4273  // Shuffles the death test cases.
4274  ShuffleRange(random(), 0, last_death_test_case_ + 1, &test_case_indices_);
4275
4276  // Shuffles the non-death test cases.
4277  ShuffleRange(random(), last_death_test_case_ + 1,
4278               static_cast<int>(test_cases_.size()), &test_case_indices_);
4279
4280  // Shuffles the tests inside each test case.
4281  for (size_t i = 0; i < test_cases_.size(); i++) {
4282    test_cases_[i]->ShuffleTests(random());
4283  }
4284}
4285
4286// Restores the test cases and tests to their order before the first shuffle.
4287void UnitTestImpl::UnshuffleTests() {
4288  for (size_t i = 0; i < test_cases_.size(); i++) {
4289    // Unshuffles the tests in each test case.
4290    test_cases_[i]->UnshuffleTests();
4291    // Resets the index of each test case.
4292    test_case_indices_[i] = static_cast<int>(i);
4293  }
4294}
4295
4296// TestInfoImpl constructor. The new instance assumes ownership of the test
4297// factory object.
4298TestInfoImpl::TestInfoImpl(TestInfo* parent,
4299                           const char* a_test_case_name,
4300                           const char* a_name,
4301                           const char* a_test_case_comment,
4302                           const char* a_comment,
4303                           TypeId a_fixture_class_id,
4304                           internal::TestFactoryBase* factory) :
4305    parent_(parent),
4306    test_case_name_(String(a_test_case_name)),
4307    name_(String(a_name)),
4308    test_case_comment_(String(a_test_case_comment)),
4309    comment_(String(a_comment)),
4310    fixture_class_id_(a_fixture_class_id),
4311    should_run_(false),
4312    is_disabled_(false),
4313    matches_filter_(false),
4314    factory_(factory) {
4315}
4316
4317// TestInfoImpl destructor.
4318TestInfoImpl::~TestInfoImpl() {
4319  delete factory_;
4320}
4321
4322// Returns the current OS stack trace as a String.
4323//
4324// The maximum number of stack frames to be included is specified by
4325// the gtest_stack_trace_depth flag.  The skip_count parameter
4326// specifies the number of top frames to be skipped, which doesn't
4327// count against the number of frames to be included.
4328//
4329// For example, if Foo() calls Bar(), which in turn calls
4330// GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
4331// the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
4332String GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/,
4333                                       int skip_count) {
4334  // We pass skip_count + 1 to skip this wrapper function in addition
4335  // to what the user really wants to skip.
4336  return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
4337}
4338
4339// Used by the GTEST_HIDE_UNREACHABLE_CODE_ macro to suppress unreachable
4340// code warnings.
4341namespace {
4342class ClassUniqueToAlwaysTrue {};
4343}
4344
4345bool IsTrue(bool condition) { return condition; }
4346
4347bool AlwaysTrue() {
4348#if GTEST_HAS_EXCEPTIONS
4349  // This condition is always false so AlwaysTrue() never actually throws,
4350  // but it makes the compiler think that it may throw.
4351  if (IsTrue(false))
4352    throw ClassUniqueToAlwaysTrue();
4353#endif  // GTEST_HAS_EXCEPTIONS
4354  return true;
4355}
4356
4357// If *pstr starts with the given prefix, modifies *pstr to be right
4358// past the prefix and returns true; otherwise leaves *pstr unchanged
4359// and returns false.  None of pstr, *pstr, and prefix can be NULL.
4360bool SkipPrefix(const char* prefix, const char** pstr) {
4361  const size_t prefix_len = strlen(prefix);
4362  if (strncmp(*pstr, prefix, prefix_len) == 0) {
4363    *pstr += prefix_len;
4364    return true;
4365  }
4366  return false;
4367}
4368
4369// Parses a string as a command line flag.  The string should have
4370// the format "--flag=value".  When def_optional is true, the "=value"
4371// part can be omitted.
4372//
4373// Returns the value of the flag, or NULL if the parsing failed.
4374const char* ParseFlagValue(const char* str,
4375                           const char* flag,
4376                           bool def_optional) {
4377  // str and flag must not be NULL.
4378  if (str == NULL || flag == NULL) return NULL;
4379
4380  // The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
4381  const String flag_str = String::Format("--%s%s", GTEST_FLAG_PREFIX_, flag);
4382  const size_t flag_len = flag_str.length();
4383  if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;
4384
4385  // Skips the flag name.
4386  const char* flag_end = str + flag_len;
4387
4388  // When def_optional is true, it's OK to not have a "=value" part.
4389  if (def_optional && (flag_end[0] == '\0')) {
4390    return flag_end;
4391  }
4392
4393  // If def_optional is true and there are more characters after the
4394  // flag name, or if def_optional is false, there must be a '=' after
4395  // the flag name.
4396  if (flag_end[0] != '=') return NULL;
4397
4398  // Returns the string after "=".
4399  return flag_end + 1;
4400}
4401
4402// Parses a string for a bool flag, in the form of either
4403// "--flag=value" or "--flag".
4404//
4405// In the former case, the value is taken as true as long as it does
4406// not start with '0', 'f', or 'F'.
4407//
4408// In the latter case, the value is taken as true.
4409//
4410// On success, stores the value of the flag in *value, and returns
4411// true.  On failure, returns false without changing *value.
4412bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
4413  // Gets the value of the flag as a string.
4414  const char* const value_str = ParseFlagValue(str, flag, true);
4415
4416  // Aborts if the parsing failed.
4417  if (value_str == NULL) return false;
4418
4419  // Converts the string value to a bool.
4420  *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
4421  return true;
4422}
4423
4424// Parses a string for an Int32 flag, in the form of
4425// "--flag=value".
4426//
4427// On success, stores the value of the flag in *value, and returns
4428// true.  On failure, returns false without changing *value.
4429bool ParseInt32Flag(const char* str, const char* flag, Int32* value) {
4430  // Gets the value of the flag as a string.
4431  const char* const value_str = ParseFlagValue(str, flag, false);
4432
4433  // Aborts if the parsing failed.
4434  if (value_str == NULL) return false;
4435
4436  // Sets *value to the value of the flag.
4437  return ParseInt32(Message() << "The value of flag --" << flag,
4438                    value_str, value);
4439}
4440
4441// Parses a string for a string flag, in the form of
4442// "--flag=value".
4443//
4444// On success, stores the value of the flag in *value, and returns
4445// true.  On failure, returns false without changing *value.
4446bool ParseStringFlag(const char* str, const char* flag, String* value) {
4447  // Gets the value of the flag as a string.
4448  const char* const value_str = ParseFlagValue(str, flag, false);
4449
4450  // Aborts if the parsing failed.
4451  if (value_str == NULL) return false;
4452
4453  // Sets *value to the value of the flag.
4454  *value = value_str;
4455  return true;
4456}
4457
4458// Determines whether a string has a prefix that Google Test uses for its
4459// flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.
4460// If Google Test detects that a command line flag has its prefix but is not
4461// recognized, it will print its help message. Flags starting with
4462// GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
4463// internal flags and do not trigger the help message.
4464static bool HasGoogleTestFlagPrefix(const char* str) {
4465  return (SkipPrefix("--", &str) ||
4466          SkipPrefix("-", &str) ||
4467          SkipPrefix("/", &str)) &&
4468         !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
4469         (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
4470          SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str));
4471}
4472
4473// Prints a string containing code-encoded text.  The following escape
4474// sequences can be used in the string to control the text color:
4475//
4476//   @@    prints a single '@' character.
4477//   @R    changes the color to red.
4478//   @G    changes the color to green.
4479//   @Y    changes the color to yellow.
4480//   @D    changes to the default terminal text color.
4481//
4482// TODO(wan@google.com): Write tests for this once we add stdout
4483// capturing to Google Test.
4484static void PrintColorEncoded(const char* str) {
4485  GTestColor color = COLOR_DEFAULT;  // The current color.
4486
4487  // Conceptually, we split the string into segments divided by escape
4488  // sequences.  Then we print one segment at a time.  At the end of
4489  // each iteration, the str pointer advances to the beginning of the
4490  // next segment.
4491  for (;;) {
4492    const char* p = strchr(str, '@');
4493    if (p == NULL) {
4494      ColoredPrintf(color, "%s", str);
4495      return;
4496    }
4497
4498    ColoredPrintf(color, "%s", String(str, p - str).c_str());
4499
4500    const char ch = p[1];
4501    str = p + 2;
4502    if (ch == '@') {
4503      ColoredPrintf(color, "@");
4504    } else if (ch == 'D') {
4505      color = COLOR_DEFAULT;
4506    } else if (ch == 'R') {
4507      color = COLOR_RED;
4508    } else if (ch == 'G') {
4509      color = COLOR_GREEN;
4510    } else if (ch == 'Y') {
4511      color = COLOR_YELLOW;
4512    } else {
4513      --str;
4514    }
4515  }
4516}
4517
4518static const char kColorEncodedHelpMessage[] =
4519"This program contains tests written using " GTEST_NAME_ ". You can use the\n"
4520"following command line flags to control its behavior:\n"
4521"\n"
4522"Test Selection:\n"
4523"  @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n"
4524"      List the names of all tests instead of running them. The name of\n"
4525"      TEST(Foo, Bar) is \"Foo.Bar\".\n"
4526"  @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS"
4527    "[@G-@YNEGATIVE_PATTERNS]@D\n"
4528"      Run only the tests whose name matches one of the positive patterns but\n"
4529"      none of the negative patterns. '?' matches any single character; '*'\n"
4530"      matches any substring; ':' separates two patterns.\n"
4531"  @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n"
4532"      Run all disabled tests too.\n"
4533"\n"
4534"Test Execution:\n"
4535"  @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n"
4536"      Run the tests repeatedly; use a negative count to repeat forever.\n"
4537"  @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n"
4538"      Randomize tests' orders on every iteration.\n"
4539"  @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n"
4540"      Random number seed to use for shuffling test orders (between 1 and\n"
4541"      99999, or 0 to use a seed based on the current time).\n"
4542"\n"
4543"Test Output:\n"
4544"  @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
4545"      Enable/disable colored output. The default is @Gauto@D.\n"
4546"  -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n"
4547"      Don't print the elapsed time of each test.\n"
4548"  @G--" GTEST_FLAG_PREFIX_ "output=xml@Y[@G:@YDIRECTORY_PATH@G"
4549    GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n"
4550"      Generate an XML report in the given directory or with the given file\n"
4551"      name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n"
4552"\n"
4553"Assertion Behavior:\n"
4554#if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
4555"  @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
4556"      Set the default death test style.\n"
4557#endif  // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
4558"  @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n"
4559"      Turn assertion failures into debugger break-points.\n"
4560"  @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n"
4561"      Turn assertion failures into C++ exceptions.\n"
4562#if GTEST_OS_WINDOWS
4563"  @G--" GTEST_FLAG_PREFIX_ "catch_exceptions@D\n"
4564"      Suppress pop-ups caused by exceptions.\n"
4565#endif  // GTEST_OS_WINDOWS
4566"\n"
4567"Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set "
4568    "the corresponding\n"
4569"environment variable of a flag (all letters in upper-case). For example, to\n"
4570"disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_
4571    "color=no@D or set\n"
4572"the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n"
4573"\n"
4574"For more information, please read the " GTEST_NAME_ " documentation at\n"
4575"@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n"
4576"(not one in your own code or tests), please report it to\n"
4577"@G<" GTEST_DEV_EMAIL_ ">@D.\n";
4578
4579// Parses the command line for Google Test flags, without initializing
4580// other parts of Google Test.  The type parameter CharType can be
4581// instantiated to either char or wchar_t.
4582template <typename CharType>
4583void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
4584  for (int i = 1; i < *argc; i++) {
4585    const String arg_string = StreamableToString(argv[i]);
4586    const char* const arg = arg_string.c_str();
4587
4588    using internal::ParseBoolFlag;
4589    using internal::ParseInt32Flag;
4590    using internal::ParseStringFlag;
4591
4592    // Do we see a Google Test flag?
4593    if (ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,
4594                      &GTEST_FLAG(also_run_disabled_tests)) ||
4595        ParseBoolFlag(arg, kBreakOnFailureFlag,
4596                      &GTEST_FLAG(break_on_failure)) ||
4597        ParseBoolFlag(arg, kCatchExceptionsFlag,
4598                      &GTEST_FLAG(catch_exceptions)) ||
4599        ParseStringFlag(arg, kColorFlag, &GTEST_FLAG(color)) ||
4600        ParseStringFlag(arg, kDeathTestStyleFlag,
4601                        &GTEST_FLAG(death_test_style)) ||
4602        ParseBoolFlag(arg, kDeathTestUseFork,
4603                      &GTEST_FLAG(death_test_use_fork)) ||
4604        ParseStringFlag(arg, kFilterFlag, &GTEST_FLAG(filter)) ||
4605        ParseStringFlag(arg, kInternalRunDeathTestFlag,
4606                        &GTEST_FLAG(internal_run_death_test)) ||
4607        ParseBoolFlag(arg, kListTestsFlag, &GTEST_FLAG(list_tests)) ||
4608        ParseStringFlag(arg, kOutputFlag, &GTEST_FLAG(output)) ||
4609        ParseBoolFlag(arg, kPrintTimeFlag, &GTEST_FLAG(print_time)) ||
4610        ParseInt32Flag(arg, kRandomSeedFlag, &GTEST_FLAG(random_seed)) ||
4611        ParseInt32Flag(arg, kRepeatFlag, &GTEST_FLAG(repeat)) ||
4612        ParseBoolFlag(arg, kShuffleFlag, &GTEST_FLAG(shuffle)) ||
4613        ParseInt32Flag(arg, kStackTraceDepthFlag,
4614                       &GTEST_FLAG(stack_trace_depth)) ||
4615        ParseBoolFlag(arg, kThrowOnFailureFlag, &GTEST_FLAG(throw_on_failure))
4616        ) {
4617      // Yes.  Shift the remainder of the argv list left by one.  Note
4618      // that argv has (*argc + 1) elements, the last one always being
4619      // NULL.  The following loop moves the trailing NULL element as
4620      // well.
4621      for (int j = i; j != *argc; j++) {
4622        argv[j] = argv[j + 1];
4623      }
4624
4625      // Decrements the argument count.
4626      (*argc)--;
4627
4628      // We also need to decrement the iterator as we just removed
4629      // an element.
4630      i--;
4631    } else if (arg_string == "--help" || arg_string == "-h" ||
4632               arg_string == "-?" || arg_string == "/?" ||
4633               HasGoogleTestFlagPrefix(arg)) {
4634      // Both help flag and unrecognized Google Test flags (excluding
4635      // internal ones) trigger help display.
4636      g_help_flag = true;
4637    }
4638  }
4639
4640  if (g_help_flag) {
4641    // We print the help here instead of in RUN_ALL_TESTS(), as the
4642    // latter may not be called at all if the user is using Google
4643    // Test with another testing framework.
4644    PrintColorEncoded(kColorEncodedHelpMessage);
4645  }
4646}
4647
4648// Parses the command line for Google Test flags, without initializing
4649// other parts of Google Test.
4650void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
4651  ParseGoogleTestFlagsOnlyImpl(argc, argv);
4652}
4653void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {
4654  ParseGoogleTestFlagsOnlyImpl(argc, argv);
4655}
4656
4657// The internal implementation of InitGoogleTest().
4658//
4659// The type parameter CharType can be instantiated to either char or
4660// wchar_t.
4661template <typename CharType>
4662void InitGoogleTestImpl(int* argc, CharType** argv) {
4663  g_init_gtest_count++;
4664
4665  // We don't want to run the initialization code twice.
4666  if (g_init_gtest_count != 1) return;
4667
4668  if (*argc <= 0) return;
4669
4670  internal::g_executable_path = internal::StreamableToString(argv[0]);
4671
4672#if GTEST_HAS_DEATH_TEST
4673  g_argvs.clear();
4674  for (int i = 0; i != *argc; i++) {
4675    g_argvs.push_back(StreamableToString(argv[i]));
4676  }
4677#endif  // GTEST_HAS_DEATH_TEST
4678
4679  ParseGoogleTestFlagsOnly(argc, argv);
4680  GetUnitTestImpl()->PostFlagParsingInit();
4681}
4682
4683}  // namespace internal
4684
4685// Initializes Google Test.  This must be called before calling
4686// RUN_ALL_TESTS().  In particular, it parses a command line for the
4687// flags that Google Test recognizes.  Whenever a Google Test flag is
4688// seen, it is removed from argv, and *argc is decremented.
4689//
4690// No value is returned.  Instead, the Google Test flag variables are
4691// updated.
4692//
4693// Calling the function for the second time has no user-visible effect.
4694void InitGoogleTest(int* argc, char** argv) {
4695  internal::InitGoogleTestImpl(argc, argv);
4696}
4697
4698// This overloaded version can be used in Windows programs compiled in
4699// UNICODE mode.
4700void InitGoogleTest(int* argc, wchar_t** argv) {
4701  internal::InitGoogleTestImpl(argc, argv);
4702}
4703
4704}  // namespace testing
4705