106f32e7eSjoerg // Copyright 2005, Google Inc.
206f32e7eSjoerg // All rights reserved.
306f32e7eSjoerg //
406f32e7eSjoerg // Redistribution and use in source and binary forms, with or without
506f32e7eSjoerg // modification, are permitted provided that the following conditions are
606f32e7eSjoerg // met:
706f32e7eSjoerg //
806f32e7eSjoerg //     * Redistributions of source code must retain the above copyright
906f32e7eSjoerg // notice, this list of conditions and the following disclaimer.
1006f32e7eSjoerg //     * Redistributions in binary form must reproduce the above
1106f32e7eSjoerg // copyright notice, this list of conditions and the following disclaimer
1206f32e7eSjoerg // in the documentation and/or other materials provided with the
1306f32e7eSjoerg // distribution.
1406f32e7eSjoerg //     * Neither the name of Google Inc. nor the names of its
1506f32e7eSjoerg // contributors may be used to endorse or promote products derived from
1606f32e7eSjoerg // this software without specific prior written permission.
1706f32e7eSjoerg //
1806f32e7eSjoerg // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
1906f32e7eSjoerg // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
2006f32e7eSjoerg // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
2106f32e7eSjoerg // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
2206f32e7eSjoerg // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
2306f32e7eSjoerg // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
2406f32e7eSjoerg // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
2506f32e7eSjoerg // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
2606f32e7eSjoerg // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
2706f32e7eSjoerg // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2806f32e7eSjoerg // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29*da58b97aSjoerg 
3006f32e7eSjoerg //
31*da58b97aSjoerg // The Google C++ Testing and Mocking Framework (Google Test)
3206f32e7eSjoerg 
3306f32e7eSjoerg #include "gtest/gtest.h"
3406f32e7eSjoerg #include "gtest/internal/custom/gtest.h"
3506f32e7eSjoerg #include "gtest/gtest-spi.h"
3606f32e7eSjoerg 
3706f32e7eSjoerg #include <ctype.h>
3806f32e7eSjoerg #include <math.h>
3906f32e7eSjoerg #include <stdarg.h>
4006f32e7eSjoerg #include <stdio.h>
4106f32e7eSjoerg #include <stdlib.h>
4206f32e7eSjoerg #include <time.h>
4306f32e7eSjoerg #include <wchar.h>
4406f32e7eSjoerg #include <wctype.h>
4506f32e7eSjoerg 
4606f32e7eSjoerg #include <algorithm>
4706f32e7eSjoerg #include <iomanip>
4806f32e7eSjoerg #include <limits>
4906f32e7eSjoerg #include <list>
5006f32e7eSjoerg #include <map>
5106f32e7eSjoerg #include <ostream>  // NOLINT
5206f32e7eSjoerg #include <sstream>
5306f32e7eSjoerg #include <vector>
5406f32e7eSjoerg 
5506f32e7eSjoerg #if GTEST_OS_LINUX
5606f32e7eSjoerg 
5706f32e7eSjoerg # define GTEST_HAS_GETTIMEOFDAY_ 1
5806f32e7eSjoerg 
5906f32e7eSjoerg # include <fcntl.h>  // NOLINT
6006f32e7eSjoerg # include <limits.h>  // NOLINT
6106f32e7eSjoerg # include <sched.h>  // NOLINT
6206f32e7eSjoerg // Declares vsnprintf().  This header is not available on Windows.
6306f32e7eSjoerg # include <strings.h>  // NOLINT
6406f32e7eSjoerg # include <sys/mman.h>  // NOLINT
6506f32e7eSjoerg # include <sys/time.h>  // NOLINT
6606f32e7eSjoerg # include <unistd.h>  // NOLINT
6706f32e7eSjoerg # include <string>
6806f32e7eSjoerg 
6906f32e7eSjoerg #elif GTEST_OS_ZOS
7006f32e7eSjoerg # define GTEST_HAS_GETTIMEOFDAY_ 1
7106f32e7eSjoerg # include <sys/time.h>  // NOLINT
7206f32e7eSjoerg 
7306f32e7eSjoerg // On z/OS we additionally need strings.h for strcasecmp.
7406f32e7eSjoerg # include <strings.h>  // NOLINT
7506f32e7eSjoerg 
7606f32e7eSjoerg #elif GTEST_OS_WINDOWS_MOBILE  // We are on Windows CE.
7706f32e7eSjoerg 
7806f32e7eSjoerg # include <windows.h>  // NOLINT
7906f32e7eSjoerg # undef min
8006f32e7eSjoerg 
8106f32e7eSjoerg #elif GTEST_OS_WINDOWS  // We are on Windows proper.
8206f32e7eSjoerg 
83*da58b97aSjoerg # include <windows.h>  // NOLINT
84*da58b97aSjoerg # undef min
85*da58b97aSjoerg 
86*da58b97aSjoerg # include <crtdbg.h>  // NOLINT
87*da58b97aSjoerg # include <debugapi.h>  // NOLINT
8806f32e7eSjoerg # include <io.h>  // NOLINT
8906f32e7eSjoerg # include <sys/timeb.h>  // NOLINT
9006f32e7eSjoerg # include <sys/types.h>  // NOLINT
9106f32e7eSjoerg # include <sys/stat.h>  // NOLINT
9206f32e7eSjoerg 
9306f32e7eSjoerg # if GTEST_OS_WINDOWS_MINGW
9406f32e7eSjoerg // MinGW has gettimeofday() but not _ftime64().
9506f32e7eSjoerg #  define GTEST_HAS_GETTIMEOFDAY_ 1
9606f32e7eSjoerg #  include <sys/time.h>  // NOLINT
9706f32e7eSjoerg # endif  // GTEST_OS_WINDOWS_MINGW
9806f32e7eSjoerg 
9906f32e7eSjoerg #else
10006f32e7eSjoerg 
10106f32e7eSjoerg // Assume other platforms have gettimeofday().
10206f32e7eSjoerg # define GTEST_HAS_GETTIMEOFDAY_ 1
10306f32e7eSjoerg 
10406f32e7eSjoerg // cpplint thinks that the header is already included, so we want to
10506f32e7eSjoerg // silence it.
10606f32e7eSjoerg # include <sys/time.h>  // NOLINT
10706f32e7eSjoerg # include <unistd.h>  // NOLINT
10806f32e7eSjoerg 
10906f32e7eSjoerg #endif  // GTEST_OS_LINUX
11006f32e7eSjoerg 
11106f32e7eSjoerg #if GTEST_HAS_EXCEPTIONS
11206f32e7eSjoerg # include <stdexcept>
11306f32e7eSjoerg #endif
11406f32e7eSjoerg 
11506f32e7eSjoerg #if GTEST_CAN_STREAM_RESULTS_
11606f32e7eSjoerg # include <arpa/inet.h>  // NOLINT
11706f32e7eSjoerg # include <netdb.h>  // NOLINT
11806f32e7eSjoerg # include <sys/socket.h>  // NOLINT
11906f32e7eSjoerg # include <sys/types.h>  // NOLINT
12006f32e7eSjoerg #endif
12106f32e7eSjoerg 
12206f32e7eSjoerg #include "src/gtest-internal-inl.h"
12306f32e7eSjoerg 
12406f32e7eSjoerg #if GTEST_OS_WINDOWS
12506f32e7eSjoerg # define vsnprintf _vsnprintf
12606f32e7eSjoerg #endif  // GTEST_OS_WINDOWS
12706f32e7eSjoerg 
128*da58b97aSjoerg #if GTEST_OS_MAC
129*da58b97aSjoerg #ifndef GTEST_OS_IOS
130*da58b97aSjoerg #include <crt_externs.h>
131*da58b97aSjoerg #endif
132*da58b97aSjoerg #endif
133*da58b97aSjoerg 
134*da58b97aSjoerg #if GTEST_HAS_ABSL
135*da58b97aSjoerg #include "absl/debugging/failure_signal_handler.h"
136*da58b97aSjoerg #include "absl/debugging/stacktrace.h"
137*da58b97aSjoerg #include "absl/debugging/symbolize.h"
138*da58b97aSjoerg #include "absl/strings/str_cat.h"
139*da58b97aSjoerg #endif  // GTEST_HAS_ABSL
140*da58b97aSjoerg 
14106f32e7eSjoerg namespace testing {
14206f32e7eSjoerg 
14306f32e7eSjoerg using internal::CountIf;
14406f32e7eSjoerg using internal::ForEach;
14506f32e7eSjoerg using internal::GetElementOr;
14606f32e7eSjoerg using internal::Shuffle;
14706f32e7eSjoerg 
14806f32e7eSjoerg // Constants.
14906f32e7eSjoerg 
150*da58b97aSjoerg // A test whose test suite name or test name matches this filter is
15106f32e7eSjoerg // disabled and not run.
15206f32e7eSjoerg static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
15306f32e7eSjoerg 
154*da58b97aSjoerg // A test suite whose name matches this filter is considered a death
155*da58b97aSjoerg // test suite and will be run before test suites whose name doesn't
15606f32e7eSjoerg // match this filter.
157*da58b97aSjoerg static const char kDeathTestSuiteFilter[] = "*DeathTest:*DeathTest/*";
15806f32e7eSjoerg 
15906f32e7eSjoerg // A test filter that matches everything.
16006f32e7eSjoerg static const char kUniversalFilter[] = "*";
16106f32e7eSjoerg 
162*da58b97aSjoerg // The default output format.
163*da58b97aSjoerg static const char kDefaultOutputFormat[] = "xml";
164*da58b97aSjoerg // The default output file.
165*da58b97aSjoerg static const char kDefaultOutputFile[] = "test_detail";
16606f32e7eSjoerg 
16706f32e7eSjoerg // The environment variable name for the test shard index.
16806f32e7eSjoerg static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
16906f32e7eSjoerg // The environment variable name for the total number of test shards.
17006f32e7eSjoerg static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
17106f32e7eSjoerg // The environment variable name for the test shard status file.
17206f32e7eSjoerg static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
17306f32e7eSjoerg 
17406f32e7eSjoerg namespace internal {
17506f32e7eSjoerg 
17606f32e7eSjoerg // The text used in failure messages to indicate the start of the
17706f32e7eSjoerg // stack trace.
17806f32e7eSjoerg const char kStackTraceMarker[] = "\nStack trace:\n";
17906f32e7eSjoerg 
180*da58b97aSjoerg // g_help_flag is true if and only if the --help flag or an equivalent form
181*da58b97aSjoerg // is specified on the command line.
18206f32e7eSjoerg bool g_help_flag = false;
18306f32e7eSjoerg 
184*da58b97aSjoerg // Utilty function to Open File for Writing
OpenFileForWriting(const std::string & output_file)185*da58b97aSjoerg static FILE* OpenFileForWriting(const std::string& output_file) {
186*da58b97aSjoerg   FILE* fileout = nullptr;
187*da58b97aSjoerg   FilePath output_file_path(output_file);
188*da58b97aSjoerg   FilePath output_dir(output_file_path.RemoveFileName());
189*da58b97aSjoerg 
190*da58b97aSjoerg   if (output_dir.CreateDirectoriesRecursively()) {
191*da58b97aSjoerg     fileout = posix::FOpen(output_file.c_str(), "w");
192*da58b97aSjoerg   }
193*da58b97aSjoerg   if (fileout == nullptr) {
194*da58b97aSjoerg     GTEST_LOG_(FATAL) << "Unable to open file \"" << output_file << "\"";
195*da58b97aSjoerg   }
196*da58b97aSjoerg   return fileout;
197*da58b97aSjoerg }
198*da58b97aSjoerg 
19906f32e7eSjoerg }  // namespace internal
20006f32e7eSjoerg 
201*da58b97aSjoerg // Bazel passes in the argument to '--test_filter' via the TESTBRIDGE_TEST_ONLY
202*da58b97aSjoerg // environment variable.
GetDefaultFilter()20306f32e7eSjoerg static const char* GetDefaultFilter() {
204*da58b97aSjoerg   const char* const testbridge_test_only =
205*da58b97aSjoerg       internal::posix::GetEnv("TESTBRIDGE_TEST_ONLY");
206*da58b97aSjoerg   if (testbridge_test_only != nullptr) {
20706f32e7eSjoerg     return testbridge_test_only;
20806f32e7eSjoerg   }
20906f32e7eSjoerg   return kUniversalFilter;
21006f32e7eSjoerg }
21106f32e7eSjoerg 
21206f32e7eSjoerg GTEST_DEFINE_bool_(
21306f32e7eSjoerg     also_run_disabled_tests,
21406f32e7eSjoerg     internal::BoolFromGTestEnv("also_run_disabled_tests", false),
21506f32e7eSjoerg     "Run disabled tests too, in addition to the tests normally being run.");
21606f32e7eSjoerg 
21706f32e7eSjoerg GTEST_DEFINE_bool_(
218*da58b97aSjoerg     break_on_failure, internal::BoolFromGTestEnv("break_on_failure", false),
219*da58b97aSjoerg     "True if and only if a failed assertion should be a debugger "
220*da58b97aSjoerg     "break-point.");
22106f32e7eSjoerg 
222*da58b97aSjoerg GTEST_DEFINE_bool_(catch_exceptions,
22306f32e7eSjoerg                    internal::BoolFromGTestEnv("catch_exceptions", true),
224*da58b97aSjoerg                    "True if and only if " GTEST_NAME_
22506f32e7eSjoerg                    " should catch exceptions and treat them as test failures.");
22606f32e7eSjoerg 
22706f32e7eSjoerg GTEST_DEFINE_string_(
22806f32e7eSjoerg     color,
22906f32e7eSjoerg     internal::StringFromGTestEnv("color", "auto"),
23006f32e7eSjoerg     "Whether to use colors in the output.  Valid values: yes, no, "
23106f32e7eSjoerg     "and auto.  'auto' means to use colors if the output is "
23206f32e7eSjoerg     "being sent to a terminal and the TERM environment variable "
23306f32e7eSjoerg     "is set to a terminal type that supports colors.");
23406f32e7eSjoerg 
23506f32e7eSjoerg GTEST_DEFINE_string_(
23606f32e7eSjoerg     filter,
23706f32e7eSjoerg     internal::StringFromGTestEnv("filter", GetDefaultFilter()),
23806f32e7eSjoerg     "A colon-separated list of glob (not regex) patterns "
23906f32e7eSjoerg     "for filtering the tests to run, optionally followed by a "
24006f32e7eSjoerg     "'-' and a : separated list of negative patterns (tests to "
24106f32e7eSjoerg     "exclude).  A test is run if it matches one of the positive "
24206f32e7eSjoerg     "patterns and does not match any of the negative patterns.");
24306f32e7eSjoerg 
244*da58b97aSjoerg GTEST_DEFINE_bool_(
245*da58b97aSjoerg     install_failure_signal_handler,
246*da58b97aSjoerg     internal::BoolFromGTestEnv("install_failure_signal_handler", false),
247*da58b97aSjoerg     "If true and supported on the current platform, " GTEST_NAME_ " should "
248*da58b97aSjoerg     "install a signal handler that dumps debugging information when fatal "
249*da58b97aSjoerg     "signals are raised.");
250*da58b97aSjoerg 
25106f32e7eSjoerg GTEST_DEFINE_bool_(list_tests, false,
25206f32e7eSjoerg                    "List all tests without running them.");
25306f32e7eSjoerg 
254*da58b97aSjoerg // The net priority order after flag processing is thus:
255*da58b97aSjoerg //   --gtest_output command line flag
256*da58b97aSjoerg //   GTEST_OUTPUT environment variable
257*da58b97aSjoerg //   XML_OUTPUT_FILE environment variable
258*da58b97aSjoerg //   ''
25906f32e7eSjoerg GTEST_DEFINE_string_(
26006f32e7eSjoerg     output,
261*da58b97aSjoerg     internal::StringFromGTestEnv("output",
262*da58b97aSjoerg       internal::OutputFlagAlsoCheckEnvVar().c_str()),
263*da58b97aSjoerg     "A format (defaults to \"xml\" but can be specified to be \"json\"), "
264*da58b97aSjoerg     "optionally followed by a colon and an output file name or directory. "
265*da58b97aSjoerg     "A directory is indicated by a trailing pathname separator. "
26606f32e7eSjoerg     "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
26706f32e7eSjoerg     "If a directory is specified, output files will be created "
26806f32e7eSjoerg     "within that directory, with file-names based on the test "
26906f32e7eSjoerg     "executable's name and, if necessary, made unique by adding "
27006f32e7eSjoerg     "digits.");
27106f32e7eSjoerg 
272*da58b97aSjoerg GTEST_DEFINE_bool_(print_time, internal::BoolFromGTestEnv("print_time", true),
273*da58b97aSjoerg                    "True if and only if " GTEST_NAME_
27406f32e7eSjoerg                    " should display elapsed time in text output.");
27506f32e7eSjoerg 
276*da58b97aSjoerg GTEST_DEFINE_bool_(print_utf8, internal::BoolFromGTestEnv("print_utf8", true),
277*da58b97aSjoerg                    "True if and only if " GTEST_NAME_
278*da58b97aSjoerg                    " prints UTF8 characters as text.");
279*da58b97aSjoerg 
28006f32e7eSjoerg GTEST_DEFINE_int32_(
28106f32e7eSjoerg     random_seed,
28206f32e7eSjoerg     internal::Int32FromGTestEnv("random_seed", 0),
28306f32e7eSjoerg     "Random number seed to use when shuffling test orders.  Must be in range "
28406f32e7eSjoerg     "[1, 99999], or 0 to use a seed based on the current time.");
28506f32e7eSjoerg 
28606f32e7eSjoerg GTEST_DEFINE_int32_(
28706f32e7eSjoerg     repeat,
28806f32e7eSjoerg     internal::Int32FromGTestEnv("repeat", 1),
28906f32e7eSjoerg     "How many times to repeat each test.  Specify a negative number "
29006f32e7eSjoerg     "for repeating forever.  Useful for shaking out flaky tests.");
29106f32e7eSjoerg 
292*da58b97aSjoerg GTEST_DEFINE_bool_(show_internal_stack_frames, false,
293*da58b97aSjoerg                    "True if and only if " GTEST_NAME_
294*da58b97aSjoerg                    " should include internal stack frames when "
29506f32e7eSjoerg                    "printing test failure stack traces.");
29606f32e7eSjoerg 
297*da58b97aSjoerg GTEST_DEFINE_bool_(shuffle, internal::BoolFromGTestEnv("shuffle", false),
298*da58b97aSjoerg                    "True if and only if " GTEST_NAME_
29906f32e7eSjoerg                    " should randomize tests' order on every run.");
30006f32e7eSjoerg 
30106f32e7eSjoerg GTEST_DEFINE_int32_(
30206f32e7eSjoerg     stack_trace_depth,
30306f32e7eSjoerg     internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
30406f32e7eSjoerg     "The maximum number of stack frames to print when an "
30506f32e7eSjoerg     "assertion fails.  The valid range is 0 through 100, inclusive.");
30606f32e7eSjoerg 
30706f32e7eSjoerg GTEST_DEFINE_string_(
30806f32e7eSjoerg     stream_result_to,
30906f32e7eSjoerg     internal::StringFromGTestEnv("stream_result_to", ""),
31006f32e7eSjoerg     "This flag specifies the host name and the port number on which to stream "
31106f32e7eSjoerg     "test results. Example: \"localhost:555\". The flag is effective only on "
31206f32e7eSjoerg     "Linux.");
31306f32e7eSjoerg 
31406f32e7eSjoerg GTEST_DEFINE_bool_(
31506f32e7eSjoerg     throw_on_failure,
31606f32e7eSjoerg     internal::BoolFromGTestEnv("throw_on_failure", false),
31706f32e7eSjoerg     "When this flag is specified, a failed assertion will throw an exception "
31806f32e7eSjoerg     "if exceptions are enabled or exit the program with a non-zero code "
319*da58b97aSjoerg     "otherwise. For use with an external test framework.");
32006f32e7eSjoerg 
32106f32e7eSjoerg #if GTEST_USE_OWN_FLAGFILE_FLAG_
32206f32e7eSjoerg GTEST_DEFINE_string_(
32306f32e7eSjoerg     flagfile,
32406f32e7eSjoerg     internal::StringFromGTestEnv("flagfile", ""),
32506f32e7eSjoerg     "This flag specifies the flagfile to read command-line flags from.");
32606f32e7eSjoerg #endif  // GTEST_USE_OWN_FLAGFILE_FLAG_
32706f32e7eSjoerg 
32806f32e7eSjoerg namespace internal {
32906f32e7eSjoerg 
33006f32e7eSjoerg // Generates a random number from [0, range), using a Linear
33106f32e7eSjoerg // Congruential Generator (LCG).  Crashes if 'range' is 0 or greater
33206f32e7eSjoerg // than kMaxRange.
Generate(UInt32 range)33306f32e7eSjoerg UInt32 Random::Generate(UInt32 range) {
33406f32e7eSjoerg   // These constants are the same as are used in glibc's rand(3).
335*da58b97aSjoerg   // Use wider types than necessary to prevent unsigned overflow diagnostics.
336*da58b97aSjoerg   state_ = static_cast<UInt32>(1103515245ULL*state_ + 12345U) % kMaxRange;
33706f32e7eSjoerg 
33806f32e7eSjoerg   GTEST_CHECK_(range > 0)
33906f32e7eSjoerg       << "Cannot generate a number in the range [0, 0).";
34006f32e7eSjoerg   GTEST_CHECK_(range <= kMaxRange)
34106f32e7eSjoerg       << "Generation of a number in [0, " << range << ") was requested, "
34206f32e7eSjoerg       << "but this can only generate numbers in [0, " << kMaxRange << ").";
34306f32e7eSjoerg 
34406f32e7eSjoerg   // Converting via modulus introduces a bit of downward bias, but
34506f32e7eSjoerg   // it's simple, and a linear congruential generator isn't too good
34606f32e7eSjoerg   // to begin with.
34706f32e7eSjoerg   return state_ % range;
34806f32e7eSjoerg }
34906f32e7eSjoerg 
350*da58b97aSjoerg // GTestIsInitialized() returns true if and only if the user has initialized
35106f32e7eSjoerg // Google Test.  Useful for catching the user mistake of not initializing
35206f32e7eSjoerg // Google Test before calling RUN_ALL_TESTS().
GTestIsInitialized()35306f32e7eSjoerg static bool GTestIsInitialized() { return GetArgvs().size() > 0; }
35406f32e7eSjoerg 
355*da58b97aSjoerg // Iterates over a vector of TestSuites, keeping a running sum of the
35606f32e7eSjoerg // results of calling a given int-returning method on each.
35706f32e7eSjoerg // Returns the sum.
SumOverTestSuiteList(const std::vector<TestSuite * > & case_list,int (TestSuite::* method)()const)358*da58b97aSjoerg static int SumOverTestSuiteList(const std::vector<TestSuite*>& case_list,
359*da58b97aSjoerg                                 int (TestSuite::*method)() const) {
36006f32e7eSjoerg   int sum = 0;
36106f32e7eSjoerg   for (size_t i = 0; i < case_list.size(); i++) {
36206f32e7eSjoerg     sum += (case_list[i]->*method)();
36306f32e7eSjoerg   }
36406f32e7eSjoerg   return sum;
36506f32e7eSjoerg }
36606f32e7eSjoerg 
367*da58b97aSjoerg // Returns true if and only if the test suite passed.
TestSuitePassed(const TestSuite * test_suite)368*da58b97aSjoerg static bool TestSuitePassed(const TestSuite* test_suite) {
369*da58b97aSjoerg   return test_suite->should_run() && test_suite->Passed();
37006f32e7eSjoerg }
37106f32e7eSjoerg 
372*da58b97aSjoerg // Returns true if and only if the test suite failed.
TestSuiteFailed(const TestSuite * test_suite)373*da58b97aSjoerg static bool TestSuiteFailed(const TestSuite* test_suite) {
374*da58b97aSjoerg   return test_suite->should_run() && test_suite->Failed();
37506f32e7eSjoerg }
37606f32e7eSjoerg 
377*da58b97aSjoerg // Returns true if and only if test_suite contains at least one test that
378*da58b97aSjoerg // should run.
ShouldRunTestSuite(const TestSuite * test_suite)379*da58b97aSjoerg static bool ShouldRunTestSuite(const TestSuite* test_suite) {
380*da58b97aSjoerg   return test_suite->should_run();
38106f32e7eSjoerg }
38206f32e7eSjoerg 
38306f32e7eSjoerg // AssertHelper constructor.
AssertHelper(TestPartResult::Type type,const char * file,int line,const char * message)38406f32e7eSjoerg AssertHelper::AssertHelper(TestPartResult::Type type,
38506f32e7eSjoerg                            const char* file,
38606f32e7eSjoerg                            int line,
38706f32e7eSjoerg                            const char* message)
38806f32e7eSjoerg     : data_(new AssertHelperData(type, file, line, message)) {
38906f32e7eSjoerg }
39006f32e7eSjoerg 
~AssertHelper()39106f32e7eSjoerg AssertHelper::~AssertHelper() {
39206f32e7eSjoerg   delete data_;
39306f32e7eSjoerg }
39406f32e7eSjoerg 
39506f32e7eSjoerg // Message assignment, for assertion streaming support.
operator =(const Message & message) const39606f32e7eSjoerg void AssertHelper::operator=(const Message& message) const {
39706f32e7eSjoerg   UnitTest::GetInstance()->
39806f32e7eSjoerg     AddTestPartResult(data_->type, data_->file, data_->line,
39906f32e7eSjoerg                       AppendUserMessage(data_->message, message),
40006f32e7eSjoerg                       UnitTest::GetInstance()->impl()
40106f32e7eSjoerg                       ->CurrentOsStackTraceExceptTop(1)
40206f32e7eSjoerg                       // Skips the stack frame for this function itself.
40306f32e7eSjoerg                       );  // NOLINT
40406f32e7eSjoerg }
40506f32e7eSjoerg 
40606f32e7eSjoerg // A copy of all command line arguments.  Set by InitGoogleTest().
407*da58b97aSjoerg static ::std::vector<std::string> g_argvs;
40806f32e7eSjoerg 
GetArgvs()409*da58b97aSjoerg ::std::vector<std::string> GetArgvs() {
41006f32e7eSjoerg #if defined(GTEST_CUSTOM_GET_ARGVS_)
411*da58b97aSjoerg   // GTEST_CUSTOM_GET_ARGVS_() may return a container of std::string or
412*da58b97aSjoerg   // ::string. This code converts it to the appropriate type.
413*da58b97aSjoerg   const auto& custom = GTEST_CUSTOM_GET_ARGVS_();
414*da58b97aSjoerg   return ::std::vector<std::string>(custom.begin(), custom.end());
41506f32e7eSjoerg #else   // defined(GTEST_CUSTOM_GET_ARGVS_)
41606f32e7eSjoerg   return g_argvs;
41706f32e7eSjoerg #endif  // defined(GTEST_CUSTOM_GET_ARGVS_)
41806f32e7eSjoerg }
41906f32e7eSjoerg 
42006f32e7eSjoerg // Returns the current application's name, removing directory path if that
42106f32e7eSjoerg // is present.
GetCurrentExecutableName()42206f32e7eSjoerg FilePath GetCurrentExecutableName() {
42306f32e7eSjoerg   FilePath result;
42406f32e7eSjoerg 
425*da58b97aSjoerg #if GTEST_OS_WINDOWS || GTEST_OS_OS2
42606f32e7eSjoerg   result.Set(FilePath(GetArgvs()[0]).RemoveExtension("exe"));
42706f32e7eSjoerg #else
42806f32e7eSjoerg   result.Set(FilePath(GetArgvs()[0]));
42906f32e7eSjoerg #endif  // GTEST_OS_WINDOWS
43006f32e7eSjoerg 
43106f32e7eSjoerg   return result.RemoveDirectoryName();
43206f32e7eSjoerg }
43306f32e7eSjoerg 
43406f32e7eSjoerg // Functions for processing the gtest_output flag.
43506f32e7eSjoerg 
43606f32e7eSjoerg // Returns the output format, or "" for normal printed output.
GetOutputFormat()43706f32e7eSjoerg std::string UnitTestOptions::GetOutputFormat() {
43806f32e7eSjoerg   const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
43906f32e7eSjoerg   const char* const colon = strchr(gtest_output_flag, ':');
440*da58b97aSjoerg   return (colon == nullptr)
441*da58b97aSjoerg              ? std::string(gtest_output_flag)
442*da58b97aSjoerg              : std::string(gtest_output_flag,
443*da58b97aSjoerg                            static_cast<size_t>(colon - gtest_output_flag));
44406f32e7eSjoerg }
44506f32e7eSjoerg 
44606f32e7eSjoerg // Returns the name of the requested output file, or the default if none
44706f32e7eSjoerg // was explicitly specified.
GetAbsolutePathToOutputFile()44806f32e7eSjoerg std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
44906f32e7eSjoerg   const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
450*da58b97aSjoerg 
451*da58b97aSjoerg   std::string format = GetOutputFormat();
452*da58b97aSjoerg   if (format.empty())
453*da58b97aSjoerg     format = std::string(kDefaultOutputFormat);
45406f32e7eSjoerg 
45506f32e7eSjoerg   const char* const colon = strchr(gtest_output_flag, ':');
456*da58b97aSjoerg   if (colon == nullptr)
457*da58b97aSjoerg     return internal::FilePath::MakeFileName(
45806f32e7eSjoerg         internal::FilePath(
45906f32e7eSjoerg             UnitTest::GetInstance()->original_working_dir()),
460*da58b97aSjoerg         internal::FilePath(kDefaultOutputFile), 0,
461*da58b97aSjoerg         format.c_str()).string();
46206f32e7eSjoerg 
46306f32e7eSjoerg   internal::FilePath output_name(colon + 1);
46406f32e7eSjoerg   if (!output_name.IsAbsolutePath())
46506f32e7eSjoerg     output_name = internal::FilePath::ConcatPaths(
46606f32e7eSjoerg         internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
46706f32e7eSjoerg         internal::FilePath(colon + 1));
46806f32e7eSjoerg 
46906f32e7eSjoerg   if (!output_name.IsDirectory())
47006f32e7eSjoerg     return output_name.string();
47106f32e7eSjoerg 
47206f32e7eSjoerg   internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
47306f32e7eSjoerg       output_name, internal::GetCurrentExecutableName(),
47406f32e7eSjoerg       GetOutputFormat().c_str()));
47506f32e7eSjoerg   return result.string();
47606f32e7eSjoerg }
47706f32e7eSjoerg 
478*da58b97aSjoerg // Returns true if and only if the wildcard pattern matches the string.
479*da58b97aSjoerg // The first ':' or '\0' character in pattern marks the end of it.
48006f32e7eSjoerg //
48106f32e7eSjoerg // This recursive algorithm isn't very efficient, but is clear and
48206f32e7eSjoerg // works well enough for matching test names, which are short.
PatternMatchesString(const char * pattern,const char * str)48306f32e7eSjoerg bool UnitTestOptions::PatternMatchesString(const char *pattern,
48406f32e7eSjoerg                                            const char *str) {
48506f32e7eSjoerg   switch (*pattern) {
48606f32e7eSjoerg     case '\0':
48706f32e7eSjoerg     case ':':  // Either ':' or '\0' marks the end of the pattern.
48806f32e7eSjoerg       return *str == '\0';
48906f32e7eSjoerg     case '?':  // Matches any single character.
49006f32e7eSjoerg       return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);
49106f32e7eSjoerg     case '*':  // Matches any string (possibly empty) of characters.
49206f32e7eSjoerg       return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||
49306f32e7eSjoerg           PatternMatchesString(pattern + 1, str);
49406f32e7eSjoerg     default:  // Non-special character.  Matches itself.
49506f32e7eSjoerg       return *pattern == *str &&
49606f32e7eSjoerg           PatternMatchesString(pattern + 1, str + 1);
49706f32e7eSjoerg   }
49806f32e7eSjoerg }
49906f32e7eSjoerg 
MatchesFilter(const std::string & name,const char * filter)50006f32e7eSjoerg bool UnitTestOptions::MatchesFilter(
50106f32e7eSjoerg     const std::string& name, const char* filter) {
50206f32e7eSjoerg   const char *cur_pattern = filter;
50306f32e7eSjoerg   for (;;) {
50406f32e7eSjoerg     if (PatternMatchesString(cur_pattern, name.c_str())) {
50506f32e7eSjoerg       return true;
50606f32e7eSjoerg     }
50706f32e7eSjoerg 
50806f32e7eSjoerg     // Finds the next pattern in the filter.
50906f32e7eSjoerg     cur_pattern = strchr(cur_pattern, ':');
51006f32e7eSjoerg 
51106f32e7eSjoerg     // Returns if no more pattern can be found.
512*da58b97aSjoerg     if (cur_pattern == nullptr) {
51306f32e7eSjoerg       return false;
51406f32e7eSjoerg     }
51506f32e7eSjoerg 
51606f32e7eSjoerg     // Skips the pattern separater (the ':' character).
51706f32e7eSjoerg     cur_pattern++;
51806f32e7eSjoerg   }
51906f32e7eSjoerg }
52006f32e7eSjoerg 
521*da58b97aSjoerg // Returns true if and only if the user-specified filter matches the test
522*da58b97aSjoerg // suite name and the test name.
FilterMatchesTest(const std::string & test_suite_name,const std::string & test_name)523*da58b97aSjoerg bool UnitTestOptions::FilterMatchesTest(const std::string& test_suite_name,
52406f32e7eSjoerg                                         const std::string& test_name) {
525*da58b97aSjoerg   const std::string& full_name = test_suite_name + "." + test_name.c_str();
52606f32e7eSjoerg 
52706f32e7eSjoerg   // Split --gtest_filter at '-', if there is one, to separate into
52806f32e7eSjoerg   // positive filter and negative filter portions
52906f32e7eSjoerg   const char* const p = GTEST_FLAG(filter).c_str();
53006f32e7eSjoerg   const char* const dash = strchr(p, '-');
53106f32e7eSjoerg   std::string positive;
53206f32e7eSjoerg   std::string negative;
533*da58b97aSjoerg   if (dash == nullptr) {
53406f32e7eSjoerg     positive = GTEST_FLAG(filter).c_str();  // Whole string is a positive filter
53506f32e7eSjoerg     negative = "";
53606f32e7eSjoerg   } else {
53706f32e7eSjoerg     positive = std::string(p, dash);   // Everything up to the dash
53806f32e7eSjoerg     negative = std::string(dash + 1);  // Everything after the dash
53906f32e7eSjoerg     if (positive.empty()) {
54006f32e7eSjoerg       // Treat '-test1' as the same as '*-test1'
54106f32e7eSjoerg       positive = kUniversalFilter;
54206f32e7eSjoerg     }
54306f32e7eSjoerg   }
54406f32e7eSjoerg 
54506f32e7eSjoerg   // A filter is a colon-separated list of patterns.  It matches a
54606f32e7eSjoerg   // test if any pattern in it matches the test.
54706f32e7eSjoerg   return (MatchesFilter(full_name, positive.c_str()) &&
54806f32e7eSjoerg           !MatchesFilter(full_name, negative.c_str()));
54906f32e7eSjoerg }
55006f32e7eSjoerg 
55106f32e7eSjoerg #if GTEST_HAS_SEH
55206f32e7eSjoerg // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
55306f32e7eSjoerg // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
55406f32e7eSjoerg // This function is useful as an __except condition.
GTestShouldProcessSEH(DWORD exception_code)55506f32e7eSjoerg int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
55606f32e7eSjoerg   // Google Test should handle a SEH exception if:
55706f32e7eSjoerg   //   1. the user wants it to, AND
55806f32e7eSjoerg   //   2. this is not a breakpoint exception, AND
55906f32e7eSjoerg   //   3. this is not a C++ exception (VC++ implements them via SEH,
56006f32e7eSjoerg   //      apparently).
56106f32e7eSjoerg   //
56206f32e7eSjoerg   // SEH exception code for C++ exceptions.
56306f32e7eSjoerg   // (see http://support.microsoft.com/kb/185294 for more information).
56406f32e7eSjoerg   const DWORD kCxxExceptionCode = 0xe06d7363;
56506f32e7eSjoerg 
56606f32e7eSjoerg   bool should_handle = true;
56706f32e7eSjoerg 
56806f32e7eSjoerg   if (!GTEST_FLAG(catch_exceptions))
56906f32e7eSjoerg     should_handle = false;
57006f32e7eSjoerg   else if (exception_code == EXCEPTION_BREAKPOINT)
57106f32e7eSjoerg     should_handle = false;
57206f32e7eSjoerg   else if (exception_code == kCxxExceptionCode)
57306f32e7eSjoerg     should_handle = false;
57406f32e7eSjoerg 
57506f32e7eSjoerg   return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
57606f32e7eSjoerg }
57706f32e7eSjoerg #endif  // GTEST_HAS_SEH
57806f32e7eSjoerg 
57906f32e7eSjoerg }  // namespace internal
58006f32e7eSjoerg 
58106f32e7eSjoerg // The c'tor sets this object as the test part result reporter used by
58206f32e7eSjoerg // Google Test.  The 'result' parameter specifies where to report the
58306f32e7eSjoerg // results. Intercepts only failures from the current thread.
ScopedFakeTestPartResultReporter(TestPartResultArray * result)58406f32e7eSjoerg ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
58506f32e7eSjoerg     TestPartResultArray* result)
58606f32e7eSjoerg     : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
58706f32e7eSjoerg       result_(result) {
58806f32e7eSjoerg   Init();
58906f32e7eSjoerg }
59006f32e7eSjoerg 
59106f32e7eSjoerg // The c'tor sets this object as the test part result reporter used by
59206f32e7eSjoerg // Google Test.  The 'result' parameter specifies where to report the
59306f32e7eSjoerg // results.
ScopedFakeTestPartResultReporter(InterceptMode intercept_mode,TestPartResultArray * result)59406f32e7eSjoerg ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
59506f32e7eSjoerg     InterceptMode intercept_mode, TestPartResultArray* result)
59606f32e7eSjoerg     : intercept_mode_(intercept_mode),
59706f32e7eSjoerg       result_(result) {
59806f32e7eSjoerg   Init();
59906f32e7eSjoerg }
60006f32e7eSjoerg 
Init()60106f32e7eSjoerg void ScopedFakeTestPartResultReporter::Init() {
60206f32e7eSjoerg   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
60306f32e7eSjoerg   if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
60406f32e7eSjoerg     old_reporter_ = impl->GetGlobalTestPartResultReporter();
60506f32e7eSjoerg     impl->SetGlobalTestPartResultReporter(this);
60606f32e7eSjoerg   } else {
60706f32e7eSjoerg     old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
60806f32e7eSjoerg     impl->SetTestPartResultReporterForCurrentThread(this);
60906f32e7eSjoerg   }
61006f32e7eSjoerg }
61106f32e7eSjoerg 
61206f32e7eSjoerg // The d'tor restores the test part result reporter used by Google Test
61306f32e7eSjoerg // before.
~ScopedFakeTestPartResultReporter()61406f32e7eSjoerg ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
61506f32e7eSjoerg   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
61606f32e7eSjoerg   if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
61706f32e7eSjoerg     impl->SetGlobalTestPartResultReporter(old_reporter_);
61806f32e7eSjoerg   } else {
61906f32e7eSjoerg     impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
62006f32e7eSjoerg   }
62106f32e7eSjoerg }
62206f32e7eSjoerg 
62306f32e7eSjoerg // Increments the test part result count and remembers the result.
62406f32e7eSjoerg // This method is from the TestPartResultReporterInterface interface.
ReportTestPartResult(const TestPartResult & result)62506f32e7eSjoerg void ScopedFakeTestPartResultReporter::ReportTestPartResult(
62606f32e7eSjoerg     const TestPartResult& result) {
62706f32e7eSjoerg   result_->Append(result);
62806f32e7eSjoerg }
62906f32e7eSjoerg 
63006f32e7eSjoerg namespace internal {
63106f32e7eSjoerg 
63206f32e7eSjoerg // Returns the type ID of ::testing::Test.  We should always call this
63306f32e7eSjoerg // instead of GetTypeId< ::testing::Test>() to get the type ID of
63406f32e7eSjoerg // testing::Test.  This is to work around a suspected linker bug when
63506f32e7eSjoerg // using Google Test as a framework on Mac OS X.  The bug causes
63606f32e7eSjoerg // GetTypeId< ::testing::Test>() to return different values depending
63706f32e7eSjoerg // on whether the call is from the Google Test framework itself or
63806f32e7eSjoerg // from user test code.  GetTestTypeId() is guaranteed to always
63906f32e7eSjoerg // return the same value, as it always calls GetTypeId<>() from the
64006f32e7eSjoerg // gtest.cc, which is within the Google Test framework.
GetTestTypeId()64106f32e7eSjoerg TypeId GetTestTypeId() {
64206f32e7eSjoerg   return GetTypeId<Test>();
64306f32e7eSjoerg }
64406f32e7eSjoerg 
64506f32e7eSjoerg // The value of GetTestTypeId() as seen from within the Google Test
64606f32e7eSjoerg // library.  This is solely for testing GetTestTypeId().
64706f32e7eSjoerg extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
64806f32e7eSjoerg 
64906f32e7eSjoerg // This predicate-formatter checks that 'results' contains a test part
65006f32e7eSjoerg // failure of the given type and that the failure message contains the
65106f32e7eSjoerg // given substring.
HasOneFailure(const char *,const char *,const char *,const TestPartResultArray & results,TestPartResult::Type type,const std::string & substr)652*da58b97aSjoerg static AssertionResult HasOneFailure(const char* /* results_expr */,
65306f32e7eSjoerg                                      const char* /* type_expr */,
65406f32e7eSjoerg                                      const char* /* substr_expr */,
65506f32e7eSjoerg                                      const TestPartResultArray& results,
65606f32e7eSjoerg                                      TestPartResult::Type type,
657*da58b97aSjoerg                                      const std::string& substr) {
65806f32e7eSjoerg   const std::string expected(type == TestPartResult::kFatalFailure ?
65906f32e7eSjoerg                         "1 fatal failure" :
66006f32e7eSjoerg                         "1 non-fatal failure");
66106f32e7eSjoerg   Message msg;
66206f32e7eSjoerg   if (results.size() != 1) {
66306f32e7eSjoerg     msg << "Expected: " << expected << "\n"
66406f32e7eSjoerg         << "  Actual: " << results.size() << " failures";
66506f32e7eSjoerg     for (int i = 0; i < results.size(); i++) {
66606f32e7eSjoerg       msg << "\n" << results.GetTestPartResult(i);
66706f32e7eSjoerg     }
66806f32e7eSjoerg     return AssertionFailure() << msg;
66906f32e7eSjoerg   }
67006f32e7eSjoerg 
67106f32e7eSjoerg   const TestPartResult& r = results.GetTestPartResult(0);
67206f32e7eSjoerg   if (r.type() != type) {
67306f32e7eSjoerg     return AssertionFailure() << "Expected: " << expected << "\n"
67406f32e7eSjoerg                               << "  Actual:\n"
67506f32e7eSjoerg                               << r;
67606f32e7eSjoerg   }
67706f32e7eSjoerg 
678*da58b97aSjoerg   if (strstr(r.message(), substr.c_str()) == nullptr) {
67906f32e7eSjoerg     return AssertionFailure() << "Expected: " << expected << " containing \""
68006f32e7eSjoerg                               << substr << "\"\n"
68106f32e7eSjoerg                               << "  Actual:\n"
68206f32e7eSjoerg                               << r;
68306f32e7eSjoerg   }
68406f32e7eSjoerg 
68506f32e7eSjoerg   return AssertionSuccess();
68606f32e7eSjoerg }
68706f32e7eSjoerg 
68806f32e7eSjoerg // The constructor of SingleFailureChecker remembers where to look up
68906f32e7eSjoerg // test part results, what type of failure we expect, and what
69006f32e7eSjoerg // substring the failure message should contain.
SingleFailureChecker(const TestPartResultArray * results,TestPartResult::Type type,const std::string & substr)691*da58b97aSjoerg SingleFailureChecker::SingleFailureChecker(const TestPartResultArray* results,
69206f32e7eSjoerg                                            TestPartResult::Type type,
693*da58b97aSjoerg                                            const std::string& substr)
694*da58b97aSjoerg     : results_(results), type_(type), substr_(substr) {}
69506f32e7eSjoerg 
69606f32e7eSjoerg // The destructor of SingleFailureChecker verifies that the given
69706f32e7eSjoerg // TestPartResultArray contains exactly one failure that has the given
69806f32e7eSjoerg // type and contains the given substring.  If that's not the case, a
69906f32e7eSjoerg // non-fatal failure will be generated.
~SingleFailureChecker()70006f32e7eSjoerg SingleFailureChecker::~SingleFailureChecker() {
70106f32e7eSjoerg   EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_);
70206f32e7eSjoerg }
70306f32e7eSjoerg 
DefaultGlobalTestPartResultReporter(UnitTestImpl * unit_test)70406f32e7eSjoerg DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
70506f32e7eSjoerg     UnitTestImpl* unit_test) : unit_test_(unit_test) {}
70606f32e7eSjoerg 
ReportTestPartResult(const TestPartResult & result)70706f32e7eSjoerg void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
70806f32e7eSjoerg     const TestPartResult& result) {
70906f32e7eSjoerg   unit_test_->current_test_result()->AddTestPartResult(result);
71006f32e7eSjoerg   unit_test_->listeners()->repeater()->OnTestPartResult(result);
71106f32e7eSjoerg }
71206f32e7eSjoerg 
DefaultPerThreadTestPartResultReporter(UnitTestImpl * unit_test)71306f32e7eSjoerg DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
71406f32e7eSjoerg     UnitTestImpl* unit_test) : unit_test_(unit_test) {}
71506f32e7eSjoerg 
ReportTestPartResult(const TestPartResult & result)71606f32e7eSjoerg void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
71706f32e7eSjoerg     const TestPartResult& result) {
71806f32e7eSjoerg   unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
71906f32e7eSjoerg }
72006f32e7eSjoerg 
72106f32e7eSjoerg // Returns the global test part result reporter.
72206f32e7eSjoerg TestPartResultReporterInterface*
GetGlobalTestPartResultReporter()72306f32e7eSjoerg UnitTestImpl::GetGlobalTestPartResultReporter() {
72406f32e7eSjoerg   internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
72506f32e7eSjoerg   return global_test_part_result_repoter_;
72606f32e7eSjoerg }
72706f32e7eSjoerg 
72806f32e7eSjoerg // Sets the global test part result reporter.
SetGlobalTestPartResultReporter(TestPartResultReporterInterface * reporter)72906f32e7eSjoerg void UnitTestImpl::SetGlobalTestPartResultReporter(
73006f32e7eSjoerg     TestPartResultReporterInterface* reporter) {
73106f32e7eSjoerg   internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
73206f32e7eSjoerg   global_test_part_result_repoter_ = reporter;
73306f32e7eSjoerg }
73406f32e7eSjoerg 
73506f32e7eSjoerg // Returns the test part result reporter for the current thread.
73606f32e7eSjoerg TestPartResultReporterInterface*
GetTestPartResultReporterForCurrentThread()73706f32e7eSjoerg UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
73806f32e7eSjoerg   return per_thread_test_part_result_reporter_.get();
73906f32e7eSjoerg }
74006f32e7eSjoerg 
74106f32e7eSjoerg // Sets the test part result reporter for the current thread.
SetTestPartResultReporterForCurrentThread(TestPartResultReporterInterface * reporter)74206f32e7eSjoerg void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
74306f32e7eSjoerg     TestPartResultReporterInterface* reporter) {
74406f32e7eSjoerg   per_thread_test_part_result_reporter_.set(reporter);
74506f32e7eSjoerg }
74606f32e7eSjoerg 
747*da58b97aSjoerg // Gets the number of successful test suites.
successful_test_suite_count() const748*da58b97aSjoerg int UnitTestImpl::successful_test_suite_count() const {
749*da58b97aSjoerg   return CountIf(test_suites_, TestSuitePassed);
75006f32e7eSjoerg }
75106f32e7eSjoerg 
752*da58b97aSjoerg // Gets the number of failed test suites.
failed_test_suite_count() const753*da58b97aSjoerg int UnitTestImpl::failed_test_suite_count() const {
754*da58b97aSjoerg   return CountIf(test_suites_, TestSuiteFailed);
75506f32e7eSjoerg }
75606f32e7eSjoerg 
757*da58b97aSjoerg // Gets the number of all test suites.
total_test_suite_count() const758*da58b97aSjoerg int UnitTestImpl::total_test_suite_count() const {
759*da58b97aSjoerg   return static_cast<int>(test_suites_.size());
76006f32e7eSjoerg }
76106f32e7eSjoerg 
762*da58b97aSjoerg // Gets the number of all test suites that contain at least one test
76306f32e7eSjoerg // that should run.
test_suite_to_run_count() const764*da58b97aSjoerg int UnitTestImpl::test_suite_to_run_count() const {
765*da58b97aSjoerg   return CountIf(test_suites_, ShouldRunTestSuite);
76606f32e7eSjoerg }
76706f32e7eSjoerg 
76806f32e7eSjoerg // Gets the number of successful tests.
successful_test_count() const76906f32e7eSjoerg int UnitTestImpl::successful_test_count() const {
770*da58b97aSjoerg   return SumOverTestSuiteList(test_suites_, &TestSuite::successful_test_count);
771*da58b97aSjoerg }
772*da58b97aSjoerg 
773*da58b97aSjoerg // Gets the number of skipped tests.
skipped_test_count() const774*da58b97aSjoerg int UnitTestImpl::skipped_test_count() const {
775*da58b97aSjoerg   return SumOverTestSuiteList(test_suites_, &TestSuite::skipped_test_count);
77606f32e7eSjoerg }
77706f32e7eSjoerg 
77806f32e7eSjoerg // Gets the number of failed tests.
failed_test_count() const77906f32e7eSjoerg int UnitTestImpl::failed_test_count() const {
780*da58b97aSjoerg   return SumOverTestSuiteList(test_suites_, &TestSuite::failed_test_count);
78106f32e7eSjoerg }
78206f32e7eSjoerg 
78306f32e7eSjoerg // Gets the number of disabled tests that will be reported in the XML report.
reportable_disabled_test_count() const78406f32e7eSjoerg int UnitTestImpl::reportable_disabled_test_count() const {
785*da58b97aSjoerg   return SumOverTestSuiteList(test_suites_,
786*da58b97aSjoerg                               &TestSuite::reportable_disabled_test_count);
78706f32e7eSjoerg }
78806f32e7eSjoerg 
78906f32e7eSjoerg // Gets the number of disabled tests.
disabled_test_count() const79006f32e7eSjoerg int UnitTestImpl::disabled_test_count() const {
791*da58b97aSjoerg   return SumOverTestSuiteList(test_suites_, &TestSuite::disabled_test_count);
79206f32e7eSjoerg }
79306f32e7eSjoerg 
79406f32e7eSjoerg // Gets the number of tests to be printed in the XML report.
reportable_test_count() const79506f32e7eSjoerg int UnitTestImpl::reportable_test_count() const {
796*da58b97aSjoerg   return SumOverTestSuiteList(test_suites_, &TestSuite::reportable_test_count);
79706f32e7eSjoerg }
79806f32e7eSjoerg 
79906f32e7eSjoerg // Gets the number of all tests.
total_test_count() const80006f32e7eSjoerg int UnitTestImpl::total_test_count() const {
801*da58b97aSjoerg   return SumOverTestSuiteList(test_suites_, &TestSuite::total_test_count);
80206f32e7eSjoerg }
80306f32e7eSjoerg 
80406f32e7eSjoerg // Gets the number of tests that should run.
test_to_run_count() const80506f32e7eSjoerg int UnitTestImpl::test_to_run_count() const {
806*da58b97aSjoerg   return SumOverTestSuiteList(test_suites_, &TestSuite::test_to_run_count);
80706f32e7eSjoerg }
80806f32e7eSjoerg 
80906f32e7eSjoerg // Returns the current OS stack trace as an std::string.
81006f32e7eSjoerg //
81106f32e7eSjoerg // The maximum number of stack frames to be included is specified by
81206f32e7eSjoerg // the gtest_stack_trace_depth flag.  The skip_count parameter
81306f32e7eSjoerg // specifies the number of top frames to be skipped, which doesn't
81406f32e7eSjoerg // count against the number of frames to be included.
81506f32e7eSjoerg //
81606f32e7eSjoerg // For example, if Foo() calls Bar(), which in turn calls
81706f32e7eSjoerg // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
81806f32e7eSjoerg // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
CurrentOsStackTraceExceptTop(int skip_count)81906f32e7eSjoerg std::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
82006f32e7eSjoerg   return os_stack_trace_getter()->CurrentStackTrace(
82106f32e7eSjoerg       static_cast<int>(GTEST_FLAG(stack_trace_depth)),
82206f32e7eSjoerg       skip_count + 1
82306f32e7eSjoerg       // Skips the user-specified number of frames plus this function
82406f32e7eSjoerg       // itself.
82506f32e7eSjoerg       );  // NOLINT
82606f32e7eSjoerg }
82706f32e7eSjoerg 
82806f32e7eSjoerg // Returns the current time in milliseconds.
GetTimeInMillis()82906f32e7eSjoerg TimeInMillis GetTimeInMillis() {
83006f32e7eSjoerg #if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__)
83106f32e7eSjoerg   // Difference between 1970-01-01 and 1601-01-01 in milliseconds.
83206f32e7eSjoerg   // http://analogous.blogspot.com/2005/04/epoch.html
83306f32e7eSjoerg   const TimeInMillis kJavaEpochToWinFileTimeDelta =
83406f32e7eSjoerg     static_cast<TimeInMillis>(116444736UL) * 100000UL;
83506f32e7eSjoerg   const DWORD kTenthMicrosInMilliSecond = 10000;
83606f32e7eSjoerg 
83706f32e7eSjoerg   SYSTEMTIME now_systime;
83806f32e7eSjoerg   FILETIME now_filetime;
83906f32e7eSjoerg   ULARGE_INTEGER now_int64;
84006f32e7eSjoerg   GetSystemTime(&now_systime);
84106f32e7eSjoerg   if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
84206f32e7eSjoerg     now_int64.LowPart = now_filetime.dwLowDateTime;
84306f32e7eSjoerg     now_int64.HighPart = now_filetime.dwHighDateTime;
84406f32e7eSjoerg     now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
84506f32e7eSjoerg       kJavaEpochToWinFileTimeDelta;
84606f32e7eSjoerg     return now_int64.QuadPart;
84706f32e7eSjoerg   }
84806f32e7eSjoerg   return 0;
84906f32e7eSjoerg #elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_
85006f32e7eSjoerg   __timeb64 now;
85106f32e7eSjoerg 
85206f32e7eSjoerg   // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996
85306f32e7eSjoerg   // (deprecated function) there.
854*da58b97aSjoerg   GTEST_DISABLE_MSC_DEPRECATED_PUSH_()
85506f32e7eSjoerg   _ftime64(&now);
856*da58b97aSjoerg   GTEST_DISABLE_MSC_DEPRECATED_POP_()
85706f32e7eSjoerg 
85806f32e7eSjoerg   return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
85906f32e7eSjoerg #elif GTEST_HAS_GETTIMEOFDAY_
86006f32e7eSjoerg   struct timeval now;
861*da58b97aSjoerg   gettimeofday(&now, nullptr);
86206f32e7eSjoerg   return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
86306f32e7eSjoerg #else
86406f32e7eSjoerg # error "Don't know how to get the current time on your system."
86506f32e7eSjoerg #endif
86606f32e7eSjoerg }
86706f32e7eSjoerg 
86806f32e7eSjoerg // Utilities
86906f32e7eSjoerg 
87006f32e7eSjoerg // class String.
87106f32e7eSjoerg 
87206f32e7eSjoerg #if GTEST_OS_WINDOWS_MOBILE
87306f32e7eSjoerg // Creates a UTF-16 wide string from the given ANSI string, allocating
87406f32e7eSjoerg // memory using new. The caller is responsible for deleting the return
87506f32e7eSjoerg // value using delete[]. Returns the wide string, or NULL if the
87606f32e7eSjoerg // input is NULL.
AnsiToUtf16(const char * ansi)87706f32e7eSjoerg LPCWSTR String::AnsiToUtf16(const char* ansi) {
878*da58b97aSjoerg   if (!ansi) return nullptr;
87906f32e7eSjoerg   const int length = strlen(ansi);
88006f32e7eSjoerg   const int unicode_length =
881*da58b97aSjoerg       MultiByteToWideChar(CP_ACP, 0, ansi, length, nullptr, 0);
88206f32e7eSjoerg   WCHAR* unicode = new WCHAR[unicode_length + 1];
88306f32e7eSjoerg   MultiByteToWideChar(CP_ACP, 0, ansi, length,
88406f32e7eSjoerg                       unicode, unicode_length);
88506f32e7eSjoerg   unicode[unicode_length] = 0;
88606f32e7eSjoerg   return unicode;
88706f32e7eSjoerg }
88806f32e7eSjoerg 
88906f32e7eSjoerg // Creates an ANSI string from the given wide string, allocating
89006f32e7eSjoerg // memory using new. The caller is responsible for deleting the return
89106f32e7eSjoerg // value using delete[]. Returns the ANSI string, or NULL if the
89206f32e7eSjoerg // input is NULL.
Utf16ToAnsi(LPCWSTR utf16_str)89306f32e7eSjoerg const char* String::Utf16ToAnsi(LPCWSTR utf16_str)  {
894*da58b97aSjoerg   if (!utf16_str) return nullptr;
895*da58b97aSjoerg   const int ansi_length = WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, nullptr,
896*da58b97aSjoerg                                               0, nullptr, nullptr);
89706f32e7eSjoerg   char* ansi = new char[ansi_length + 1];
898*da58b97aSjoerg   WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, ansi, ansi_length, nullptr,
899*da58b97aSjoerg                       nullptr);
90006f32e7eSjoerg   ansi[ansi_length] = 0;
90106f32e7eSjoerg   return ansi;
90206f32e7eSjoerg }
90306f32e7eSjoerg 
90406f32e7eSjoerg #endif  // GTEST_OS_WINDOWS_MOBILE
90506f32e7eSjoerg 
906*da58b97aSjoerg // Compares two C strings.  Returns true if and only if they have the same
907*da58b97aSjoerg // content.
90806f32e7eSjoerg //
90906f32e7eSjoerg // Unlike strcmp(), this function can handle NULL argument(s).  A NULL
91006f32e7eSjoerg // C string is considered different to any non-NULL C string,
91106f32e7eSjoerg // including the empty string.
CStringEquals(const char * lhs,const char * rhs)91206f32e7eSjoerg bool String::CStringEquals(const char * lhs, const char * rhs) {
913*da58b97aSjoerg   if (lhs == nullptr) return rhs == nullptr;
91406f32e7eSjoerg 
915*da58b97aSjoerg   if (rhs == nullptr) return false;
91606f32e7eSjoerg 
91706f32e7eSjoerg   return strcmp(lhs, rhs) == 0;
91806f32e7eSjoerg }
91906f32e7eSjoerg 
920*da58b97aSjoerg #if GTEST_HAS_STD_WSTRING
92106f32e7eSjoerg 
92206f32e7eSjoerg // Converts an array of wide chars to a narrow string using the UTF-8
92306f32e7eSjoerg // encoding, and streams the result to the given Message object.
StreamWideCharsToMessage(const wchar_t * wstr,size_t length,Message * msg)92406f32e7eSjoerg static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
92506f32e7eSjoerg                                      Message* msg) {
92606f32e7eSjoerg   for (size_t i = 0; i != length; ) {  // NOLINT
92706f32e7eSjoerg     if (wstr[i] != L'\0') {
92806f32e7eSjoerg       *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
92906f32e7eSjoerg       while (i != length && wstr[i] != L'\0')
93006f32e7eSjoerg         i++;
93106f32e7eSjoerg     } else {
93206f32e7eSjoerg       *msg << '\0';
93306f32e7eSjoerg       i++;
93406f32e7eSjoerg     }
93506f32e7eSjoerg   }
93606f32e7eSjoerg }
93706f32e7eSjoerg 
938*da58b97aSjoerg #endif  // GTEST_HAS_STD_WSTRING
93906f32e7eSjoerg 
SplitString(const::std::string & str,char delimiter,::std::vector<::std::string> * dest)94006f32e7eSjoerg void SplitString(const ::std::string& str, char delimiter,
94106f32e7eSjoerg                  ::std::vector< ::std::string>* dest) {
94206f32e7eSjoerg   ::std::vector< ::std::string> parsed;
94306f32e7eSjoerg   ::std::string::size_type pos = 0;
94406f32e7eSjoerg   while (::testing::internal::AlwaysTrue()) {
94506f32e7eSjoerg     const ::std::string::size_type colon = str.find(delimiter, pos);
94606f32e7eSjoerg     if (colon == ::std::string::npos) {
94706f32e7eSjoerg       parsed.push_back(str.substr(pos));
94806f32e7eSjoerg       break;
94906f32e7eSjoerg     } else {
95006f32e7eSjoerg       parsed.push_back(str.substr(pos, colon - pos));
95106f32e7eSjoerg       pos = colon + 1;
95206f32e7eSjoerg     }
95306f32e7eSjoerg   }
95406f32e7eSjoerg   dest->swap(parsed);
95506f32e7eSjoerg }
95606f32e7eSjoerg 
95706f32e7eSjoerg }  // namespace internal
95806f32e7eSjoerg 
95906f32e7eSjoerg // Constructs an empty Message.
96006f32e7eSjoerg // We allocate the stringstream separately because otherwise each use of
96106f32e7eSjoerg // ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's
96206f32e7eSjoerg // stack frame leading to huge stack frames in some cases; gcc does not reuse
96306f32e7eSjoerg // the stack space.
Message()96406f32e7eSjoerg Message::Message() : ss_(new ::std::stringstream) {
96506f32e7eSjoerg   // By default, we want there to be enough precision when printing
96606f32e7eSjoerg   // a double to a Message.
96706f32e7eSjoerg   *ss_ << std::setprecision(std::numeric_limits<double>::digits10 + 2);
96806f32e7eSjoerg }
96906f32e7eSjoerg 
97006f32e7eSjoerg // These two overloads allow streaming a wide C string to a Message
97106f32e7eSjoerg // using the UTF-8 encoding.
operator <<(const wchar_t * wide_c_str)97206f32e7eSjoerg Message& Message::operator <<(const wchar_t* wide_c_str) {
97306f32e7eSjoerg   return *this << internal::String::ShowWideCString(wide_c_str);
97406f32e7eSjoerg }
operator <<(wchar_t * wide_c_str)97506f32e7eSjoerg Message& Message::operator <<(wchar_t* wide_c_str) {
97606f32e7eSjoerg   return *this << internal::String::ShowWideCString(wide_c_str);
97706f32e7eSjoerg }
97806f32e7eSjoerg 
97906f32e7eSjoerg #if GTEST_HAS_STD_WSTRING
98006f32e7eSjoerg // Converts the given wide string to a narrow string using the UTF-8
98106f32e7eSjoerg // encoding, and streams the result to this Message object.
operator <<(const::std::wstring & wstr)98206f32e7eSjoerg Message& Message::operator <<(const ::std::wstring& wstr) {
98306f32e7eSjoerg   internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
98406f32e7eSjoerg   return *this;
98506f32e7eSjoerg }
98606f32e7eSjoerg #endif  // GTEST_HAS_STD_WSTRING
98706f32e7eSjoerg 
98806f32e7eSjoerg // Gets the text streamed to this object so far as an std::string.
98906f32e7eSjoerg // Each '\0' character in the buffer is replaced with "\\0".
GetString() const99006f32e7eSjoerg std::string Message::GetString() const {
99106f32e7eSjoerg   return internal::StringStreamToString(ss_.get());
99206f32e7eSjoerg }
99306f32e7eSjoerg 
99406f32e7eSjoerg // AssertionResult constructors.
99506f32e7eSjoerg // Used in EXPECT_TRUE/FALSE(assertion_result).
AssertionResult(const AssertionResult & other)99606f32e7eSjoerg AssertionResult::AssertionResult(const AssertionResult& other)
99706f32e7eSjoerg     : success_(other.success_),
998*da58b97aSjoerg       message_(other.message_.get() != nullptr
999*da58b97aSjoerg                    ? new ::std::string(*other.message_)
1000*da58b97aSjoerg                    : static_cast< ::std::string*>(nullptr)) {}
100106f32e7eSjoerg 
100206f32e7eSjoerg // Swaps two AssertionResults.
swap(AssertionResult & other)100306f32e7eSjoerg void AssertionResult::swap(AssertionResult& other) {
100406f32e7eSjoerg   using std::swap;
100506f32e7eSjoerg   swap(success_, other.success_);
100606f32e7eSjoerg   swap(message_, other.message_);
100706f32e7eSjoerg }
100806f32e7eSjoerg 
100906f32e7eSjoerg // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
operator !() const101006f32e7eSjoerg AssertionResult AssertionResult::operator!() const {
101106f32e7eSjoerg   AssertionResult negation(!success_);
1012*da58b97aSjoerg   if (message_.get() != nullptr) negation << *message_;
101306f32e7eSjoerg   return negation;
101406f32e7eSjoerg }
101506f32e7eSjoerg 
101606f32e7eSjoerg // Makes a successful assertion result.
AssertionSuccess()101706f32e7eSjoerg AssertionResult AssertionSuccess() {
101806f32e7eSjoerg   return AssertionResult(true);
101906f32e7eSjoerg }
102006f32e7eSjoerg 
102106f32e7eSjoerg // Makes a failed assertion result.
AssertionFailure()102206f32e7eSjoerg AssertionResult AssertionFailure() {
102306f32e7eSjoerg   return AssertionResult(false);
102406f32e7eSjoerg }
102506f32e7eSjoerg 
102606f32e7eSjoerg // Makes a failed assertion result with the given failure message.
102706f32e7eSjoerg // Deprecated; use AssertionFailure() << message.
AssertionFailure(const Message & message)102806f32e7eSjoerg AssertionResult AssertionFailure(const Message& message) {
102906f32e7eSjoerg   return AssertionFailure() << message;
103006f32e7eSjoerg }
103106f32e7eSjoerg 
103206f32e7eSjoerg namespace internal {
103306f32e7eSjoerg 
103406f32e7eSjoerg namespace edit_distance {
CalculateOptimalEdits(const std::vector<size_t> & left,const std::vector<size_t> & right)103506f32e7eSjoerg std::vector<EditType> CalculateOptimalEdits(const std::vector<size_t>& left,
103606f32e7eSjoerg                                             const std::vector<size_t>& right) {
103706f32e7eSjoerg   std::vector<std::vector<double> > costs(
103806f32e7eSjoerg       left.size() + 1, std::vector<double>(right.size() + 1));
103906f32e7eSjoerg   std::vector<std::vector<EditType> > best_move(
104006f32e7eSjoerg       left.size() + 1, std::vector<EditType>(right.size() + 1));
104106f32e7eSjoerg 
104206f32e7eSjoerg   // Populate for empty right.
104306f32e7eSjoerg   for (size_t l_i = 0; l_i < costs.size(); ++l_i) {
104406f32e7eSjoerg     costs[l_i][0] = static_cast<double>(l_i);
104506f32e7eSjoerg     best_move[l_i][0] = kRemove;
104606f32e7eSjoerg   }
104706f32e7eSjoerg   // Populate for empty left.
104806f32e7eSjoerg   for (size_t r_i = 1; r_i < costs[0].size(); ++r_i) {
104906f32e7eSjoerg     costs[0][r_i] = static_cast<double>(r_i);
105006f32e7eSjoerg     best_move[0][r_i] = kAdd;
105106f32e7eSjoerg   }
105206f32e7eSjoerg 
105306f32e7eSjoerg   for (size_t l_i = 0; l_i < left.size(); ++l_i) {
105406f32e7eSjoerg     for (size_t r_i = 0; r_i < right.size(); ++r_i) {
105506f32e7eSjoerg       if (left[l_i] == right[r_i]) {
105606f32e7eSjoerg         // Found a match. Consume it.
105706f32e7eSjoerg         costs[l_i + 1][r_i + 1] = costs[l_i][r_i];
105806f32e7eSjoerg         best_move[l_i + 1][r_i + 1] = kMatch;
105906f32e7eSjoerg         continue;
106006f32e7eSjoerg       }
106106f32e7eSjoerg 
106206f32e7eSjoerg       const double add = costs[l_i + 1][r_i];
106306f32e7eSjoerg       const double remove = costs[l_i][r_i + 1];
106406f32e7eSjoerg       const double replace = costs[l_i][r_i];
106506f32e7eSjoerg       if (add < remove && add < replace) {
106606f32e7eSjoerg         costs[l_i + 1][r_i + 1] = add + 1;
106706f32e7eSjoerg         best_move[l_i + 1][r_i + 1] = kAdd;
106806f32e7eSjoerg       } else if (remove < add && remove < replace) {
106906f32e7eSjoerg         costs[l_i + 1][r_i + 1] = remove + 1;
107006f32e7eSjoerg         best_move[l_i + 1][r_i + 1] = kRemove;
107106f32e7eSjoerg       } else {
107206f32e7eSjoerg         // We make replace a little more expensive than add/remove to lower
107306f32e7eSjoerg         // their priority.
107406f32e7eSjoerg         costs[l_i + 1][r_i + 1] = replace + 1.00001;
107506f32e7eSjoerg         best_move[l_i + 1][r_i + 1] = kReplace;
107606f32e7eSjoerg       }
107706f32e7eSjoerg     }
107806f32e7eSjoerg   }
107906f32e7eSjoerg 
108006f32e7eSjoerg   // Reconstruct the best path. We do it in reverse order.
108106f32e7eSjoerg   std::vector<EditType> best_path;
108206f32e7eSjoerg   for (size_t l_i = left.size(), r_i = right.size(); l_i > 0 || r_i > 0;) {
108306f32e7eSjoerg     EditType move = best_move[l_i][r_i];
108406f32e7eSjoerg     best_path.push_back(move);
108506f32e7eSjoerg     l_i -= move != kAdd;
108606f32e7eSjoerg     r_i -= move != kRemove;
108706f32e7eSjoerg   }
108806f32e7eSjoerg   std::reverse(best_path.begin(), best_path.end());
108906f32e7eSjoerg   return best_path;
109006f32e7eSjoerg }
109106f32e7eSjoerg 
109206f32e7eSjoerg namespace {
109306f32e7eSjoerg 
109406f32e7eSjoerg // Helper class to convert string into ids with deduplication.
109506f32e7eSjoerg class InternalStrings {
109606f32e7eSjoerg  public:
GetId(const std::string & str)109706f32e7eSjoerg   size_t GetId(const std::string& str) {
109806f32e7eSjoerg     IdMap::iterator it = ids_.find(str);
109906f32e7eSjoerg     if (it != ids_.end()) return it->second;
110006f32e7eSjoerg     size_t id = ids_.size();
110106f32e7eSjoerg     return ids_[str] = id;
110206f32e7eSjoerg   }
110306f32e7eSjoerg 
110406f32e7eSjoerg  private:
110506f32e7eSjoerg   typedef std::map<std::string, size_t> IdMap;
110606f32e7eSjoerg   IdMap ids_;
110706f32e7eSjoerg };
110806f32e7eSjoerg 
110906f32e7eSjoerg }  // namespace
111006f32e7eSjoerg 
CalculateOptimalEdits(const std::vector<std::string> & left,const std::vector<std::string> & right)111106f32e7eSjoerg std::vector<EditType> CalculateOptimalEdits(
111206f32e7eSjoerg     const std::vector<std::string>& left,
111306f32e7eSjoerg     const std::vector<std::string>& right) {
111406f32e7eSjoerg   std::vector<size_t> left_ids, right_ids;
111506f32e7eSjoerg   {
111606f32e7eSjoerg     InternalStrings intern_table;
111706f32e7eSjoerg     for (size_t i = 0; i < left.size(); ++i) {
111806f32e7eSjoerg       left_ids.push_back(intern_table.GetId(left[i]));
111906f32e7eSjoerg     }
112006f32e7eSjoerg     for (size_t i = 0; i < right.size(); ++i) {
112106f32e7eSjoerg       right_ids.push_back(intern_table.GetId(right[i]));
112206f32e7eSjoerg     }
112306f32e7eSjoerg   }
112406f32e7eSjoerg   return CalculateOptimalEdits(left_ids, right_ids);
112506f32e7eSjoerg }
112606f32e7eSjoerg 
112706f32e7eSjoerg namespace {
112806f32e7eSjoerg 
112906f32e7eSjoerg // Helper class that holds the state for one hunk and prints it out to the
113006f32e7eSjoerg // stream.
113106f32e7eSjoerg // It reorders adds/removes when possible to group all removes before all
113206f32e7eSjoerg // adds. It also adds the hunk header before printint into the stream.
113306f32e7eSjoerg class Hunk {
113406f32e7eSjoerg  public:
Hunk(size_t left_start,size_t right_start)113506f32e7eSjoerg   Hunk(size_t left_start, size_t right_start)
113606f32e7eSjoerg       : left_start_(left_start),
113706f32e7eSjoerg         right_start_(right_start),
113806f32e7eSjoerg         adds_(),
113906f32e7eSjoerg         removes_(),
114006f32e7eSjoerg         common_() {}
114106f32e7eSjoerg 
PushLine(char edit,const char * line)114206f32e7eSjoerg   void PushLine(char edit, const char* line) {
114306f32e7eSjoerg     switch (edit) {
114406f32e7eSjoerg       case ' ':
114506f32e7eSjoerg         ++common_;
114606f32e7eSjoerg         FlushEdits();
114706f32e7eSjoerg         hunk_.push_back(std::make_pair(' ', line));
114806f32e7eSjoerg         break;
114906f32e7eSjoerg       case '-':
115006f32e7eSjoerg         ++removes_;
115106f32e7eSjoerg         hunk_removes_.push_back(std::make_pair('-', line));
115206f32e7eSjoerg         break;
115306f32e7eSjoerg       case '+':
115406f32e7eSjoerg         ++adds_;
115506f32e7eSjoerg         hunk_adds_.push_back(std::make_pair('+', line));
115606f32e7eSjoerg         break;
115706f32e7eSjoerg     }
115806f32e7eSjoerg   }
115906f32e7eSjoerg 
PrintTo(std::ostream * os)116006f32e7eSjoerg   void PrintTo(std::ostream* os) {
116106f32e7eSjoerg     PrintHeader(os);
116206f32e7eSjoerg     FlushEdits();
116306f32e7eSjoerg     for (std::list<std::pair<char, const char*> >::const_iterator it =
116406f32e7eSjoerg              hunk_.begin();
116506f32e7eSjoerg          it != hunk_.end(); ++it) {
116606f32e7eSjoerg       *os << it->first << it->second << "\n";
116706f32e7eSjoerg     }
116806f32e7eSjoerg   }
116906f32e7eSjoerg 
has_edits() const117006f32e7eSjoerg   bool has_edits() const { return adds_ || removes_; }
117106f32e7eSjoerg 
117206f32e7eSjoerg  private:
FlushEdits()117306f32e7eSjoerg   void FlushEdits() {
117406f32e7eSjoerg     hunk_.splice(hunk_.end(), hunk_removes_);
117506f32e7eSjoerg     hunk_.splice(hunk_.end(), hunk_adds_);
117606f32e7eSjoerg   }
117706f32e7eSjoerg 
117806f32e7eSjoerg   // Print a unified diff header for one hunk.
117906f32e7eSjoerg   // The format is
118006f32e7eSjoerg   //   "@@ -<left_start>,<left_length> +<right_start>,<right_length> @@"
1181*da58b97aSjoerg   // where the left/right parts are omitted if unnecessary.
PrintHeader(std::ostream * ss) const118206f32e7eSjoerg   void PrintHeader(std::ostream* ss) const {
118306f32e7eSjoerg     *ss << "@@ ";
118406f32e7eSjoerg     if (removes_) {
118506f32e7eSjoerg       *ss << "-" << left_start_ << "," << (removes_ + common_);
118606f32e7eSjoerg     }
118706f32e7eSjoerg     if (removes_ && adds_) {
118806f32e7eSjoerg       *ss << " ";
118906f32e7eSjoerg     }
119006f32e7eSjoerg     if (adds_) {
119106f32e7eSjoerg       *ss << "+" << right_start_ << "," << (adds_ + common_);
119206f32e7eSjoerg     }
119306f32e7eSjoerg     *ss << " @@\n";
119406f32e7eSjoerg   }
119506f32e7eSjoerg 
119606f32e7eSjoerg   size_t left_start_, right_start_;
119706f32e7eSjoerg   size_t adds_, removes_, common_;
119806f32e7eSjoerg   std::list<std::pair<char, const char*> > hunk_, hunk_adds_, hunk_removes_;
119906f32e7eSjoerg };
120006f32e7eSjoerg 
120106f32e7eSjoerg }  // namespace
120206f32e7eSjoerg 
120306f32e7eSjoerg // Create a list of diff hunks in Unified diff format.
120406f32e7eSjoerg // Each hunk has a header generated by PrintHeader above plus a body with
120506f32e7eSjoerg // lines prefixed with ' ' for no change, '-' for deletion and '+' for
120606f32e7eSjoerg // addition.
120706f32e7eSjoerg // 'context' represents the desired unchanged prefix/suffix around the diff.
120806f32e7eSjoerg // If two hunks are close enough that their contexts overlap, then they are
120906f32e7eSjoerg // joined into one hunk.
CreateUnifiedDiff(const std::vector<std::string> & left,const std::vector<std::string> & right,size_t context)121006f32e7eSjoerg std::string CreateUnifiedDiff(const std::vector<std::string>& left,
121106f32e7eSjoerg                               const std::vector<std::string>& right,
121206f32e7eSjoerg                               size_t context) {
121306f32e7eSjoerg   const std::vector<EditType> edits = CalculateOptimalEdits(left, right);
121406f32e7eSjoerg 
121506f32e7eSjoerg   size_t l_i = 0, r_i = 0, edit_i = 0;
121606f32e7eSjoerg   std::stringstream ss;
121706f32e7eSjoerg   while (edit_i < edits.size()) {
121806f32e7eSjoerg     // Find first edit.
121906f32e7eSjoerg     while (edit_i < edits.size() && edits[edit_i] == kMatch) {
122006f32e7eSjoerg       ++l_i;
122106f32e7eSjoerg       ++r_i;
122206f32e7eSjoerg       ++edit_i;
122306f32e7eSjoerg     }
122406f32e7eSjoerg 
122506f32e7eSjoerg     // Find the first line to include in the hunk.
122606f32e7eSjoerg     const size_t prefix_context = std::min(l_i, context);
122706f32e7eSjoerg     Hunk hunk(l_i - prefix_context + 1, r_i - prefix_context + 1);
122806f32e7eSjoerg     for (size_t i = prefix_context; i > 0; --i) {
122906f32e7eSjoerg       hunk.PushLine(' ', left[l_i - i].c_str());
123006f32e7eSjoerg     }
123106f32e7eSjoerg 
123206f32e7eSjoerg     // Iterate the edits until we found enough suffix for the hunk or the input
123306f32e7eSjoerg     // is over.
123406f32e7eSjoerg     size_t n_suffix = 0;
123506f32e7eSjoerg     for (; edit_i < edits.size(); ++edit_i) {
123606f32e7eSjoerg       if (n_suffix >= context) {
123706f32e7eSjoerg         // Continue only if the next hunk is very close.
1238*da58b97aSjoerg         auto it = edits.begin() + static_cast<int>(edit_i);
123906f32e7eSjoerg         while (it != edits.end() && *it == kMatch) ++it;
1240*da58b97aSjoerg         if (it == edits.end() ||
1241*da58b97aSjoerg             static_cast<size_t>(it - edits.begin()) - edit_i >= context) {
124206f32e7eSjoerg           // There is no next edit or it is too far away.
124306f32e7eSjoerg           break;
124406f32e7eSjoerg         }
124506f32e7eSjoerg       }
124606f32e7eSjoerg 
124706f32e7eSjoerg       EditType edit = edits[edit_i];
124806f32e7eSjoerg       // Reset count when a non match is found.
124906f32e7eSjoerg       n_suffix = edit == kMatch ? n_suffix + 1 : 0;
125006f32e7eSjoerg 
125106f32e7eSjoerg       if (edit == kMatch || edit == kRemove || edit == kReplace) {
125206f32e7eSjoerg         hunk.PushLine(edit == kMatch ? ' ' : '-', left[l_i].c_str());
125306f32e7eSjoerg       }
125406f32e7eSjoerg       if (edit == kAdd || edit == kReplace) {
125506f32e7eSjoerg         hunk.PushLine('+', right[r_i].c_str());
125606f32e7eSjoerg       }
125706f32e7eSjoerg 
125806f32e7eSjoerg       // Advance indices, depending on edit type.
125906f32e7eSjoerg       l_i += edit != kAdd;
126006f32e7eSjoerg       r_i += edit != kRemove;
126106f32e7eSjoerg     }
126206f32e7eSjoerg 
126306f32e7eSjoerg     if (!hunk.has_edits()) {
126406f32e7eSjoerg       // We are done. We don't want this hunk.
126506f32e7eSjoerg       break;
126606f32e7eSjoerg     }
126706f32e7eSjoerg 
126806f32e7eSjoerg     hunk.PrintTo(&ss);
126906f32e7eSjoerg   }
127006f32e7eSjoerg   return ss.str();
127106f32e7eSjoerg }
127206f32e7eSjoerg 
127306f32e7eSjoerg }  // namespace edit_distance
127406f32e7eSjoerg 
127506f32e7eSjoerg namespace {
127606f32e7eSjoerg 
127706f32e7eSjoerg // The string representation of the values received in EqFailure() are already
127806f32e7eSjoerg // escaped. Split them on escaped '\n' boundaries. Leave all other escaped
127906f32e7eSjoerg // characters the same.
SplitEscapedString(const std::string & str)128006f32e7eSjoerg std::vector<std::string> SplitEscapedString(const std::string& str) {
128106f32e7eSjoerg   std::vector<std::string> lines;
128206f32e7eSjoerg   size_t start = 0, end = str.size();
128306f32e7eSjoerg   if (end > 2 && str[0] == '"' && str[end - 1] == '"') {
128406f32e7eSjoerg     ++start;
128506f32e7eSjoerg     --end;
128606f32e7eSjoerg   }
128706f32e7eSjoerg   bool escaped = false;
128806f32e7eSjoerg   for (size_t i = start; i + 1 < end; ++i) {
128906f32e7eSjoerg     if (escaped) {
129006f32e7eSjoerg       escaped = false;
129106f32e7eSjoerg       if (str[i] == 'n') {
129206f32e7eSjoerg         lines.push_back(str.substr(start, i - start - 1));
129306f32e7eSjoerg         start = i + 1;
129406f32e7eSjoerg       }
129506f32e7eSjoerg     } else {
129606f32e7eSjoerg       escaped = str[i] == '\\';
129706f32e7eSjoerg     }
129806f32e7eSjoerg   }
129906f32e7eSjoerg   lines.push_back(str.substr(start, end - start));
130006f32e7eSjoerg   return lines;
130106f32e7eSjoerg }
130206f32e7eSjoerg 
130306f32e7eSjoerg }  // namespace
130406f32e7eSjoerg 
130506f32e7eSjoerg // Constructs and returns the message for an equality assertion
130606f32e7eSjoerg // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
130706f32e7eSjoerg //
130806f32e7eSjoerg // The first four parameters are the expressions used in the assertion
130906f32e7eSjoerg // and their values, as strings.  For example, for ASSERT_EQ(foo, bar)
131006f32e7eSjoerg // where foo is 5 and bar is 6, we have:
131106f32e7eSjoerg //
131206f32e7eSjoerg //   lhs_expression: "foo"
131306f32e7eSjoerg //   rhs_expression: "bar"
131406f32e7eSjoerg //   lhs_value:      "5"
131506f32e7eSjoerg //   rhs_value:      "6"
131606f32e7eSjoerg //
1317*da58b97aSjoerg // The ignoring_case parameter is true if and only if the assertion is a
131806f32e7eSjoerg // *_STRCASEEQ*.  When it's true, the string "Ignoring case" will
131906f32e7eSjoerg // be inserted into the message.
EqFailure(const char * lhs_expression,const char * rhs_expression,const std::string & lhs_value,const std::string & rhs_value,bool ignoring_case)132006f32e7eSjoerg AssertionResult EqFailure(const char* lhs_expression,
132106f32e7eSjoerg                           const char* rhs_expression,
132206f32e7eSjoerg                           const std::string& lhs_value,
132306f32e7eSjoerg                           const std::string& rhs_value,
132406f32e7eSjoerg                           bool ignoring_case) {
132506f32e7eSjoerg   Message msg;
1326*da58b97aSjoerg   msg << "Expected equality of these values:";
1327*da58b97aSjoerg   msg << "\n  " << lhs_expression;
132806f32e7eSjoerg   if (lhs_value != lhs_expression) {
132906f32e7eSjoerg     msg << "\n    Which is: " << lhs_value;
133006f32e7eSjoerg   }
1331*da58b97aSjoerg   msg << "\n  " << rhs_expression;
133206f32e7eSjoerg   if (rhs_value != rhs_expression) {
133306f32e7eSjoerg     msg << "\n    Which is: " << rhs_value;
133406f32e7eSjoerg   }
133506f32e7eSjoerg 
133606f32e7eSjoerg   if (ignoring_case) {
133706f32e7eSjoerg     msg << "\nIgnoring case";
133806f32e7eSjoerg   }
133906f32e7eSjoerg 
134006f32e7eSjoerg   if (!lhs_value.empty() && !rhs_value.empty()) {
134106f32e7eSjoerg     const std::vector<std::string> lhs_lines =
134206f32e7eSjoerg         SplitEscapedString(lhs_value);
134306f32e7eSjoerg     const std::vector<std::string> rhs_lines =
134406f32e7eSjoerg         SplitEscapedString(rhs_value);
134506f32e7eSjoerg     if (lhs_lines.size() > 1 || rhs_lines.size() > 1) {
134606f32e7eSjoerg       msg << "\nWith diff:\n"
134706f32e7eSjoerg           << edit_distance::CreateUnifiedDiff(lhs_lines, rhs_lines);
134806f32e7eSjoerg     }
134906f32e7eSjoerg   }
135006f32e7eSjoerg 
135106f32e7eSjoerg   return AssertionFailure() << msg;
135206f32e7eSjoerg }
135306f32e7eSjoerg 
135406f32e7eSjoerg // Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
GetBoolAssertionFailureMessage(const AssertionResult & assertion_result,const char * expression_text,const char * actual_predicate_value,const char * expected_predicate_value)135506f32e7eSjoerg std::string GetBoolAssertionFailureMessage(
135606f32e7eSjoerg     const AssertionResult& assertion_result,
135706f32e7eSjoerg     const char* expression_text,
135806f32e7eSjoerg     const char* actual_predicate_value,
135906f32e7eSjoerg     const char* expected_predicate_value) {
136006f32e7eSjoerg   const char* actual_message = assertion_result.message();
136106f32e7eSjoerg   Message msg;
136206f32e7eSjoerg   msg << "Value of: " << expression_text
136306f32e7eSjoerg       << "\n  Actual: " << actual_predicate_value;
136406f32e7eSjoerg   if (actual_message[0] != '\0')
136506f32e7eSjoerg     msg << " (" << actual_message << ")";
136606f32e7eSjoerg   msg << "\nExpected: " << expected_predicate_value;
136706f32e7eSjoerg   return msg.GetString();
136806f32e7eSjoerg }
136906f32e7eSjoerg 
137006f32e7eSjoerg // Helper function for implementing ASSERT_NEAR.
DoubleNearPredFormat(const char * expr1,const char * expr2,const char * abs_error_expr,double val1,double val2,double abs_error)137106f32e7eSjoerg AssertionResult DoubleNearPredFormat(const char* expr1,
137206f32e7eSjoerg                                      const char* expr2,
137306f32e7eSjoerg                                      const char* abs_error_expr,
137406f32e7eSjoerg                                      double val1,
137506f32e7eSjoerg                                      double val2,
137606f32e7eSjoerg                                      double abs_error) {
137706f32e7eSjoerg   const double diff = fabs(val1 - val2);
137806f32e7eSjoerg   if (diff <= abs_error) return AssertionSuccess();
137906f32e7eSjoerg 
138006f32e7eSjoerg   return AssertionFailure()
138106f32e7eSjoerg       << "The difference between " << expr1 << " and " << expr2
138206f32e7eSjoerg       << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"
138306f32e7eSjoerg       << expr1 << " evaluates to " << val1 << ",\n"
138406f32e7eSjoerg       << expr2 << " evaluates to " << val2 << ", and\n"
138506f32e7eSjoerg       << abs_error_expr << " evaluates to " << abs_error << ".";
138606f32e7eSjoerg }
138706f32e7eSjoerg 
138806f32e7eSjoerg 
138906f32e7eSjoerg // Helper template for implementing FloatLE() and DoubleLE().
139006f32e7eSjoerg template <typename RawType>
FloatingPointLE(const char * expr1,const char * expr2,RawType val1,RawType val2)139106f32e7eSjoerg AssertionResult FloatingPointLE(const char* expr1,
139206f32e7eSjoerg                                 const char* expr2,
139306f32e7eSjoerg                                 RawType val1,
139406f32e7eSjoerg                                 RawType val2) {
139506f32e7eSjoerg   // Returns success if val1 is less than val2,
139606f32e7eSjoerg   if (val1 < val2) {
139706f32e7eSjoerg     return AssertionSuccess();
139806f32e7eSjoerg   }
139906f32e7eSjoerg 
140006f32e7eSjoerg   // or if val1 is almost equal to val2.
140106f32e7eSjoerg   const FloatingPoint<RawType> lhs(val1), rhs(val2);
140206f32e7eSjoerg   if (lhs.AlmostEquals(rhs)) {
140306f32e7eSjoerg     return AssertionSuccess();
140406f32e7eSjoerg   }
140506f32e7eSjoerg 
140606f32e7eSjoerg   // Note that the above two checks will both fail if either val1 or
140706f32e7eSjoerg   // val2 is NaN, as the IEEE floating-point standard requires that
140806f32e7eSjoerg   // any predicate involving a NaN must return false.
140906f32e7eSjoerg 
141006f32e7eSjoerg   ::std::stringstream val1_ss;
141106f32e7eSjoerg   val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
141206f32e7eSjoerg           << val1;
141306f32e7eSjoerg 
141406f32e7eSjoerg   ::std::stringstream val2_ss;
141506f32e7eSjoerg   val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
141606f32e7eSjoerg           << val2;
141706f32e7eSjoerg 
141806f32e7eSjoerg   return AssertionFailure()
141906f32e7eSjoerg       << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
142006f32e7eSjoerg       << "  Actual: " << StringStreamToString(&val1_ss) << " vs "
142106f32e7eSjoerg       << StringStreamToString(&val2_ss);
142206f32e7eSjoerg }
142306f32e7eSjoerg 
142406f32e7eSjoerg }  // namespace internal
142506f32e7eSjoerg 
142606f32e7eSjoerg // Asserts that val1 is less than, or almost equal to, val2.  Fails
142706f32e7eSjoerg // otherwise.  In particular, it fails if either val1 or val2 is NaN.
FloatLE(const char * expr1,const char * expr2,float val1,float val2)142806f32e7eSjoerg AssertionResult FloatLE(const char* expr1, const char* expr2,
142906f32e7eSjoerg                         float val1, float val2) {
143006f32e7eSjoerg   return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
143106f32e7eSjoerg }
143206f32e7eSjoerg 
143306f32e7eSjoerg // Asserts that val1 is less than, or almost equal to, val2.  Fails
143406f32e7eSjoerg // otherwise.  In particular, it fails if either val1 or val2 is NaN.
DoubleLE(const char * expr1,const char * expr2,double val1,double val2)143506f32e7eSjoerg AssertionResult DoubleLE(const char* expr1, const char* expr2,
143606f32e7eSjoerg                          double val1, double val2) {
143706f32e7eSjoerg   return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
143806f32e7eSjoerg }
143906f32e7eSjoerg 
144006f32e7eSjoerg namespace internal {
144106f32e7eSjoerg 
144206f32e7eSjoerg // The helper function for {ASSERT|EXPECT}_EQ with int or enum
144306f32e7eSjoerg // arguments.
CmpHelperEQ(const char * lhs_expression,const char * rhs_expression,BiggestInt lhs,BiggestInt rhs)144406f32e7eSjoerg AssertionResult CmpHelperEQ(const char* lhs_expression,
144506f32e7eSjoerg                             const char* rhs_expression,
144606f32e7eSjoerg                             BiggestInt lhs,
144706f32e7eSjoerg                             BiggestInt rhs) {
144806f32e7eSjoerg   if (lhs == rhs) {
144906f32e7eSjoerg     return AssertionSuccess();
145006f32e7eSjoerg   }
145106f32e7eSjoerg 
145206f32e7eSjoerg   return EqFailure(lhs_expression,
145306f32e7eSjoerg                    rhs_expression,
145406f32e7eSjoerg                    FormatForComparisonFailureMessage(lhs, rhs),
145506f32e7eSjoerg                    FormatForComparisonFailureMessage(rhs, lhs),
145606f32e7eSjoerg                    false);
145706f32e7eSjoerg }
145806f32e7eSjoerg 
145906f32e7eSjoerg // A macro for implementing the helper functions needed to implement
146006f32e7eSjoerg // ASSERT_?? and EXPECT_?? with integer or enum arguments.  It is here
146106f32e7eSjoerg // just to avoid copy-and-paste of similar code.
146206f32e7eSjoerg #define GTEST_IMPL_CMP_HELPER_(op_name, op)\
146306f32e7eSjoerg AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
146406f32e7eSjoerg                                    BiggestInt val1, BiggestInt val2) {\
146506f32e7eSjoerg   if (val1 op val2) {\
146606f32e7eSjoerg     return AssertionSuccess();\
146706f32e7eSjoerg   } else {\
146806f32e7eSjoerg     return AssertionFailure() \
146906f32e7eSjoerg         << "Expected: (" << expr1 << ") " #op " (" << expr2\
147006f32e7eSjoerg         << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
147106f32e7eSjoerg         << " vs " << FormatForComparisonFailureMessage(val2, val1);\
147206f32e7eSjoerg   }\
147306f32e7eSjoerg }
147406f32e7eSjoerg 
147506f32e7eSjoerg // Implements the helper function for {ASSERT|EXPECT}_NE with int or
147606f32e7eSjoerg // enum arguments.
147706f32e7eSjoerg GTEST_IMPL_CMP_HELPER_(NE, !=)
147806f32e7eSjoerg // Implements the helper function for {ASSERT|EXPECT}_LE with int or
147906f32e7eSjoerg // enum arguments.
148006f32e7eSjoerg GTEST_IMPL_CMP_HELPER_(LE, <=)
148106f32e7eSjoerg // Implements the helper function for {ASSERT|EXPECT}_LT with int or
148206f32e7eSjoerg // enum arguments.
148306f32e7eSjoerg GTEST_IMPL_CMP_HELPER_(LT, < )
148406f32e7eSjoerg // Implements the helper function for {ASSERT|EXPECT}_GE with int or
148506f32e7eSjoerg // enum arguments.
148606f32e7eSjoerg GTEST_IMPL_CMP_HELPER_(GE, >=)
148706f32e7eSjoerg // Implements the helper function for {ASSERT|EXPECT}_GT with int or
148806f32e7eSjoerg // enum arguments.
148906f32e7eSjoerg GTEST_IMPL_CMP_HELPER_(GT, > )
149006f32e7eSjoerg 
149106f32e7eSjoerg #undef GTEST_IMPL_CMP_HELPER_
149206f32e7eSjoerg 
149306f32e7eSjoerg // The helper function for {ASSERT|EXPECT}_STREQ.
CmpHelperSTREQ(const char * lhs_expression,const char * rhs_expression,const char * lhs,const char * rhs)149406f32e7eSjoerg AssertionResult CmpHelperSTREQ(const char* lhs_expression,
149506f32e7eSjoerg                                const char* rhs_expression,
149606f32e7eSjoerg                                const char* lhs,
149706f32e7eSjoerg                                const char* rhs) {
149806f32e7eSjoerg   if (String::CStringEquals(lhs, rhs)) {
149906f32e7eSjoerg     return AssertionSuccess();
150006f32e7eSjoerg   }
150106f32e7eSjoerg 
150206f32e7eSjoerg   return EqFailure(lhs_expression,
150306f32e7eSjoerg                    rhs_expression,
150406f32e7eSjoerg                    PrintToString(lhs),
150506f32e7eSjoerg                    PrintToString(rhs),
150606f32e7eSjoerg                    false);
150706f32e7eSjoerg }
150806f32e7eSjoerg 
150906f32e7eSjoerg // The helper function for {ASSERT|EXPECT}_STRCASEEQ.
CmpHelperSTRCASEEQ(const char * lhs_expression,const char * rhs_expression,const char * lhs,const char * rhs)151006f32e7eSjoerg AssertionResult CmpHelperSTRCASEEQ(const char* lhs_expression,
151106f32e7eSjoerg                                    const char* rhs_expression,
151206f32e7eSjoerg                                    const char* lhs,
151306f32e7eSjoerg                                    const char* rhs) {
151406f32e7eSjoerg   if (String::CaseInsensitiveCStringEquals(lhs, rhs)) {
151506f32e7eSjoerg     return AssertionSuccess();
151606f32e7eSjoerg   }
151706f32e7eSjoerg 
151806f32e7eSjoerg   return EqFailure(lhs_expression,
151906f32e7eSjoerg                    rhs_expression,
152006f32e7eSjoerg                    PrintToString(lhs),
152106f32e7eSjoerg                    PrintToString(rhs),
152206f32e7eSjoerg                    true);
152306f32e7eSjoerg }
152406f32e7eSjoerg 
152506f32e7eSjoerg // The helper function for {ASSERT|EXPECT}_STRNE.
CmpHelperSTRNE(const char * s1_expression,const char * s2_expression,const char * s1,const char * s2)152606f32e7eSjoerg AssertionResult CmpHelperSTRNE(const char* s1_expression,
152706f32e7eSjoerg                                const char* s2_expression,
152806f32e7eSjoerg                                const char* s1,
152906f32e7eSjoerg                                const char* s2) {
153006f32e7eSjoerg   if (!String::CStringEquals(s1, s2)) {
153106f32e7eSjoerg     return AssertionSuccess();
153206f32e7eSjoerg   } else {
153306f32e7eSjoerg     return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
153406f32e7eSjoerg                               << s2_expression << "), actual: \""
153506f32e7eSjoerg                               << s1 << "\" vs \"" << s2 << "\"";
153606f32e7eSjoerg   }
153706f32e7eSjoerg }
153806f32e7eSjoerg 
153906f32e7eSjoerg // The helper function for {ASSERT|EXPECT}_STRCASENE.
CmpHelperSTRCASENE(const char * s1_expression,const char * s2_expression,const char * s1,const char * s2)154006f32e7eSjoerg AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
154106f32e7eSjoerg                                    const char* s2_expression,
154206f32e7eSjoerg                                    const char* s1,
154306f32e7eSjoerg                                    const char* s2) {
154406f32e7eSjoerg   if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
154506f32e7eSjoerg     return AssertionSuccess();
154606f32e7eSjoerg   } else {
154706f32e7eSjoerg     return AssertionFailure()
154806f32e7eSjoerg         << "Expected: (" << s1_expression << ") != ("
154906f32e7eSjoerg         << s2_expression << ") (ignoring case), actual: \""
155006f32e7eSjoerg         << s1 << "\" vs \"" << s2 << "\"";
155106f32e7eSjoerg   }
155206f32e7eSjoerg }
155306f32e7eSjoerg 
155406f32e7eSjoerg }  // namespace internal
155506f32e7eSjoerg 
155606f32e7eSjoerg namespace {
155706f32e7eSjoerg 
155806f32e7eSjoerg // Helper functions for implementing IsSubString() and IsNotSubstring().
155906f32e7eSjoerg 
1560*da58b97aSjoerg // This group of overloaded functions return true if and only if needle
1561*da58b97aSjoerg // is a substring of haystack.  NULL is considered a substring of
1562*da58b97aSjoerg // itself only.
156306f32e7eSjoerg 
IsSubstringPred(const char * needle,const char * haystack)156406f32e7eSjoerg bool IsSubstringPred(const char* needle, const char* haystack) {
1565*da58b97aSjoerg   if (needle == nullptr || haystack == nullptr) return needle == haystack;
156606f32e7eSjoerg 
1567*da58b97aSjoerg   return strstr(haystack, needle) != nullptr;
156806f32e7eSjoerg }
156906f32e7eSjoerg 
IsSubstringPred(const wchar_t * needle,const wchar_t * haystack)157006f32e7eSjoerg bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
1571*da58b97aSjoerg   if (needle == nullptr || haystack == nullptr) return needle == haystack;
157206f32e7eSjoerg 
1573*da58b97aSjoerg   return wcsstr(haystack, needle) != nullptr;
157406f32e7eSjoerg }
157506f32e7eSjoerg 
157606f32e7eSjoerg // StringType here can be either ::std::string or ::std::wstring.
157706f32e7eSjoerg template <typename StringType>
IsSubstringPred(const StringType & needle,const StringType & haystack)157806f32e7eSjoerg bool IsSubstringPred(const StringType& needle,
157906f32e7eSjoerg                      const StringType& haystack) {
158006f32e7eSjoerg   return haystack.find(needle) != StringType::npos;
158106f32e7eSjoerg }
158206f32e7eSjoerg 
158306f32e7eSjoerg // This function implements either IsSubstring() or IsNotSubstring(),
158406f32e7eSjoerg // depending on the value of the expected_to_be_substring parameter.
158506f32e7eSjoerg // StringType here can be const char*, const wchar_t*, ::std::string,
158606f32e7eSjoerg // or ::std::wstring.
158706f32e7eSjoerg template <typename StringType>
IsSubstringImpl(bool expected_to_be_substring,const char * needle_expr,const char * haystack_expr,const StringType & needle,const StringType & haystack)158806f32e7eSjoerg AssertionResult IsSubstringImpl(
158906f32e7eSjoerg     bool expected_to_be_substring,
159006f32e7eSjoerg     const char* needle_expr, const char* haystack_expr,
159106f32e7eSjoerg     const StringType& needle, const StringType& haystack) {
159206f32e7eSjoerg   if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
159306f32e7eSjoerg     return AssertionSuccess();
159406f32e7eSjoerg 
159506f32e7eSjoerg   const bool is_wide_string = sizeof(needle[0]) > 1;
159606f32e7eSjoerg   const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
159706f32e7eSjoerg   return AssertionFailure()
159806f32e7eSjoerg       << "Value of: " << needle_expr << "\n"
159906f32e7eSjoerg       << "  Actual: " << begin_string_quote << needle << "\"\n"
160006f32e7eSjoerg       << "Expected: " << (expected_to_be_substring ? "" : "not ")
160106f32e7eSjoerg       << "a substring of " << haystack_expr << "\n"
160206f32e7eSjoerg       << "Which is: " << begin_string_quote << haystack << "\"";
160306f32e7eSjoerg }
160406f32e7eSjoerg 
160506f32e7eSjoerg }  // namespace
160606f32e7eSjoerg 
160706f32e7eSjoerg // IsSubstring() and IsNotSubstring() check whether needle is a
160806f32e7eSjoerg // substring of haystack (NULL is considered a substring of itself
160906f32e7eSjoerg // only), and return an appropriate error message when they fail.
161006f32e7eSjoerg 
IsSubstring(const char * needle_expr,const char * haystack_expr,const char * needle,const char * haystack)161106f32e7eSjoerg AssertionResult IsSubstring(
161206f32e7eSjoerg     const char* needle_expr, const char* haystack_expr,
161306f32e7eSjoerg     const char* needle, const char* haystack) {
161406f32e7eSjoerg   return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
161506f32e7eSjoerg }
161606f32e7eSjoerg 
IsSubstring(const char * needle_expr,const char * haystack_expr,const wchar_t * needle,const wchar_t * haystack)161706f32e7eSjoerg AssertionResult IsSubstring(
161806f32e7eSjoerg     const char* needle_expr, const char* haystack_expr,
161906f32e7eSjoerg     const wchar_t* needle, const wchar_t* haystack) {
162006f32e7eSjoerg   return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
162106f32e7eSjoerg }
162206f32e7eSjoerg 
IsNotSubstring(const char * needle_expr,const char * haystack_expr,const char * needle,const char * haystack)162306f32e7eSjoerg AssertionResult IsNotSubstring(
162406f32e7eSjoerg     const char* needle_expr, const char* haystack_expr,
162506f32e7eSjoerg     const char* needle, const char* haystack) {
162606f32e7eSjoerg   return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
162706f32e7eSjoerg }
162806f32e7eSjoerg 
IsNotSubstring(const char * needle_expr,const char * haystack_expr,const wchar_t * needle,const wchar_t * haystack)162906f32e7eSjoerg AssertionResult IsNotSubstring(
163006f32e7eSjoerg     const char* needle_expr, const char* haystack_expr,
163106f32e7eSjoerg     const wchar_t* needle, const wchar_t* haystack) {
163206f32e7eSjoerg   return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
163306f32e7eSjoerg }
163406f32e7eSjoerg 
IsSubstring(const char * needle_expr,const char * haystack_expr,const::std::string & needle,const::std::string & haystack)163506f32e7eSjoerg AssertionResult IsSubstring(
163606f32e7eSjoerg     const char* needle_expr, const char* haystack_expr,
163706f32e7eSjoerg     const ::std::string& needle, const ::std::string& haystack) {
163806f32e7eSjoerg   return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
163906f32e7eSjoerg }
164006f32e7eSjoerg 
IsNotSubstring(const char * needle_expr,const char * haystack_expr,const::std::string & needle,const::std::string & haystack)164106f32e7eSjoerg AssertionResult IsNotSubstring(
164206f32e7eSjoerg     const char* needle_expr, const char* haystack_expr,
164306f32e7eSjoerg     const ::std::string& needle, const ::std::string& haystack) {
164406f32e7eSjoerg   return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
164506f32e7eSjoerg }
164606f32e7eSjoerg 
164706f32e7eSjoerg #if GTEST_HAS_STD_WSTRING
IsSubstring(const char * needle_expr,const char * haystack_expr,const::std::wstring & needle,const::std::wstring & haystack)164806f32e7eSjoerg AssertionResult IsSubstring(
164906f32e7eSjoerg     const char* needle_expr, const char* haystack_expr,
165006f32e7eSjoerg     const ::std::wstring& needle, const ::std::wstring& haystack) {
165106f32e7eSjoerg   return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
165206f32e7eSjoerg }
165306f32e7eSjoerg 
IsNotSubstring(const char * needle_expr,const char * haystack_expr,const::std::wstring & needle,const::std::wstring & haystack)165406f32e7eSjoerg AssertionResult IsNotSubstring(
165506f32e7eSjoerg     const char* needle_expr, const char* haystack_expr,
165606f32e7eSjoerg     const ::std::wstring& needle, const ::std::wstring& haystack) {
165706f32e7eSjoerg   return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
165806f32e7eSjoerg }
165906f32e7eSjoerg #endif  // GTEST_HAS_STD_WSTRING
166006f32e7eSjoerg 
166106f32e7eSjoerg namespace internal {
166206f32e7eSjoerg 
166306f32e7eSjoerg #if GTEST_OS_WINDOWS
166406f32e7eSjoerg 
166506f32e7eSjoerg namespace {
166606f32e7eSjoerg 
166706f32e7eSjoerg // Helper function for IsHRESULT{SuccessFailure} predicates
HRESULTFailureHelper(const char * expr,const char * expected,long hr)166806f32e7eSjoerg AssertionResult HRESULTFailureHelper(const char* expr,
166906f32e7eSjoerg                                      const char* expected,
167006f32e7eSjoerg                                      long hr) {  // NOLINT
1671*da58b97aSjoerg # if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_TV_TITLE
167206f32e7eSjoerg 
167306f32e7eSjoerg   // Windows CE doesn't support FormatMessage.
167406f32e7eSjoerg   const char error_text[] = "";
167506f32e7eSjoerg 
167606f32e7eSjoerg # else
167706f32e7eSjoerg 
167806f32e7eSjoerg   // Looks up the human-readable system message for the HRESULT code
167906f32e7eSjoerg   // and since we're not passing any params to FormatMessage, we don't
168006f32e7eSjoerg   // want inserts expanded.
168106f32e7eSjoerg   const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
168206f32e7eSjoerg                        FORMAT_MESSAGE_IGNORE_INSERTS;
168306f32e7eSjoerg   const DWORD kBufSize = 4096;
168406f32e7eSjoerg   // Gets the system's human readable message string for this HRESULT.
168506f32e7eSjoerg   char error_text[kBufSize] = { '\0' };
168606f32e7eSjoerg   DWORD message_length = ::FormatMessageA(kFlags,
168706f32e7eSjoerg                                           0,   // no source, we're asking system
1688*da58b97aSjoerg                                           static_cast<DWORD>(hr),  // the error
168906f32e7eSjoerg                                           0,   // no line width restrictions
169006f32e7eSjoerg                                           error_text,  // output buffer
169106f32e7eSjoerg                                           kBufSize,    // buf size
1692*da58b97aSjoerg                                           nullptr);  // no arguments for inserts
169306f32e7eSjoerg   // Trims tailing white space (FormatMessage leaves a trailing CR-LF)
169406f32e7eSjoerg   for (; message_length && IsSpace(error_text[message_length - 1]);
169506f32e7eSjoerg           --message_length) {
169606f32e7eSjoerg     error_text[message_length - 1] = '\0';
169706f32e7eSjoerg   }
169806f32e7eSjoerg 
169906f32e7eSjoerg # endif  // GTEST_OS_WINDOWS_MOBILE
170006f32e7eSjoerg 
170106f32e7eSjoerg   const std::string error_hex("0x" + String::FormatHexInt(hr));
170206f32e7eSjoerg   return ::testing::AssertionFailure()
170306f32e7eSjoerg       << "Expected: " << expr << " " << expected << ".\n"
170406f32e7eSjoerg       << "  Actual: " << error_hex << " " << error_text << "\n";
170506f32e7eSjoerg }
170606f32e7eSjoerg 
170706f32e7eSjoerg }  // namespace
170806f32e7eSjoerg 
IsHRESULTSuccess(const char * expr,long hr)170906f32e7eSjoerg AssertionResult IsHRESULTSuccess(const char* expr, long hr) {  // NOLINT
171006f32e7eSjoerg   if (SUCCEEDED(hr)) {
171106f32e7eSjoerg     return AssertionSuccess();
171206f32e7eSjoerg   }
171306f32e7eSjoerg   return HRESULTFailureHelper(expr, "succeeds", hr);
171406f32e7eSjoerg }
171506f32e7eSjoerg 
IsHRESULTFailure(const char * expr,long hr)171606f32e7eSjoerg AssertionResult IsHRESULTFailure(const char* expr, long hr) {  // NOLINT
171706f32e7eSjoerg   if (FAILED(hr)) {
171806f32e7eSjoerg     return AssertionSuccess();
171906f32e7eSjoerg   }
172006f32e7eSjoerg   return HRESULTFailureHelper(expr, "fails", hr);
172106f32e7eSjoerg }
172206f32e7eSjoerg 
172306f32e7eSjoerg #endif  // GTEST_OS_WINDOWS
172406f32e7eSjoerg 
172506f32e7eSjoerg // Utility functions for encoding Unicode text (wide strings) in
172606f32e7eSjoerg // UTF-8.
172706f32e7eSjoerg 
172806f32e7eSjoerg // A Unicode code-point can have up to 21 bits, and is encoded in UTF-8
172906f32e7eSjoerg // like this:
173006f32e7eSjoerg //
173106f32e7eSjoerg // Code-point length   Encoding
173206f32e7eSjoerg //   0 -  7 bits       0xxxxxxx
173306f32e7eSjoerg //   8 - 11 bits       110xxxxx 10xxxxxx
173406f32e7eSjoerg //  12 - 16 bits       1110xxxx 10xxxxxx 10xxxxxx
173506f32e7eSjoerg //  17 - 21 bits       11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
173606f32e7eSjoerg 
173706f32e7eSjoerg // The maximum code-point a one-byte UTF-8 sequence can represent.
173806f32e7eSjoerg const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) <<  7) - 1;
173906f32e7eSjoerg 
174006f32e7eSjoerg // The maximum code-point a two-byte UTF-8 sequence can represent.
174106f32e7eSjoerg const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1;
174206f32e7eSjoerg 
174306f32e7eSjoerg // The maximum code-point a three-byte UTF-8 sequence can represent.
174406f32e7eSjoerg const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2*6)) - 1;
174506f32e7eSjoerg 
174606f32e7eSjoerg // The maximum code-point a four-byte UTF-8 sequence can represent.
174706f32e7eSjoerg const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3*6)) - 1;
174806f32e7eSjoerg 
174906f32e7eSjoerg // Chops off the n lowest bits from a bit pattern.  Returns the n
175006f32e7eSjoerg // lowest bits.  As a side effect, the original bit pattern will be
175106f32e7eSjoerg // shifted to the right by n bits.
ChopLowBits(UInt32 * bits,int n)175206f32e7eSjoerg inline UInt32 ChopLowBits(UInt32* bits, int n) {
175306f32e7eSjoerg   const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1);
175406f32e7eSjoerg   *bits >>= n;
175506f32e7eSjoerg   return low_bits;
175606f32e7eSjoerg }
175706f32e7eSjoerg 
175806f32e7eSjoerg // Converts a Unicode code point to a narrow string in UTF-8 encoding.
175906f32e7eSjoerg // code_point parameter is of type UInt32 because wchar_t may not be
176006f32e7eSjoerg // wide enough to contain a code point.
176106f32e7eSjoerg // If the code_point is not a valid Unicode code point
176206f32e7eSjoerg // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
176306f32e7eSjoerg // to "(Invalid Unicode 0xXXXXXXXX)".
CodePointToUtf8(UInt32 code_point)176406f32e7eSjoerg std::string CodePointToUtf8(UInt32 code_point) {
176506f32e7eSjoerg   if (code_point > kMaxCodePoint4) {
1766*da58b97aSjoerg     return "(Invalid Unicode 0x" + String::FormatHexUInt32(code_point) + ")";
176706f32e7eSjoerg   }
176806f32e7eSjoerg 
176906f32e7eSjoerg   char str[5];  // Big enough for the largest valid code point.
177006f32e7eSjoerg   if (code_point <= kMaxCodePoint1) {
177106f32e7eSjoerg     str[1] = '\0';
177206f32e7eSjoerg     str[0] = static_cast<char>(code_point);                          // 0xxxxxxx
177306f32e7eSjoerg   } else if (code_point <= kMaxCodePoint2) {
177406f32e7eSjoerg     str[2] = '\0';
177506f32e7eSjoerg     str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
177606f32e7eSjoerg     str[0] = static_cast<char>(0xC0 | code_point);                   // 110xxxxx
177706f32e7eSjoerg   } else if (code_point <= kMaxCodePoint3) {
177806f32e7eSjoerg     str[3] = '\0';
177906f32e7eSjoerg     str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
178006f32e7eSjoerg     str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
178106f32e7eSjoerg     str[0] = static_cast<char>(0xE0 | code_point);                   // 1110xxxx
178206f32e7eSjoerg   } else {  // code_point <= kMaxCodePoint4
178306f32e7eSjoerg     str[4] = '\0';
178406f32e7eSjoerg     str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
178506f32e7eSjoerg     str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
178606f32e7eSjoerg     str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
178706f32e7eSjoerg     str[0] = static_cast<char>(0xF0 | code_point);                   // 11110xxx
178806f32e7eSjoerg   }
178906f32e7eSjoerg   return str;
179006f32e7eSjoerg }
179106f32e7eSjoerg 
1792*da58b97aSjoerg // The following two functions only make sense if the system
179306f32e7eSjoerg // uses UTF-16 for wide string encoding. All supported systems
1794*da58b97aSjoerg // with 16 bit wchar_t (Windows, Cygwin) do use UTF-16.
179506f32e7eSjoerg 
179606f32e7eSjoerg // Determines if the arguments constitute UTF-16 surrogate pair
179706f32e7eSjoerg // and thus should be combined into a single Unicode code point
179806f32e7eSjoerg // using CreateCodePointFromUtf16SurrogatePair.
IsUtf16SurrogatePair(wchar_t first,wchar_t second)179906f32e7eSjoerg inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
180006f32e7eSjoerg   return sizeof(wchar_t) == 2 &&
180106f32e7eSjoerg       (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;
180206f32e7eSjoerg }
180306f32e7eSjoerg 
180406f32e7eSjoerg // Creates a Unicode code point from UTF16 surrogate pair.
CreateCodePointFromUtf16SurrogatePair(wchar_t first,wchar_t second)180506f32e7eSjoerg inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first,
180606f32e7eSjoerg                                                     wchar_t second) {
1807*da58b97aSjoerg   const auto first_u = static_cast<UInt32>(first);
1808*da58b97aSjoerg   const auto second_u = static_cast<UInt32>(second);
180906f32e7eSjoerg   const UInt32 mask = (1 << 10) - 1;
1810*da58b97aSjoerg   return (sizeof(wchar_t) == 2)
1811*da58b97aSjoerg              ? (((first_u & mask) << 10) | (second_u & mask)) + 0x10000
1812*da58b97aSjoerg              :
181306f32e7eSjoerg              // This function should not be called when the condition is
181406f32e7eSjoerg              // false, but we provide a sensible default in case it is.
1815*da58b97aSjoerg              first_u;
181606f32e7eSjoerg }
181706f32e7eSjoerg 
181806f32e7eSjoerg // Converts a wide string to a narrow string in UTF-8 encoding.
181906f32e7eSjoerg // The wide string is assumed to have the following encoding:
1820*da58b97aSjoerg //   UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin)
182106f32e7eSjoerg //   UTF-32 if sizeof(wchar_t) == 4 (on Linux)
182206f32e7eSjoerg // Parameter str points to a null-terminated wide string.
182306f32e7eSjoerg // Parameter num_chars may additionally limit the number
182406f32e7eSjoerg // of wchar_t characters processed. -1 is used when the entire string
182506f32e7eSjoerg // should be processed.
182606f32e7eSjoerg // If the string contains code points that are not valid Unicode code points
182706f32e7eSjoerg // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
182806f32e7eSjoerg // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
182906f32e7eSjoerg // and contains invalid UTF-16 surrogate pairs, values in those pairs
183006f32e7eSjoerg // will be encoded as individual Unicode characters from Basic Normal Plane.
WideStringToUtf8(const wchar_t * str,int num_chars)183106f32e7eSjoerg std::string WideStringToUtf8(const wchar_t* str, int num_chars) {
183206f32e7eSjoerg   if (num_chars == -1)
183306f32e7eSjoerg     num_chars = static_cast<int>(wcslen(str));
183406f32e7eSjoerg 
183506f32e7eSjoerg   ::std::stringstream stream;
183606f32e7eSjoerg   for (int i = 0; i < num_chars; ++i) {
183706f32e7eSjoerg     UInt32 unicode_code_point;
183806f32e7eSjoerg 
183906f32e7eSjoerg     if (str[i] == L'\0') {
184006f32e7eSjoerg       break;
184106f32e7eSjoerg     } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
184206f32e7eSjoerg       unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i],
184306f32e7eSjoerg                                                                  str[i + 1]);
184406f32e7eSjoerg       i++;
184506f32e7eSjoerg     } else {
184606f32e7eSjoerg       unicode_code_point = static_cast<UInt32>(str[i]);
184706f32e7eSjoerg     }
184806f32e7eSjoerg 
184906f32e7eSjoerg     stream << CodePointToUtf8(unicode_code_point);
185006f32e7eSjoerg   }
185106f32e7eSjoerg   return StringStreamToString(&stream);
185206f32e7eSjoerg }
185306f32e7eSjoerg 
185406f32e7eSjoerg // Converts a wide C string to an std::string using the UTF-8 encoding.
185506f32e7eSjoerg // NULL will be converted to "(null)".
ShowWideCString(const wchar_t * wide_c_str)185606f32e7eSjoerg std::string String::ShowWideCString(const wchar_t * wide_c_str) {
1857*da58b97aSjoerg   if (wide_c_str == nullptr) return "(null)";
185806f32e7eSjoerg 
185906f32e7eSjoerg   return internal::WideStringToUtf8(wide_c_str, -1);
186006f32e7eSjoerg }
186106f32e7eSjoerg 
1862*da58b97aSjoerg // Compares two wide C strings.  Returns true if and only if they have the
1863*da58b97aSjoerg // same content.
186406f32e7eSjoerg //
186506f32e7eSjoerg // Unlike wcscmp(), this function can handle NULL argument(s).  A NULL
186606f32e7eSjoerg // C string is considered different to any non-NULL C string,
186706f32e7eSjoerg // including the empty string.
WideCStringEquals(const wchar_t * lhs,const wchar_t * rhs)186806f32e7eSjoerg bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {
1869*da58b97aSjoerg   if (lhs == nullptr) return rhs == nullptr;
187006f32e7eSjoerg 
1871*da58b97aSjoerg   if (rhs == nullptr) return false;
187206f32e7eSjoerg 
187306f32e7eSjoerg   return wcscmp(lhs, rhs) == 0;
187406f32e7eSjoerg }
187506f32e7eSjoerg 
187606f32e7eSjoerg // Helper function for *_STREQ on wide strings.
CmpHelperSTREQ(const char * lhs_expression,const char * rhs_expression,const wchar_t * lhs,const wchar_t * rhs)187706f32e7eSjoerg AssertionResult CmpHelperSTREQ(const char* lhs_expression,
187806f32e7eSjoerg                                const char* rhs_expression,
187906f32e7eSjoerg                                const wchar_t* lhs,
188006f32e7eSjoerg                                const wchar_t* rhs) {
188106f32e7eSjoerg   if (String::WideCStringEquals(lhs, rhs)) {
188206f32e7eSjoerg     return AssertionSuccess();
188306f32e7eSjoerg   }
188406f32e7eSjoerg 
188506f32e7eSjoerg   return EqFailure(lhs_expression,
188606f32e7eSjoerg                    rhs_expression,
188706f32e7eSjoerg                    PrintToString(lhs),
188806f32e7eSjoerg                    PrintToString(rhs),
188906f32e7eSjoerg                    false);
189006f32e7eSjoerg }
189106f32e7eSjoerg 
189206f32e7eSjoerg // Helper function for *_STRNE on wide strings.
CmpHelperSTRNE(const char * s1_expression,const char * s2_expression,const wchar_t * s1,const wchar_t * s2)189306f32e7eSjoerg AssertionResult CmpHelperSTRNE(const char* s1_expression,
189406f32e7eSjoerg                                const char* s2_expression,
189506f32e7eSjoerg                                const wchar_t* s1,
189606f32e7eSjoerg                                const wchar_t* s2) {
189706f32e7eSjoerg   if (!String::WideCStringEquals(s1, s2)) {
189806f32e7eSjoerg     return AssertionSuccess();
189906f32e7eSjoerg   }
190006f32e7eSjoerg 
190106f32e7eSjoerg   return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
190206f32e7eSjoerg                             << s2_expression << "), actual: "
190306f32e7eSjoerg                             << PrintToString(s1)
190406f32e7eSjoerg                             << " vs " << PrintToString(s2);
190506f32e7eSjoerg }
190606f32e7eSjoerg 
1907*da58b97aSjoerg // Compares two C strings, ignoring case.  Returns true if and only if they have
190806f32e7eSjoerg // the same content.
190906f32e7eSjoerg //
191006f32e7eSjoerg // Unlike strcasecmp(), this function can handle NULL argument(s).  A
191106f32e7eSjoerg // NULL C string is considered different to any non-NULL C string,
191206f32e7eSjoerg // including the empty string.
CaseInsensitiveCStringEquals(const char * lhs,const char * rhs)191306f32e7eSjoerg bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) {
1914*da58b97aSjoerg   if (lhs == nullptr) return rhs == nullptr;
1915*da58b97aSjoerg   if (rhs == nullptr) return false;
191606f32e7eSjoerg   return posix::StrCaseCmp(lhs, rhs) == 0;
191706f32e7eSjoerg }
191806f32e7eSjoerg 
1919*da58b97aSjoerg // Compares two wide C strings, ignoring case.  Returns true if and only if they
192006f32e7eSjoerg // have the same content.
192106f32e7eSjoerg //
192206f32e7eSjoerg // Unlike wcscasecmp(), this function can handle NULL argument(s).
192306f32e7eSjoerg // A NULL C string is considered different to any non-NULL wide C string,
192406f32e7eSjoerg // including the empty string.
192506f32e7eSjoerg // NB: The implementations on different platforms slightly differ.
192606f32e7eSjoerg // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
192706f32e7eSjoerg // environment variable. On GNU platform this method uses wcscasecmp
192806f32e7eSjoerg // which compares according to LC_CTYPE category of the current locale.
192906f32e7eSjoerg // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
193006f32e7eSjoerg // current locale.
CaseInsensitiveWideCStringEquals(const wchar_t * lhs,const wchar_t * rhs)193106f32e7eSjoerg bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
193206f32e7eSjoerg                                               const wchar_t* rhs) {
1933*da58b97aSjoerg   if (lhs == nullptr) return rhs == nullptr;
193406f32e7eSjoerg 
1935*da58b97aSjoerg   if (rhs == nullptr) return false;
193606f32e7eSjoerg 
193706f32e7eSjoerg #if GTEST_OS_WINDOWS
193806f32e7eSjoerg   return _wcsicmp(lhs, rhs) == 0;
193906f32e7eSjoerg #elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID
194006f32e7eSjoerg   return wcscasecmp(lhs, rhs) == 0;
194106f32e7eSjoerg #else
194206f32e7eSjoerg   // Android, Mac OS X and Cygwin don't define wcscasecmp.
194306f32e7eSjoerg   // Other unknown OSes may not define it either.
194406f32e7eSjoerg   wint_t left, right;
194506f32e7eSjoerg   do {
1946*da58b97aSjoerg     left = towlower(static_cast<wint_t>(*lhs++));
1947*da58b97aSjoerg     right = towlower(static_cast<wint_t>(*rhs++));
194806f32e7eSjoerg   } while (left && left == right);
194906f32e7eSjoerg   return left == right;
195006f32e7eSjoerg #endif  // OS selector
195106f32e7eSjoerg }
195206f32e7eSjoerg 
1953*da58b97aSjoerg // Returns true if and only if str ends with the given suffix, ignoring case.
195406f32e7eSjoerg // Any string is considered to end with an empty suffix.
EndsWithCaseInsensitive(const std::string & str,const std::string & suffix)195506f32e7eSjoerg bool String::EndsWithCaseInsensitive(
195606f32e7eSjoerg     const std::string& str, const std::string& suffix) {
195706f32e7eSjoerg   const size_t str_len = str.length();
195806f32e7eSjoerg   const size_t suffix_len = suffix.length();
195906f32e7eSjoerg   return (str_len >= suffix_len) &&
196006f32e7eSjoerg          CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len,
196106f32e7eSjoerg                                       suffix.c_str());
196206f32e7eSjoerg }
196306f32e7eSjoerg 
196406f32e7eSjoerg // Formats an int value as "%02d".
FormatIntWidth2(int value)196506f32e7eSjoerg std::string String::FormatIntWidth2(int value) {
196606f32e7eSjoerg   std::stringstream ss;
196706f32e7eSjoerg   ss << std::setfill('0') << std::setw(2) << value;
196806f32e7eSjoerg   return ss.str();
196906f32e7eSjoerg }
197006f32e7eSjoerg 
197106f32e7eSjoerg // Formats an int value as "%X".
FormatHexUInt32(UInt32 value)1972*da58b97aSjoerg std::string String::FormatHexUInt32(UInt32 value) {
197306f32e7eSjoerg   std::stringstream ss;
197406f32e7eSjoerg   ss << std::hex << std::uppercase << value;
197506f32e7eSjoerg   return ss.str();
197606f32e7eSjoerg }
197706f32e7eSjoerg 
1978*da58b97aSjoerg // Formats an int value as "%X".
FormatHexInt(int value)1979*da58b97aSjoerg std::string String::FormatHexInt(int value) {
1980*da58b97aSjoerg   return FormatHexUInt32(static_cast<UInt32>(value));
1981*da58b97aSjoerg }
1982*da58b97aSjoerg 
198306f32e7eSjoerg // Formats a byte as "%02X".
FormatByte(unsigned char value)198406f32e7eSjoerg std::string String::FormatByte(unsigned char value) {
198506f32e7eSjoerg   std::stringstream ss;
198606f32e7eSjoerg   ss << std::setfill('0') << std::setw(2) << std::hex << std::uppercase
198706f32e7eSjoerg      << static_cast<unsigned int>(value);
198806f32e7eSjoerg   return ss.str();
198906f32e7eSjoerg }
199006f32e7eSjoerg 
199106f32e7eSjoerg // Converts the buffer in a stringstream to an std::string, converting NUL
199206f32e7eSjoerg // bytes to "\\0" along the way.
StringStreamToString(::std::stringstream * ss)199306f32e7eSjoerg std::string StringStreamToString(::std::stringstream* ss) {
199406f32e7eSjoerg   const ::std::string& str = ss->str();
199506f32e7eSjoerg   const char* const start = str.c_str();
199606f32e7eSjoerg   const char* const end = start + str.length();
199706f32e7eSjoerg 
199806f32e7eSjoerg   std::string result;
1999*da58b97aSjoerg   result.reserve(static_cast<size_t>(2 * (end - start)));
200006f32e7eSjoerg   for (const char* ch = start; ch != end; ++ch) {
200106f32e7eSjoerg     if (*ch == '\0') {
200206f32e7eSjoerg       result += "\\0";  // Replaces NUL with "\\0";
200306f32e7eSjoerg     } else {
200406f32e7eSjoerg       result += *ch;
200506f32e7eSjoerg     }
200606f32e7eSjoerg   }
200706f32e7eSjoerg 
200806f32e7eSjoerg   return result;
200906f32e7eSjoerg }
201006f32e7eSjoerg 
201106f32e7eSjoerg // Appends the user-supplied message to the Google-Test-generated message.
AppendUserMessage(const std::string & gtest_msg,const Message & user_msg)201206f32e7eSjoerg std::string AppendUserMessage(const std::string& gtest_msg,
201306f32e7eSjoerg                               const Message& user_msg) {
201406f32e7eSjoerg   // Appends the user message if it's non-empty.
201506f32e7eSjoerg   const std::string user_msg_string = user_msg.GetString();
201606f32e7eSjoerg   if (user_msg_string.empty()) {
201706f32e7eSjoerg     return gtest_msg;
201806f32e7eSjoerg   }
201906f32e7eSjoerg 
202006f32e7eSjoerg   return gtest_msg + "\n" + user_msg_string;
202106f32e7eSjoerg }
202206f32e7eSjoerg 
202306f32e7eSjoerg }  // namespace internal
202406f32e7eSjoerg 
202506f32e7eSjoerg // class TestResult
202606f32e7eSjoerg 
202706f32e7eSjoerg // Creates an empty TestResult.
TestResult()202806f32e7eSjoerg TestResult::TestResult()
2029*da58b97aSjoerg     : death_test_count_(0), start_timestamp_(0), elapsed_time_(0) {}
203006f32e7eSjoerg 
203106f32e7eSjoerg // D'tor.
~TestResult()203206f32e7eSjoerg TestResult::~TestResult() {
203306f32e7eSjoerg }
203406f32e7eSjoerg 
203506f32e7eSjoerg // Returns the i-th test part result among all the results. i can
203606f32e7eSjoerg // range from 0 to total_part_count() - 1. If i is not in that range,
203706f32e7eSjoerg // aborts the program.
GetTestPartResult(int i) const203806f32e7eSjoerg const TestPartResult& TestResult::GetTestPartResult(int i) const {
203906f32e7eSjoerg   if (i < 0 || i >= total_part_count())
204006f32e7eSjoerg     internal::posix::Abort();
2041*da58b97aSjoerg   return test_part_results_.at(static_cast<size_t>(i));
204206f32e7eSjoerg }
204306f32e7eSjoerg 
204406f32e7eSjoerg // Returns the i-th test property. i can range from 0 to
204506f32e7eSjoerg // test_property_count() - 1. If i is not in that range, aborts the
204606f32e7eSjoerg // program.
GetTestProperty(int i) const204706f32e7eSjoerg const TestProperty& TestResult::GetTestProperty(int i) const {
204806f32e7eSjoerg   if (i < 0 || i >= test_property_count())
204906f32e7eSjoerg     internal::posix::Abort();
2050*da58b97aSjoerg   return test_properties_.at(static_cast<size_t>(i));
205106f32e7eSjoerg }
205206f32e7eSjoerg 
205306f32e7eSjoerg // Clears the test part results.
ClearTestPartResults()205406f32e7eSjoerg void TestResult::ClearTestPartResults() {
205506f32e7eSjoerg   test_part_results_.clear();
205606f32e7eSjoerg }
205706f32e7eSjoerg 
205806f32e7eSjoerg // Adds a test part result to the list.
AddTestPartResult(const TestPartResult & test_part_result)205906f32e7eSjoerg void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
206006f32e7eSjoerg   test_part_results_.push_back(test_part_result);
206106f32e7eSjoerg }
206206f32e7eSjoerg 
206306f32e7eSjoerg // Adds a test property to the list. If a property with the same key as the
206406f32e7eSjoerg // supplied property is already represented, the value of this test_property
206506f32e7eSjoerg // replaces the old value for that key.
RecordProperty(const std::string & xml_element,const TestProperty & test_property)206606f32e7eSjoerg void TestResult::RecordProperty(const std::string& xml_element,
206706f32e7eSjoerg                                 const TestProperty& test_property) {
206806f32e7eSjoerg   if (!ValidateTestProperty(xml_element, test_property)) {
206906f32e7eSjoerg     return;
207006f32e7eSjoerg   }
207106f32e7eSjoerg   internal::MutexLock lock(&test_properites_mutex_);
207206f32e7eSjoerg   const std::vector<TestProperty>::iterator property_with_matching_key =
207306f32e7eSjoerg       std::find_if(test_properties_.begin(), test_properties_.end(),
207406f32e7eSjoerg                    internal::TestPropertyKeyIs(test_property.key()));
207506f32e7eSjoerg   if (property_with_matching_key == test_properties_.end()) {
207606f32e7eSjoerg     test_properties_.push_back(test_property);
207706f32e7eSjoerg     return;
207806f32e7eSjoerg   }
207906f32e7eSjoerg   property_with_matching_key->SetValue(test_property.value());
208006f32e7eSjoerg }
208106f32e7eSjoerg 
208206f32e7eSjoerg // The list of reserved attributes used in the <testsuites> element of XML
208306f32e7eSjoerg // output.
208406f32e7eSjoerg static const char* const kReservedTestSuitesAttributes[] = {
208506f32e7eSjoerg   "disabled",
208606f32e7eSjoerg   "errors",
208706f32e7eSjoerg   "failures",
208806f32e7eSjoerg   "name",
208906f32e7eSjoerg   "random_seed",
209006f32e7eSjoerg   "tests",
209106f32e7eSjoerg   "time",
209206f32e7eSjoerg   "timestamp"
209306f32e7eSjoerg };
209406f32e7eSjoerg 
209506f32e7eSjoerg // The list of reserved attributes used in the <testsuite> element of XML
209606f32e7eSjoerg // output.
209706f32e7eSjoerg static const char* const kReservedTestSuiteAttributes[] = {
2098*da58b97aSjoerg     "disabled", "errors", "failures", "name", "tests", "time", "timestamp"};
209906f32e7eSjoerg 
210006f32e7eSjoerg // The list of reserved attributes used in the <testcase> element of XML output.
210106f32e7eSjoerg static const char* const kReservedTestCaseAttributes[] = {
2102*da58b97aSjoerg     "classname",   "name", "status", "time",  "type_param",
2103*da58b97aSjoerg     "value_param", "file", "line"};
2104*da58b97aSjoerg 
2105*da58b97aSjoerg // Use a slightly different set for allowed output to ensure existing tests can
2106*da58b97aSjoerg // still RecordProperty("result") or "RecordProperty(timestamp")
2107*da58b97aSjoerg static const char* const kReservedOutputTestCaseAttributes[] = {
2108*da58b97aSjoerg     "classname",   "name", "status", "time",   "type_param",
2109*da58b97aSjoerg     "value_param", "file", "line",   "result", "timestamp"};
211006f32e7eSjoerg 
211106f32e7eSjoerg template <int kSize>
ArrayAsVector(const char * const (& array)[kSize])211206f32e7eSjoerg std::vector<std::string> ArrayAsVector(const char* const (&array)[kSize]) {
211306f32e7eSjoerg   return std::vector<std::string>(array, array + kSize);
211406f32e7eSjoerg }
211506f32e7eSjoerg 
GetReservedAttributesForElement(const std::string & xml_element)211606f32e7eSjoerg static std::vector<std::string> GetReservedAttributesForElement(
211706f32e7eSjoerg     const std::string& xml_element) {
211806f32e7eSjoerg   if (xml_element == "testsuites") {
211906f32e7eSjoerg     return ArrayAsVector(kReservedTestSuitesAttributes);
212006f32e7eSjoerg   } else if (xml_element == "testsuite") {
212106f32e7eSjoerg     return ArrayAsVector(kReservedTestSuiteAttributes);
212206f32e7eSjoerg   } else if (xml_element == "testcase") {
212306f32e7eSjoerg     return ArrayAsVector(kReservedTestCaseAttributes);
212406f32e7eSjoerg   } else {
212506f32e7eSjoerg     GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element;
212606f32e7eSjoerg   }
212706f32e7eSjoerg   // This code is unreachable but some compilers may not realizes that.
212806f32e7eSjoerg   return std::vector<std::string>();
212906f32e7eSjoerg }
213006f32e7eSjoerg 
2131*da58b97aSjoerg // TODO(jdesprez): Merge the two getReserved attributes once skip is improved
GetReservedOutputAttributesForElement(const std::string & xml_element)2132*da58b97aSjoerg static std::vector<std::string> GetReservedOutputAttributesForElement(
2133*da58b97aSjoerg     const std::string& xml_element) {
2134*da58b97aSjoerg   if (xml_element == "testsuites") {
2135*da58b97aSjoerg     return ArrayAsVector(kReservedTestSuitesAttributes);
2136*da58b97aSjoerg   } else if (xml_element == "testsuite") {
2137*da58b97aSjoerg     return ArrayAsVector(kReservedTestSuiteAttributes);
2138*da58b97aSjoerg   } else if (xml_element == "testcase") {
2139*da58b97aSjoerg     return ArrayAsVector(kReservedOutputTestCaseAttributes);
2140*da58b97aSjoerg   } else {
2141*da58b97aSjoerg     GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element;
2142*da58b97aSjoerg   }
2143*da58b97aSjoerg   // This code is unreachable but some compilers may not realizes that.
2144*da58b97aSjoerg   return std::vector<std::string>();
2145*da58b97aSjoerg }
2146*da58b97aSjoerg 
FormatWordList(const std::vector<std::string> & words)214706f32e7eSjoerg static std::string FormatWordList(const std::vector<std::string>& words) {
214806f32e7eSjoerg   Message word_list;
214906f32e7eSjoerg   for (size_t i = 0; i < words.size(); ++i) {
215006f32e7eSjoerg     if (i > 0 && words.size() > 2) {
215106f32e7eSjoerg       word_list << ", ";
215206f32e7eSjoerg     }
215306f32e7eSjoerg     if (i == words.size() - 1) {
215406f32e7eSjoerg       word_list << "and ";
215506f32e7eSjoerg     }
215606f32e7eSjoerg     word_list << "'" << words[i] << "'";
215706f32e7eSjoerg   }
215806f32e7eSjoerg   return word_list.GetString();
215906f32e7eSjoerg }
216006f32e7eSjoerg 
ValidateTestPropertyName(const std::string & property_name,const std::vector<std::string> & reserved_names)2161*da58b97aSjoerg static bool ValidateTestPropertyName(
2162*da58b97aSjoerg     const std::string& property_name,
216306f32e7eSjoerg     const std::vector<std::string>& reserved_names) {
216406f32e7eSjoerg   if (std::find(reserved_names.begin(), reserved_names.end(), property_name) !=
216506f32e7eSjoerg           reserved_names.end()) {
216606f32e7eSjoerg     ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name
216706f32e7eSjoerg                   << " (" << FormatWordList(reserved_names)
216806f32e7eSjoerg                   << " are reserved by " << GTEST_NAME_ << ")";
216906f32e7eSjoerg     return false;
217006f32e7eSjoerg   }
217106f32e7eSjoerg   return true;
217206f32e7eSjoerg }
217306f32e7eSjoerg 
217406f32e7eSjoerg // Adds a failure if the key is a reserved attribute of the element named
217506f32e7eSjoerg // xml_element.  Returns true if the property is valid.
ValidateTestProperty(const std::string & xml_element,const TestProperty & test_property)217606f32e7eSjoerg bool TestResult::ValidateTestProperty(const std::string& xml_element,
217706f32e7eSjoerg                                       const TestProperty& test_property) {
217806f32e7eSjoerg   return ValidateTestPropertyName(test_property.key(),
217906f32e7eSjoerg                                   GetReservedAttributesForElement(xml_element));
218006f32e7eSjoerg }
218106f32e7eSjoerg 
218206f32e7eSjoerg // Clears the object.
Clear()218306f32e7eSjoerg void TestResult::Clear() {
218406f32e7eSjoerg   test_part_results_.clear();
218506f32e7eSjoerg   test_properties_.clear();
218606f32e7eSjoerg   death_test_count_ = 0;
218706f32e7eSjoerg   elapsed_time_ = 0;
218806f32e7eSjoerg }
218906f32e7eSjoerg 
2190*da58b97aSjoerg // Returns true off the test part was skipped.
TestPartSkipped(const TestPartResult & result)2191*da58b97aSjoerg static bool TestPartSkipped(const TestPartResult& result) {
2192*da58b97aSjoerg   return result.skipped();
2193*da58b97aSjoerg }
2194*da58b97aSjoerg 
2195*da58b97aSjoerg // Returns true if and only if the test was skipped.
Skipped() const2196*da58b97aSjoerg bool TestResult::Skipped() const {
2197*da58b97aSjoerg   return !Failed() && CountIf(test_part_results_, TestPartSkipped) > 0;
2198*da58b97aSjoerg }
2199*da58b97aSjoerg 
2200*da58b97aSjoerg // Returns true if and only if the test failed.
Failed() const220106f32e7eSjoerg bool TestResult::Failed() const {
220206f32e7eSjoerg   for (int i = 0; i < total_part_count(); ++i) {
220306f32e7eSjoerg     if (GetTestPartResult(i).failed())
220406f32e7eSjoerg       return true;
220506f32e7eSjoerg   }
220606f32e7eSjoerg   return false;
220706f32e7eSjoerg }
220806f32e7eSjoerg 
2209*da58b97aSjoerg // Returns true if and only if the test part fatally failed.
TestPartFatallyFailed(const TestPartResult & result)221006f32e7eSjoerg static bool TestPartFatallyFailed(const TestPartResult& result) {
221106f32e7eSjoerg   return result.fatally_failed();
221206f32e7eSjoerg }
221306f32e7eSjoerg 
2214*da58b97aSjoerg // Returns true if and only if the test fatally failed.
HasFatalFailure() const221506f32e7eSjoerg bool TestResult::HasFatalFailure() const {
221606f32e7eSjoerg   return CountIf(test_part_results_, TestPartFatallyFailed) > 0;
221706f32e7eSjoerg }
221806f32e7eSjoerg 
2219*da58b97aSjoerg // Returns true if and only if the test part non-fatally failed.
TestPartNonfatallyFailed(const TestPartResult & result)222006f32e7eSjoerg static bool TestPartNonfatallyFailed(const TestPartResult& result) {
222106f32e7eSjoerg   return result.nonfatally_failed();
222206f32e7eSjoerg }
222306f32e7eSjoerg 
2224*da58b97aSjoerg // Returns true if and only if the test has a non-fatal failure.
HasNonfatalFailure() const222506f32e7eSjoerg bool TestResult::HasNonfatalFailure() const {
222606f32e7eSjoerg   return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0;
222706f32e7eSjoerg }
222806f32e7eSjoerg 
222906f32e7eSjoerg // Gets the number of all test parts.  This is the sum of the number
223006f32e7eSjoerg // of successful test parts and the number of failed test parts.
total_part_count() const223106f32e7eSjoerg int TestResult::total_part_count() const {
223206f32e7eSjoerg   return static_cast<int>(test_part_results_.size());
223306f32e7eSjoerg }
223406f32e7eSjoerg 
223506f32e7eSjoerg // Returns the number of the test properties.
test_property_count() const223606f32e7eSjoerg int TestResult::test_property_count() const {
223706f32e7eSjoerg   return static_cast<int>(test_properties_.size());
223806f32e7eSjoerg }
223906f32e7eSjoerg 
224006f32e7eSjoerg // class Test
224106f32e7eSjoerg 
224206f32e7eSjoerg // Creates a Test object.
224306f32e7eSjoerg 
224406f32e7eSjoerg // The c'tor saves the states of all flags.
Test()224506f32e7eSjoerg Test::Test()
224606f32e7eSjoerg     : gtest_flag_saver_(new GTEST_FLAG_SAVER_) {
224706f32e7eSjoerg }
224806f32e7eSjoerg 
224906f32e7eSjoerg // The d'tor restores the states of all flags.  The actual work is
225006f32e7eSjoerg // done by the d'tor of the gtest_flag_saver_ field, and thus not
225106f32e7eSjoerg // visible here.
~Test()225206f32e7eSjoerg Test::~Test() {
225306f32e7eSjoerg }
225406f32e7eSjoerg 
225506f32e7eSjoerg // Sets up the test fixture.
225606f32e7eSjoerg //
225706f32e7eSjoerg // A sub-class may override this.
SetUp()225806f32e7eSjoerg void Test::SetUp() {
225906f32e7eSjoerg }
226006f32e7eSjoerg 
226106f32e7eSjoerg // Tears down the test fixture.
226206f32e7eSjoerg //
226306f32e7eSjoerg // A sub-class may override this.
TearDown()226406f32e7eSjoerg void Test::TearDown() {
226506f32e7eSjoerg }
226606f32e7eSjoerg 
226706f32e7eSjoerg // Allows user supplied key value pairs to be recorded for later output.
RecordProperty(const std::string & key,const std::string & value)226806f32e7eSjoerg void Test::RecordProperty(const std::string& key, const std::string& value) {
226906f32e7eSjoerg   UnitTest::GetInstance()->RecordProperty(key, value);
227006f32e7eSjoerg }
227106f32e7eSjoerg 
227206f32e7eSjoerg // Allows user supplied key value pairs to be recorded for later output.
RecordProperty(const std::string & key,int value)227306f32e7eSjoerg void Test::RecordProperty(const std::string& key, int value) {
227406f32e7eSjoerg   Message value_message;
227506f32e7eSjoerg   value_message << value;
227606f32e7eSjoerg   RecordProperty(key, value_message.GetString().c_str());
227706f32e7eSjoerg }
227806f32e7eSjoerg 
227906f32e7eSjoerg namespace internal {
228006f32e7eSjoerg 
ReportFailureInUnknownLocation(TestPartResult::Type result_type,const std::string & message)228106f32e7eSjoerg void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
228206f32e7eSjoerg                                     const std::string& message) {
228306f32e7eSjoerg   // This function is a friend of UnitTest and as such has access to
228406f32e7eSjoerg   // AddTestPartResult.
228506f32e7eSjoerg   UnitTest::GetInstance()->AddTestPartResult(
228606f32e7eSjoerg       result_type,
2287*da58b97aSjoerg       nullptr,  // No info about the source file where the exception occurred.
228806f32e7eSjoerg       -1,       // We have no info on which line caused the exception.
228906f32e7eSjoerg       message,
229006f32e7eSjoerg       "");  // No stack trace, either.
229106f32e7eSjoerg }
229206f32e7eSjoerg 
229306f32e7eSjoerg }  // namespace internal
229406f32e7eSjoerg 
2295*da58b97aSjoerg // Google Test requires all tests in the same test suite to use the same test
229606f32e7eSjoerg // fixture class.  This function checks if the current test has the
2297*da58b97aSjoerg // same fixture class as the first test in the current test suite.  If
229806f32e7eSjoerg // yes, it returns true; otherwise it generates a Google Test failure and
229906f32e7eSjoerg // returns false.
HasSameFixtureClass()230006f32e7eSjoerg bool Test::HasSameFixtureClass() {
230106f32e7eSjoerg   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2302*da58b97aSjoerg   const TestSuite* const test_suite = impl->current_test_suite();
230306f32e7eSjoerg 
2304*da58b97aSjoerg   // Info about the first test in the current test suite.
2305*da58b97aSjoerg   const TestInfo* const first_test_info = test_suite->test_info_list()[0];
230606f32e7eSjoerg   const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_;
230706f32e7eSjoerg   const char* const first_test_name = first_test_info->name();
230806f32e7eSjoerg 
230906f32e7eSjoerg   // Info about the current test.
231006f32e7eSjoerg   const TestInfo* const this_test_info = impl->current_test_info();
231106f32e7eSjoerg   const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_;
231206f32e7eSjoerg   const char* const this_test_name = this_test_info->name();
231306f32e7eSjoerg 
231406f32e7eSjoerg   if (this_fixture_id != first_fixture_id) {
231506f32e7eSjoerg     // Is the first test defined using TEST?
231606f32e7eSjoerg     const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();
231706f32e7eSjoerg     // Is this test defined using TEST?
231806f32e7eSjoerg     const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();
231906f32e7eSjoerg 
232006f32e7eSjoerg     if (first_is_TEST || this_is_TEST) {
2321*da58b97aSjoerg       // Both TEST and TEST_F appear in same test suite, which is incorrect.
232206f32e7eSjoerg       // Tell the user how to fix this.
232306f32e7eSjoerg 
232406f32e7eSjoerg       // Gets the name of the TEST and the name of the TEST_F.  Note
232506f32e7eSjoerg       // that first_is_TEST and this_is_TEST cannot both be true, as
232606f32e7eSjoerg       // the fixture IDs are different for the two tests.
232706f32e7eSjoerg       const char* const TEST_name =
232806f32e7eSjoerg           first_is_TEST ? first_test_name : this_test_name;
232906f32e7eSjoerg       const char* const TEST_F_name =
233006f32e7eSjoerg           first_is_TEST ? this_test_name : first_test_name;
233106f32e7eSjoerg 
233206f32e7eSjoerg       ADD_FAILURE()
2333*da58b97aSjoerg           << "All tests in the same test suite must use the same test fixture\n"
2334*da58b97aSjoerg           << "class, so mixing TEST_F and TEST in the same test suite is\n"
2335*da58b97aSjoerg           << "illegal.  In test suite " << this_test_info->test_suite_name()
233606f32e7eSjoerg           << ",\n"
233706f32e7eSjoerg           << "test " << TEST_F_name << " is defined using TEST_F but\n"
233806f32e7eSjoerg           << "test " << TEST_name << " is defined using TEST.  You probably\n"
233906f32e7eSjoerg           << "want to change the TEST to TEST_F or move it to another test\n"
234006f32e7eSjoerg           << "case.";
234106f32e7eSjoerg     } else {
234206f32e7eSjoerg       // Two fixture classes with the same name appear in two different
234306f32e7eSjoerg       // namespaces, which is not allowed. Tell the user how to fix this.
234406f32e7eSjoerg       ADD_FAILURE()
2345*da58b97aSjoerg           << "All tests in the same test suite must use the same test fixture\n"
2346*da58b97aSjoerg           << "class.  However, in test suite "
2347*da58b97aSjoerg           << this_test_info->test_suite_name() << ",\n"
2348*da58b97aSjoerg           << "you defined test " << first_test_name << " and test "
2349*da58b97aSjoerg           << this_test_name << "\n"
235006f32e7eSjoerg           << "using two different test fixture classes.  This can happen if\n"
235106f32e7eSjoerg           << "the two classes are from different namespaces or translation\n"
235206f32e7eSjoerg           << "units and have the same name.  You should probably rename one\n"
2353*da58b97aSjoerg           << "of the classes to put the tests into different test suites.";
235406f32e7eSjoerg     }
235506f32e7eSjoerg     return false;
235606f32e7eSjoerg   }
235706f32e7eSjoerg 
235806f32e7eSjoerg   return true;
235906f32e7eSjoerg }
236006f32e7eSjoerg 
236106f32e7eSjoerg #if GTEST_HAS_SEH
236206f32e7eSjoerg 
236306f32e7eSjoerg // Adds an "exception thrown" fatal failure to the current test.  This
236406f32e7eSjoerg // function returns its result via an output parameter pointer because VC++
236506f32e7eSjoerg // prohibits creation of objects with destructors on stack in functions
236606f32e7eSjoerg // using __try (see error C2712).
FormatSehExceptionMessage(DWORD exception_code,const char * location)236706f32e7eSjoerg static std::string* FormatSehExceptionMessage(DWORD exception_code,
236806f32e7eSjoerg                                               const char* location) {
236906f32e7eSjoerg   Message message;
237006f32e7eSjoerg   message << "SEH exception with code 0x" << std::setbase(16) <<
237106f32e7eSjoerg     exception_code << std::setbase(10) << " thrown in " << location << ".";
237206f32e7eSjoerg 
237306f32e7eSjoerg   return new std::string(message.GetString());
237406f32e7eSjoerg }
237506f32e7eSjoerg 
237606f32e7eSjoerg #endif  // GTEST_HAS_SEH
237706f32e7eSjoerg 
237806f32e7eSjoerg namespace internal {
237906f32e7eSjoerg 
238006f32e7eSjoerg #if GTEST_HAS_EXCEPTIONS
238106f32e7eSjoerg 
238206f32e7eSjoerg // Adds an "exception thrown" fatal failure to the current test.
FormatCxxExceptionMessage(const char * description,const char * location)238306f32e7eSjoerg static std::string FormatCxxExceptionMessage(const char* description,
238406f32e7eSjoerg                                              const char* location) {
238506f32e7eSjoerg   Message message;
2386*da58b97aSjoerg   if (description != nullptr) {
238706f32e7eSjoerg     message << "C++ exception with description \"" << description << "\"";
238806f32e7eSjoerg   } else {
238906f32e7eSjoerg     message << "Unknown C++ exception";
239006f32e7eSjoerg   }
239106f32e7eSjoerg   message << " thrown in " << location << ".";
239206f32e7eSjoerg 
239306f32e7eSjoerg   return message.GetString();
239406f32e7eSjoerg }
239506f32e7eSjoerg 
239606f32e7eSjoerg static std::string PrintTestPartResultToString(
239706f32e7eSjoerg     const TestPartResult& test_part_result);
239806f32e7eSjoerg 
GoogleTestFailureException(const TestPartResult & failure)239906f32e7eSjoerg GoogleTestFailureException::GoogleTestFailureException(
240006f32e7eSjoerg     const TestPartResult& failure)
240106f32e7eSjoerg     : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
240206f32e7eSjoerg 
240306f32e7eSjoerg #endif  // GTEST_HAS_EXCEPTIONS
240406f32e7eSjoerg 
240506f32e7eSjoerg // We put these helper functions in the internal namespace as IBM's xlC
240606f32e7eSjoerg // compiler rejects the code if they were declared static.
240706f32e7eSjoerg 
240806f32e7eSjoerg // Runs the given method and handles SEH exceptions it throws, when
240906f32e7eSjoerg // SEH is supported; returns the 0-value for type Result in case of an
241006f32e7eSjoerg // SEH exception.  (Microsoft compilers cannot handle SEH and C++
241106f32e7eSjoerg // exceptions in the same function.  Therefore, we provide a separate
241206f32e7eSjoerg // wrapper function for handling SEH exceptions.)
241306f32e7eSjoerg template <class T, typename Result>
HandleSehExceptionsInMethodIfSupported(T * object,Result (T::* method)(),const char * location)241406f32e7eSjoerg Result HandleSehExceptionsInMethodIfSupported(
241506f32e7eSjoerg     T* object, Result (T::*method)(), const char* location) {
241606f32e7eSjoerg #if GTEST_HAS_SEH
241706f32e7eSjoerg   __try {
241806f32e7eSjoerg     return (object->*method)();
241906f32e7eSjoerg   } __except (internal::UnitTestOptions::GTestShouldProcessSEH(  // NOLINT
242006f32e7eSjoerg       GetExceptionCode())) {
242106f32e7eSjoerg     // We create the exception message on the heap because VC++ prohibits
242206f32e7eSjoerg     // creation of objects with destructors on stack in functions using __try
242306f32e7eSjoerg     // (see error C2712).
242406f32e7eSjoerg     std::string* exception_message = FormatSehExceptionMessage(
242506f32e7eSjoerg         GetExceptionCode(), location);
242606f32e7eSjoerg     internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
242706f32e7eSjoerg                                              *exception_message);
242806f32e7eSjoerg     delete exception_message;
242906f32e7eSjoerg     return static_cast<Result>(0);
243006f32e7eSjoerg   }
243106f32e7eSjoerg #else
243206f32e7eSjoerg   (void)location;
243306f32e7eSjoerg   return (object->*method)();
243406f32e7eSjoerg #endif  // GTEST_HAS_SEH
243506f32e7eSjoerg }
243606f32e7eSjoerg 
243706f32e7eSjoerg // Runs the given method and catches and reports C++ and/or SEH-style
243806f32e7eSjoerg // exceptions, if they are supported; returns the 0-value for type
243906f32e7eSjoerg // Result in case of an SEH exception.
244006f32e7eSjoerg template <class T, typename Result>
HandleExceptionsInMethodIfSupported(T * object,Result (T::* method)(),const char * location)244106f32e7eSjoerg Result HandleExceptionsInMethodIfSupported(
244206f32e7eSjoerg     T* object, Result (T::*method)(), const char* location) {
244306f32e7eSjoerg   // NOTE: The user code can affect the way in which Google Test handles
244406f32e7eSjoerg   // exceptions by setting GTEST_FLAG(catch_exceptions), but only before
244506f32e7eSjoerg   // RUN_ALL_TESTS() starts. It is technically possible to check the flag
244606f32e7eSjoerg   // after the exception is caught and either report or re-throw the
244706f32e7eSjoerg   // exception based on the flag's value:
244806f32e7eSjoerg   //
244906f32e7eSjoerg   // try {
245006f32e7eSjoerg   //   // Perform the test method.
245106f32e7eSjoerg   // } catch (...) {
245206f32e7eSjoerg   //   if (GTEST_FLAG(catch_exceptions))
245306f32e7eSjoerg   //     // Report the exception as failure.
245406f32e7eSjoerg   //   else
245506f32e7eSjoerg   //     throw;  // Re-throws the original exception.
245606f32e7eSjoerg   // }
245706f32e7eSjoerg   //
245806f32e7eSjoerg   // However, the purpose of this flag is to allow the program to drop into
245906f32e7eSjoerg   // the debugger when the exception is thrown. On most platforms, once the
246006f32e7eSjoerg   // control enters the catch block, the exception origin information is
246106f32e7eSjoerg   // lost and the debugger will stop the program at the point of the
246206f32e7eSjoerg   // re-throw in this function -- instead of at the point of the original
246306f32e7eSjoerg   // throw statement in the code under test.  For this reason, we perform
246406f32e7eSjoerg   // the check early, sacrificing the ability to affect Google Test's
246506f32e7eSjoerg   // exception handling in the method where the exception is thrown.
246606f32e7eSjoerg   if (internal::GetUnitTestImpl()->catch_exceptions()) {
246706f32e7eSjoerg #if GTEST_HAS_EXCEPTIONS
246806f32e7eSjoerg     try {
246906f32e7eSjoerg       return HandleSehExceptionsInMethodIfSupported(object, method, location);
2470*da58b97aSjoerg     } catch (const AssertionException&) {  // NOLINT
2471*da58b97aSjoerg       // This failure was reported already.
247206f32e7eSjoerg     } catch (const internal::GoogleTestFailureException&) {  // NOLINT
247306f32e7eSjoerg       // This exception type can only be thrown by a failed Google
247406f32e7eSjoerg       // Test assertion with the intention of letting another testing
247506f32e7eSjoerg       // framework catch it.  Therefore we just re-throw it.
247606f32e7eSjoerg       throw;
247706f32e7eSjoerg     } catch (const std::exception& e) {  // NOLINT
247806f32e7eSjoerg       internal::ReportFailureInUnknownLocation(
247906f32e7eSjoerg           TestPartResult::kFatalFailure,
248006f32e7eSjoerg           FormatCxxExceptionMessage(e.what(), location));
248106f32e7eSjoerg     } catch (...) {  // NOLINT
248206f32e7eSjoerg       internal::ReportFailureInUnknownLocation(
248306f32e7eSjoerg           TestPartResult::kFatalFailure,
2484*da58b97aSjoerg           FormatCxxExceptionMessage(nullptr, location));
248506f32e7eSjoerg     }
248606f32e7eSjoerg     return static_cast<Result>(0);
248706f32e7eSjoerg #else
248806f32e7eSjoerg     return HandleSehExceptionsInMethodIfSupported(object, method, location);
248906f32e7eSjoerg #endif  // GTEST_HAS_EXCEPTIONS
249006f32e7eSjoerg   } else {
249106f32e7eSjoerg     return (object->*method)();
249206f32e7eSjoerg   }
249306f32e7eSjoerg }
249406f32e7eSjoerg 
249506f32e7eSjoerg }  // namespace internal
249606f32e7eSjoerg 
249706f32e7eSjoerg // Runs the test and updates the test result.
Run()249806f32e7eSjoerg void Test::Run() {
249906f32e7eSjoerg   if (!HasSameFixtureClass()) return;
250006f32e7eSjoerg 
250106f32e7eSjoerg   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
250206f32e7eSjoerg   impl->os_stack_trace_getter()->UponLeavingGTest();
250306f32e7eSjoerg   internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()");
2504*da58b97aSjoerg   // We will run the test only if SetUp() was successful and didn't call
2505*da58b97aSjoerg   // GTEST_SKIP().
2506*da58b97aSjoerg   if (!HasFatalFailure() && !IsSkipped()) {
250706f32e7eSjoerg     impl->os_stack_trace_getter()->UponLeavingGTest();
250806f32e7eSjoerg     internal::HandleExceptionsInMethodIfSupported(
250906f32e7eSjoerg         this, &Test::TestBody, "the test body");
251006f32e7eSjoerg   }
251106f32e7eSjoerg 
251206f32e7eSjoerg   // However, we want to clean up as much as possible.  Hence we will
251306f32e7eSjoerg   // always call TearDown(), even if SetUp() or the test body has
251406f32e7eSjoerg   // failed.
251506f32e7eSjoerg   impl->os_stack_trace_getter()->UponLeavingGTest();
251606f32e7eSjoerg   internal::HandleExceptionsInMethodIfSupported(
251706f32e7eSjoerg       this, &Test::TearDown, "TearDown()");
251806f32e7eSjoerg }
251906f32e7eSjoerg 
2520*da58b97aSjoerg // Returns true if and only if the current test has a fatal failure.
HasFatalFailure()252106f32e7eSjoerg bool Test::HasFatalFailure() {
252206f32e7eSjoerg   return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
252306f32e7eSjoerg }
252406f32e7eSjoerg 
2525*da58b97aSjoerg // Returns true if and only if the current test has a non-fatal failure.
HasNonfatalFailure()252606f32e7eSjoerg bool Test::HasNonfatalFailure() {
252706f32e7eSjoerg   return internal::GetUnitTestImpl()->current_test_result()->
252806f32e7eSjoerg       HasNonfatalFailure();
252906f32e7eSjoerg }
253006f32e7eSjoerg 
2531*da58b97aSjoerg // Returns true if and only if the current test was skipped.
IsSkipped()2532*da58b97aSjoerg bool Test::IsSkipped() {
2533*da58b97aSjoerg   return internal::GetUnitTestImpl()->current_test_result()->Skipped();
2534*da58b97aSjoerg }
2535*da58b97aSjoerg 
253606f32e7eSjoerg // class TestInfo
253706f32e7eSjoerg 
253806f32e7eSjoerg // Constructs a TestInfo object. It assumes ownership of the test factory
253906f32e7eSjoerg // object.
TestInfo(const std::string & a_test_suite_name,const std::string & a_name,const char * a_type_param,const char * a_value_param,internal::CodeLocation a_code_location,internal::TypeId fixture_class_id,internal::TestFactoryBase * factory)2540*da58b97aSjoerg TestInfo::TestInfo(const std::string& a_test_suite_name,
2541*da58b97aSjoerg                    const std::string& a_name, const char* a_type_param,
254206f32e7eSjoerg                    const char* a_value_param,
254306f32e7eSjoerg                    internal::CodeLocation a_code_location,
254406f32e7eSjoerg                    internal::TypeId fixture_class_id,
254506f32e7eSjoerg                    internal::TestFactoryBase* factory)
2546*da58b97aSjoerg     : test_suite_name_(a_test_suite_name),
254706f32e7eSjoerg       name_(a_name),
2548*da58b97aSjoerg       type_param_(a_type_param ? new std::string(a_type_param) : nullptr),
2549*da58b97aSjoerg       value_param_(a_value_param ? new std::string(a_value_param) : nullptr),
255006f32e7eSjoerg       location_(a_code_location),
255106f32e7eSjoerg       fixture_class_id_(fixture_class_id),
255206f32e7eSjoerg       should_run_(false),
255306f32e7eSjoerg       is_disabled_(false),
255406f32e7eSjoerg       matches_filter_(false),
255506f32e7eSjoerg       factory_(factory),
255606f32e7eSjoerg       result_() {}
255706f32e7eSjoerg 
255806f32e7eSjoerg // Destructs a TestInfo object.
~TestInfo()255906f32e7eSjoerg TestInfo::~TestInfo() { delete factory_; }
256006f32e7eSjoerg 
256106f32e7eSjoerg namespace internal {
256206f32e7eSjoerg 
256306f32e7eSjoerg // Creates a new TestInfo object and registers it with Google Test;
256406f32e7eSjoerg // returns the created object.
256506f32e7eSjoerg //
256606f32e7eSjoerg // Arguments:
256706f32e7eSjoerg //
2568*da58b97aSjoerg //   test_suite_name:   name of the test suite
256906f32e7eSjoerg //   name:             name of the test
257006f32e7eSjoerg //   type_param:       the name of the test's type parameter, or NULL if
257106f32e7eSjoerg //                     this is not a typed or a type-parameterized test.
257206f32e7eSjoerg //   value_param:      text representation of the test's value parameter,
257306f32e7eSjoerg //                     or NULL if this is not a value-parameterized test.
257406f32e7eSjoerg //   code_location:    code location where the test is defined
257506f32e7eSjoerg //   fixture_class_id: ID of the test fixture class
2576*da58b97aSjoerg //   set_up_tc:        pointer to the function that sets up the test suite
2577*da58b97aSjoerg //   tear_down_tc:     pointer to the function that tears down the test suite
257806f32e7eSjoerg //   factory:          pointer to the factory that creates a test object.
257906f32e7eSjoerg //                     The newly created TestInfo instance will assume
258006f32e7eSjoerg //                     ownership of the factory object.
MakeAndRegisterTestInfo(const char * test_suite_name,const char * name,const char * type_param,const char * value_param,CodeLocation code_location,TypeId fixture_class_id,SetUpTestSuiteFunc set_up_tc,TearDownTestSuiteFunc tear_down_tc,TestFactoryBase * factory)258106f32e7eSjoerg TestInfo* MakeAndRegisterTestInfo(
2582*da58b97aSjoerg     const char* test_suite_name, const char* name, const char* type_param,
2583*da58b97aSjoerg     const char* value_param, CodeLocation code_location,
2584*da58b97aSjoerg     TypeId fixture_class_id, SetUpTestSuiteFunc set_up_tc,
2585*da58b97aSjoerg     TearDownTestSuiteFunc tear_down_tc, TestFactoryBase* factory) {
258606f32e7eSjoerg   TestInfo* const test_info =
2587*da58b97aSjoerg       new TestInfo(test_suite_name, name, type_param, value_param,
258806f32e7eSjoerg                    code_location, fixture_class_id, factory);
258906f32e7eSjoerg   GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
259006f32e7eSjoerg   return test_info;
259106f32e7eSjoerg }
259206f32e7eSjoerg 
ReportInvalidTestSuiteType(const char * test_suite_name,CodeLocation code_location)2593*da58b97aSjoerg void ReportInvalidTestSuiteType(const char* test_suite_name,
259406f32e7eSjoerg                                 CodeLocation code_location) {
259506f32e7eSjoerg   Message errors;
259606f32e7eSjoerg   errors
2597*da58b97aSjoerg       << "Attempted redefinition of test suite " << test_suite_name << ".\n"
2598*da58b97aSjoerg       << "All tests in the same test suite must use the same test fixture\n"
2599*da58b97aSjoerg       << "class.  However, in test suite " << test_suite_name << ", you tried\n"
260006f32e7eSjoerg       << "to define a test using a fixture class different from the one\n"
260106f32e7eSjoerg       << "used earlier. This can happen if the two fixture classes are\n"
260206f32e7eSjoerg       << "from different namespaces and have the same name. You should\n"
260306f32e7eSjoerg       << "probably rename one of the classes to put the tests into different\n"
2604*da58b97aSjoerg       << "test suites.";
260506f32e7eSjoerg 
2606*da58b97aSjoerg   GTEST_LOG_(ERROR) << FormatFileLocation(code_location.file.c_str(),
2607*da58b97aSjoerg                                           code_location.line)
2608*da58b97aSjoerg                     << " " << errors.GetString();
260906f32e7eSjoerg }
261006f32e7eSjoerg }  // namespace internal
261106f32e7eSjoerg 
261206f32e7eSjoerg namespace {
261306f32e7eSjoerg 
261406f32e7eSjoerg // A predicate that checks the test name of a TestInfo against a known
261506f32e7eSjoerg // value.
261606f32e7eSjoerg //
2617*da58b97aSjoerg // This is used for implementation of the TestSuite class only.  We put
261806f32e7eSjoerg // it in the anonymous namespace to prevent polluting the outer
261906f32e7eSjoerg // namespace.
262006f32e7eSjoerg //
262106f32e7eSjoerg // TestNameIs is copyable.
262206f32e7eSjoerg class TestNameIs {
262306f32e7eSjoerg  public:
262406f32e7eSjoerg   // Constructor.
262506f32e7eSjoerg   //
262606f32e7eSjoerg   // TestNameIs has NO default constructor.
TestNameIs(const char * name)262706f32e7eSjoerg   explicit TestNameIs(const char* name)
262806f32e7eSjoerg       : name_(name) {}
262906f32e7eSjoerg 
2630*da58b97aSjoerg   // Returns true if and only if the test name of test_info matches name_.
operator ()(const TestInfo * test_info) const263106f32e7eSjoerg   bool operator()(const TestInfo * test_info) const {
263206f32e7eSjoerg     return test_info && test_info->name() == name_;
263306f32e7eSjoerg   }
263406f32e7eSjoerg 
263506f32e7eSjoerg  private:
263606f32e7eSjoerg   std::string name_;
263706f32e7eSjoerg };
263806f32e7eSjoerg 
263906f32e7eSjoerg }  // namespace
264006f32e7eSjoerg 
264106f32e7eSjoerg namespace internal {
264206f32e7eSjoerg 
264306f32e7eSjoerg // This method expands all parameterized tests registered with macros TEST_P
2644*da58b97aSjoerg // and INSTANTIATE_TEST_SUITE_P into regular tests and registers those.
264506f32e7eSjoerg // This will be done just once during the program runtime.
RegisterParameterizedTests()264606f32e7eSjoerg void UnitTestImpl::RegisterParameterizedTests() {
264706f32e7eSjoerg   if (!parameterized_tests_registered_) {
264806f32e7eSjoerg     parameterized_test_registry_.RegisterTests();
264906f32e7eSjoerg     parameterized_tests_registered_ = true;
265006f32e7eSjoerg   }
265106f32e7eSjoerg }
265206f32e7eSjoerg 
265306f32e7eSjoerg }  // namespace internal
265406f32e7eSjoerg 
265506f32e7eSjoerg // Creates the test object, runs it, records its result, and then
265606f32e7eSjoerg // deletes it.
Run()265706f32e7eSjoerg void TestInfo::Run() {
265806f32e7eSjoerg   if (!should_run_) return;
265906f32e7eSjoerg 
266006f32e7eSjoerg   // Tells UnitTest where to store test result.
266106f32e7eSjoerg   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
266206f32e7eSjoerg   impl->set_current_test_info(this);
266306f32e7eSjoerg 
266406f32e7eSjoerg   TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
266506f32e7eSjoerg 
266606f32e7eSjoerg   // Notifies the unit test event listeners that a test is about to start.
266706f32e7eSjoerg   repeater->OnTestStart(*this);
266806f32e7eSjoerg 
266906f32e7eSjoerg   const TimeInMillis start = internal::GetTimeInMillis();
267006f32e7eSjoerg 
267106f32e7eSjoerg   impl->os_stack_trace_getter()->UponLeavingGTest();
267206f32e7eSjoerg 
267306f32e7eSjoerg   // Creates the test object.
267406f32e7eSjoerg   Test* const test = internal::HandleExceptionsInMethodIfSupported(
267506f32e7eSjoerg       factory_, &internal::TestFactoryBase::CreateTest,
267606f32e7eSjoerg       "the test fixture's constructor");
267706f32e7eSjoerg 
2678*da58b97aSjoerg   // Runs the test if the constructor didn't generate a fatal failure or invoke
2679*da58b97aSjoerg   // GTEST_SKIP().
2680*da58b97aSjoerg   // Note that the object will not be null
2681*da58b97aSjoerg   if (!Test::HasFatalFailure() && !Test::IsSkipped()) {
268206f32e7eSjoerg     // This doesn't throw as all user code that can throw are wrapped into
268306f32e7eSjoerg     // exception handling code.
268406f32e7eSjoerg     test->Run();
268506f32e7eSjoerg   }
268606f32e7eSjoerg 
2687*da58b97aSjoerg   if (test != nullptr) {
268806f32e7eSjoerg     // Deletes the test object.
268906f32e7eSjoerg     impl->os_stack_trace_getter()->UponLeavingGTest();
269006f32e7eSjoerg     internal::HandleExceptionsInMethodIfSupported(
269106f32e7eSjoerg         test, &Test::DeleteSelf_, "the test fixture's destructor");
2692*da58b97aSjoerg   }
269306f32e7eSjoerg 
2694*da58b97aSjoerg   result_.set_start_timestamp(start);
269506f32e7eSjoerg   result_.set_elapsed_time(internal::GetTimeInMillis() - start);
269606f32e7eSjoerg 
269706f32e7eSjoerg   // Notifies the unit test event listener that a test has just finished.
269806f32e7eSjoerg   repeater->OnTestEnd(*this);
269906f32e7eSjoerg 
270006f32e7eSjoerg   // Tells UnitTest to stop associating assertion results to this
270106f32e7eSjoerg   // test.
2702*da58b97aSjoerg   impl->set_current_test_info(nullptr);
270306f32e7eSjoerg }
270406f32e7eSjoerg 
2705*da58b97aSjoerg // class TestSuite
270606f32e7eSjoerg 
2707*da58b97aSjoerg // Gets the number of successful tests in this test suite.
successful_test_count() const2708*da58b97aSjoerg int TestSuite::successful_test_count() const {
270906f32e7eSjoerg   return CountIf(test_info_list_, TestPassed);
271006f32e7eSjoerg }
271106f32e7eSjoerg 
2712*da58b97aSjoerg // Gets the number of successful tests in this test suite.
skipped_test_count() const2713*da58b97aSjoerg int TestSuite::skipped_test_count() const {
2714*da58b97aSjoerg   return CountIf(test_info_list_, TestSkipped);
2715*da58b97aSjoerg }
2716*da58b97aSjoerg 
2717*da58b97aSjoerg // Gets the number of failed tests in this test suite.
failed_test_count() const2718*da58b97aSjoerg int TestSuite::failed_test_count() const {
271906f32e7eSjoerg   return CountIf(test_info_list_, TestFailed);
272006f32e7eSjoerg }
272106f32e7eSjoerg 
272206f32e7eSjoerg // Gets the number of disabled tests that will be reported in the XML report.
reportable_disabled_test_count() const2723*da58b97aSjoerg int TestSuite::reportable_disabled_test_count() const {
272406f32e7eSjoerg   return CountIf(test_info_list_, TestReportableDisabled);
272506f32e7eSjoerg }
272606f32e7eSjoerg 
2727*da58b97aSjoerg // Gets the number of disabled tests in this test suite.
disabled_test_count() const2728*da58b97aSjoerg int TestSuite::disabled_test_count() const {
272906f32e7eSjoerg   return CountIf(test_info_list_, TestDisabled);
273006f32e7eSjoerg }
273106f32e7eSjoerg 
273206f32e7eSjoerg // Gets the number of tests to be printed in the XML report.
reportable_test_count() const2733*da58b97aSjoerg int TestSuite::reportable_test_count() const {
273406f32e7eSjoerg   return CountIf(test_info_list_, TestReportable);
273506f32e7eSjoerg }
273606f32e7eSjoerg 
2737*da58b97aSjoerg // Get the number of tests in this test suite that should run.
test_to_run_count() const2738*da58b97aSjoerg int TestSuite::test_to_run_count() const {
273906f32e7eSjoerg   return CountIf(test_info_list_, ShouldRunTest);
274006f32e7eSjoerg }
274106f32e7eSjoerg 
274206f32e7eSjoerg // Gets the number of all tests.
total_test_count() const2743*da58b97aSjoerg int TestSuite::total_test_count() const {
274406f32e7eSjoerg   return static_cast<int>(test_info_list_.size());
274506f32e7eSjoerg }
274606f32e7eSjoerg 
2747*da58b97aSjoerg // Creates a TestSuite with the given name.
274806f32e7eSjoerg //
274906f32e7eSjoerg // Arguments:
275006f32e7eSjoerg //
2751*da58b97aSjoerg //   name:         name of the test suite
2752*da58b97aSjoerg //   a_type_param: the name of the test suite's type parameter, or NULL if
2753*da58b97aSjoerg //                 this is not a typed or a type-parameterized test suite.
2754*da58b97aSjoerg //   set_up_tc:    pointer to the function that sets up the test suite
2755*da58b97aSjoerg //   tear_down_tc: pointer to the function that tears down the test suite
TestSuite(const char * a_name,const char * a_type_param,internal::SetUpTestSuiteFunc set_up_tc,internal::TearDownTestSuiteFunc tear_down_tc)2756*da58b97aSjoerg TestSuite::TestSuite(const char* a_name, const char* a_type_param,
2757*da58b97aSjoerg                      internal::SetUpTestSuiteFunc set_up_tc,
2758*da58b97aSjoerg                      internal::TearDownTestSuiteFunc tear_down_tc)
275906f32e7eSjoerg     : name_(a_name),
2760*da58b97aSjoerg       type_param_(a_type_param ? new std::string(a_type_param) : nullptr),
276106f32e7eSjoerg       set_up_tc_(set_up_tc),
276206f32e7eSjoerg       tear_down_tc_(tear_down_tc),
276306f32e7eSjoerg       should_run_(false),
2764*da58b97aSjoerg       start_timestamp_(0),
2765*da58b97aSjoerg       elapsed_time_(0) {}
276606f32e7eSjoerg 
2767*da58b97aSjoerg // Destructor of TestSuite.
~TestSuite()2768*da58b97aSjoerg TestSuite::~TestSuite() {
276906f32e7eSjoerg   // Deletes every Test in the collection.
277006f32e7eSjoerg   ForEach(test_info_list_, internal::Delete<TestInfo>);
277106f32e7eSjoerg }
277206f32e7eSjoerg 
277306f32e7eSjoerg // Returns the i-th test among all the tests. i can range from 0 to
277406f32e7eSjoerg // total_test_count() - 1. If i is not in that range, returns NULL.
GetTestInfo(int i) const2775*da58b97aSjoerg const TestInfo* TestSuite::GetTestInfo(int i) const {
277606f32e7eSjoerg   const int index = GetElementOr(test_indices_, i, -1);
2777*da58b97aSjoerg   return index < 0 ? nullptr : test_info_list_[static_cast<size_t>(index)];
277806f32e7eSjoerg }
277906f32e7eSjoerg 
278006f32e7eSjoerg // Returns the i-th test among all the tests. i can range from 0 to
278106f32e7eSjoerg // total_test_count() - 1. If i is not in that range, returns NULL.
GetMutableTestInfo(int i)2782*da58b97aSjoerg TestInfo* TestSuite::GetMutableTestInfo(int i) {
278306f32e7eSjoerg   const int index = GetElementOr(test_indices_, i, -1);
2784*da58b97aSjoerg   return index < 0 ? nullptr : test_info_list_[static_cast<size_t>(index)];
278506f32e7eSjoerg }
278606f32e7eSjoerg 
2787*da58b97aSjoerg // Adds a test to this test suite.  Will delete the test upon
2788*da58b97aSjoerg // destruction of the TestSuite object.
AddTestInfo(TestInfo * test_info)2789*da58b97aSjoerg void TestSuite::AddTestInfo(TestInfo* test_info) {
279006f32e7eSjoerg   test_info_list_.push_back(test_info);
279106f32e7eSjoerg   test_indices_.push_back(static_cast<int>(test_indices_.size()));
279206f32e7eSjoerg }
279306f32e7eSjoerg 
2794*da58b97aSjoerg // Runs every test in this TestSuite.
Run()2795*da58b97aSjoerg void TestSuite::Run() {
279606f32e7eSjoerg   if (!should_run_) return;
279706f32e7eSjoerg 
279806f32e7eSjoerg   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2799*da58b97aSjoerg   impl->set_current_test_suite(this);
280006f32e7eSjoerg 
280106f32e7eSjoerg   TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
280206f32e7eSjoerg 
2803*da58b97aSjoerg   // Call both legacy and the new API
2804*da58b97aSjoerg   repeater->OnTestSuiteStart(*this);
2805*da58b97aSjoerg //  Legacy API is deprecated but still available
2806*da58b97aSjoerg #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI
280706f32e7eSjoerg   repeater->OnTestCaseStart(*this);
2808*da58b97aSjoerg #endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI
2809*da58b97aSjoerg 
281006f32e7eSjoerg   impl->os_stack_trace_getter()->UponLeavingGTest();
281106f32e7eSjoerg   internal::HandleExceptionsInMethodIfSupported(
2812*da58b97aSjoerg       this, &TestSuite::RunSetUpTestSuite, "SetUpTestSuite()");
281306f32e7eSjoerg 
2814*da58b97aSjoerg   start_timestamp_ = internal::GetTimeInMillis();
281506f32e7eSjoerg   for (int i = 0; i < total_test_count(); i++) {
281606f32e7eSjoerg     GetMutableTestInfo(i)->Run();
281706f32e7eSjoerg   }
2818*da58b97aSjoerg   elapsed_time_ = internal::GetTimeInMillis() - start_timestamp_;
281906f32e7eSjoerg 
282006f32e7eSjoerg   impl->os_stack_trace_getter()->UponLeavingGTest();
282106f32e7eSjoerg   internal::HandleExceptionsInMethodIfSupported(
2822*da58b97aSjoerg       this, &TestSuite::RunTearDownTestSuite, "TearDownTestSuite()");
282306f32e7eSjoerg 
2824*da58b97aSjoerg   // Call both legacy and the new API
2825*da58b97aSjoerg   repeater->OnTestSuiteEnd(*this);
2826*da58b97aSjoerg //  Legacy API is deprecated but still available
2827*da58b97aSjoerg #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI
282806f32e7eSjoerg   repeater->OnTestCaseEnd(*this);
2829*da58b97aSjoerg #endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI
2830*da58b97aSjoerg 
2831*da58b97aSjoerg   impl->set_current_test_suite(nullptr);
283206f32e7eSjoerg }
283306f32e7eSjoerg 
2834*da58b97aSjoerg // Clears the results of all tests in this test suite.
ClearResult()2835*da58b97aSjoerg void TestSuite::ClearResult() {
283606f32e7eSjoerg   ad_hoc_test_result_.Clear();
283706f32e7eSjoerg   ForEach(test_info_list_, TestInfo::ClearTestResult);
283806f32e7eSjoerg }
283906f32e7eSjoerg 
2840*da58b97aSjoerg // Shuffles the tests in this test suite.
ShuffleTests(internal::Random * random)2841*da58b97aSjoerg void TestSuite::ShuffleTests(internal::Random* random) {
284206f32e7eSjoerg   Shuffle(random, &test_indices_);
284306f32e7eSjoerg }
284406f32e7eSjoerg 
284506f32e7eSjoerg // Restores the test order to before the first shuffle.
UnshuffleTests()2846*da58b97aSjoerg void TestSuite::UnshuffleTests() {
284706f32e7eSjoerg   for (size_t i = 0; i < test_indices_.size(); i++) {
284806f32e7eSjoerg     test_indices_[i] = static_cast<int>(i);
284906f32e7eSjoerg   }
285006f32e7eSjoerg }
285106f32e7eSjoerg 
285206f32e7eSjoerg // Formats a countable noun.  Depending on its quantity, either the
285306f32e7eSjoerg // singular form or the plural form is used. e.g.
285406f32e7eSjoerg //
285506f32e7eSjoerg // FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
285606f32e7eSjoerg // FormatCountableNoun(5, "book", "books") returns "5 books".
FormatCountableNoun(int count,const char * singular_form,const char * plural_form)285706f32e7eSjoerg static std::string FormatCountableNoun(int count,
285806f32e7eSjoerg                                        const char * singular_form,
285906f32e7eSjoerg                                        const char * plural_form) {
286006f32e7eSjoerg   return internal::StreamableToString(count) + " " +
286106f32e7eSjoerg       (count == 1 ? singular_form : plural_form);
286206f32e7eSjoerg }
286306f32e7eSjoerg 
286406f32e7eSjoerg // Formats the count of tests.
FormatTestCount(int test_count)286506f32e7eSjoerg static std::string FormatTestCount(int test_count) {
286606f32e7eSjoerg   return FormatCountableNoun(test_count, "test", "tests");
286706f32e7eSjoerg }
286806f32e7eSjoerg 
2869*da58b97aSjoerg // Formats the count of test suites.
FormatTestSuiteCount(int test_suite_count)2870*da58b97aSjoerg static std::string FormatTestSuiteCount(int test_suite_count) {
2871*da58b97aSjoerg   return FormatCountableNoun(test_suite_count, "test suite", "test suites");
287206f32e7eSjoerg }
287306f32e7eSjoerg 
287406f32e7eSjoerg // Converts a TestPartResult::Type enum to human-friendly string
287506f32e7eSjoerg // representation.  Both kNonFatalFailure and kFatalFailure are translated
287606f32e7eSjoerg // to "Failure", as the user usually doesn't care about the difference
287706f32e7eSjoerg // between the two when viewing the test result.
TestPartResultTypeToString(TestPartResult::Type type)287806f32e7eSjoerg static const char * TestPartResultTypeToString(TestPartResult::Type type) {
287906f32e7eSjoerg   switch (type) {
2880*da58b97aSjoerg     case TestPartResult::kSkip:
2881*da58b97aSjoerg       return "Skipped";
288206f32e7eSjoerg     case TestPartResult::kSuccess:
288306f32e7eSjoerg       return "Success";
288406f32e7eSjoerg 
288506f32e7eSjoerg     case TestPartResult::kNonFatalFailure:
288606f32e7eSjoerg     case TestPartResult::kFatalFailure:
288706f32e7eSjoerg #ifdef _MSC_VER
288806f32e7eSjoerg       return "error: ";
288906f32e7eSjoerg #else
289006f32e7eSjoerg       return "Failure\n";
289106f32e7eSjoerg #endif
289206f32e7eSjoerg     default:
289306f32e7eSjoerg       return "Unknown result type";
289406f32e7eSjoerg   }
289506f32e7eSjoerg }
289606f32e7eSjoerg 
289706f32e7eSjoerg namespace internal {
289806f32e7eSjoerg 
289906f32e7eSjoerg // Prints a TestPartResult to an std::string.
PrintTestPartResultToString(const TestPartResult & test_part_result)290006f32e7eSjoerg static std::string PrintTestPartResultToString(
290106f32e7eSjoerg     const TestPartResult& test_part_result) {
290206f32e7eSjoerg   return (Message()
290306f32e7eSjoerg           << internal::FormatFileLocation(test_part_result.file_name(),
290406f32e7eSjoerg                                           test_part_result.line_number())
290506f32e7eSjoerg           << " " << TestPartResultTypeToString(test_part_result.type())
290606f32e7eSjoerg           << test_part_result.message()).GetString();
290706f32e7eSjoerg }
290806f32e7eSjoerg 
290906f32e7eSjoerg // Prints a TestPartResult.
PrintTestPartResult(const TestPartResult & test_part_result)291006f32e7eSjoerg static void PrintTestPartResult(const TestPartResult& test_part_result) {
291106f32e7eSjoerg   const std::string& result =
291206f32e7eSjoerg       PrintTestPartResultToString(test_part_result);
291306f32e7eSjoerg   printf("%s\n", result.c_str());
291406f32e7eSjoerg   fflush(stdout);
291506f32e7eSjoerg   // If the test program runs in Visual Studio or a debugger, the
291606f32e7eSjoerg   // following statements add the test part result message to the Output
291706f32e7eSjoerg   // window such that the user can double-click on it to jump to the
291806f32e7eSjoerg   // corresponding source code location; otherwise they do nothing.
291906f32e7eSjoerg #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
292006f32e7eSjoerg   // We don't call OutputDebugString*() on Windows Mobile, as printing
292106f32e7eSjoerg   // to stdout is done by OutputDebugString() there already - we don't
292206f32e7eSjoerg   // want the same message printed twice.
292306f32e7eSjoerg   ::OutputDebugStringA(result.c_str());
292406f32e7eSjoerg   ::OutputDebugStringA("\n");
292506f32e7eSjoerg #endif
292606f32e7eSjoerg }
292706f32e7eSjoerg 
292806f32e7eSjoerg // class PrettyUnitTestResultPrinter
292906f32e7eSjoerg #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \
2930*da58b97aSjoerg     !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
293106f32e7eSjoerg 
293206f32e7eSjoerg // Returns the character attribute for the given color.
GetColorAttribute(GTestColor color)2933*da58b97aSjoerg static WORD GetColorAttribute(GTestColor color) {
293406f32e7eSjoerg   switch (color) {
293506f32e7eSjoerg     case COLOR_RED:    return FOREGROUND_RED;
293606f32e7eSjoerg     case COLOR_GREEN:  return FOREGROUND_GREEN;
293706f32e7eSjoerg     case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
293806f32e7eSjoerg     default:           return 0;
293906f32e7eSjoerg   }
294006f32e7eSjoerg }
294106f32e7eSjoerg 
GetBitOffset(WORD color_mask)2942*da58b97aSjoerg static int GetBitOffset(WORD color_mask) {
2943*da58b97aSjoerg   if (color_mask == 0) return 0;
2944*da58b97aSjoerg 
2945*da58b97aSjoerg   int bitOffset = 0;
2946*da58b97aSjoerg   while ((color_mask & 1) == 0) {
2947*da58b97aSjoerg     color_mask >>= 1;
2948*da58b97aSjoerg     ++bitOffset;
2949*da58b97aSjoerg   }
2950*da58b97aSjoerg   return bitOffset;
2951*da58b97aSjoerg }
2952*da58b97aSjoerg 
GetNewColor(GTestColor color,WORD old_color_attrs)2953*da58b97aSjoerg static WORD GetNewColor(GTestColor color, WORD old_color_attrs) {
2954*da58b97aSjoerg   // Let's reuse the BG
2955*da58b97aSjoerg   static const WORD background_mask = BACKGROUND_BLUE | BACKGROUND_GREEN |
2956*da58b97aSjoerg                                       BACKGROUND_RED | BACKGROUND_INTENSITY;
2957*da58b97aSjoerg   static const WORD foreground_mask = FOREGROUND_BLUE | FOREGROUND_GREEN |
2958*da58b97aSjoerg                                       FOREGROUND_RED | FOREGROUND_INTENSITY;
2959*da58b97aSjoerg   const WORD existing_bg = old_color_attrs & background_mask;
2960*da58b97aSjoerg 
2961*da58b97aSjoerg   WORD new_color =
2962*da58b97aSjoerg       GetColorAttribute(color) | existing_bg | FOREGROUND_INTENSITY;
2963*da58b97aSjoerg   static const int bg_bitOffset = GetBitOffset(background_mask);
2964*da58b97aSjoerg   static const int fg_bitOffset = GetBitOffset(foreground_mask);
2965*da58b97aSjoerg 
2966*da58b97aSjoerg   if (((new_color & background_mask) >> bg_bitOffset) ==
2967*da58b97aSjoerg       ((new_color & foreground_mask) >> fg_bitOffset)) {
2968*da58b97aSjoerg     new_color ^= FOREGROUND_INTENSITY;  // invert intensity
2969*da58b97aSjoerg   }
2970*da58b97aSjoerg   return new_color;
2971*da58b97aSjoerg }
2972*da58b97aSjoerg 
297306f32e7eSjoerg #else
297406f32e7eSjoerg 
297506f32e7eSjoerg // Returns the ANSI color code for the given color.  COLOR_DEFAULT is
297606f32e7eSjoerg // an invalid input.
GetAnsiColorCode(GTestColor color)2977*da58b97aSjoerg static const char* GetAnsiColorCode(GTestColor color) {
297806f32e7eSjoerg   switch (color) {
297906f32e7eSjoerg     case COLOR_RED:     return "1";
298006f32e7eSjoerg     case COLOR_GREEN:   return "2";
298106f32e7eSjoerg     case COLOR_YELLOW:  return "3";
2982*da58b97aSjoerg     default:
2983*da58b97aSjoerg       return nullptr;
2984*da58b97aSjoerg   }
298506f32e7eSjoerg }
298606f32e7eSjoerg 
298706f32e7eSjoerg #endif  // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
298806f32e7eSjoerg 
2989*da58b97aSjoerg // Returns true if and only if Google Test should use colors in the output.
ShouldUseColor(bool stdout_is_tty)299006f32e7eSjoerg bool ShouldUseColor(bool stdout_is_tty) {
299106f32e7eSjoerg   const char* const gtest_color = GTEST_FLAG(color).c_str();
299206f32e7eSjoerg 
299306f32e7eSjoerg   if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
2994*da58b97aSjoerg #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
299506f32e7eSjoerg     // On Windows the TERM variable is usually not set, but the
299606f32e7eSjoerg     // console there does support colors.
299706f32e7eSjoerg     return stdout_is_tty;
299806f32e7eSjoerg #else
299906f32e7eSjoerg     // On non-Windows platforms, we rely on the TERM variable.
300006f32e7eSjoerg     const char* const term = posix::GetEnv("TERM");
300106f32e7eSjoerg     const bool term_supports_color =
300206f32e7eSjoerg         String::CStringEquals(term, "xterm") ||
300306f32e7eSjoerg         String::CStringEquals(term, "xterm-color") ||
300406f32e7eSjoerg         String::CStringEquals(term, "xterm-256color") ||
300506f32e7eSjoerg         String::CStringEquals(term, "screen") ||
300606f32e7eSjoerg         String::CStringEquals(term, "screen-256color") ||
300706f32e7eSjoerg         String::CStringEquals(term, "tmux") ||
300806f32e7eSjoerg         String::CStringEquals(term, "tmux-256color") ||
300906f32e7eSjoerg         String::CStringEquals(term, "rxvt-unicode") ||
301006f32e7eSjoerg         String::CStringEquals(term, "rxvt-unicode-256color") ||
301106f32e7eSjoerg         String::CStringEquals(term, "linux") ||
301206f32e7eSjoerg         String::CStringEquals(term, "cygwin");
301306f32e7eSjoerg     return stdout_is_tty && term_supports_color;
301406f32e7eSjoerg #endif  // GTEST_OS_WINDOWS
301506f32e7eSjoerg   }
301606f32e7eSjoerg 
301706f32e7eSjoerg   return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
301806f32e7eSjoerg       String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
301906f32e7eSjoerg       String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
302006f32e7eSjoerg       String::CStringEquals(gtest_color, "1");
302106f32e7eSjoerg   // We take "yes", "true", "t", and "1" as meaning "yes".  If the
302206f32e7eSjoerg   // value is neither one of these nor "auto", we treat it as "no" to
302306f32e7eSjoerg   // be conservative.
302406f32e7eSjoerg }
302506f32e7eSjoerg 
302606f32e7eSjoerg // Helpers for printing colored strings to stdout. Note that on Windows, we
302706f32e7eSjoerg // cannot simply emit special characters and have the terminal change colors.
302806f32e7eSjoerg // This routine must actually emit the characters rather than return a string
302906f32e7eSjoerg // that would be colored when printed, as can be done on Linux.
ColoredPrintf(GTestColor color,const char * fmt,...)303006f32e7eSjoerg void ColoredPrintf(GTestColor color, const char* fmt, ...) {
303106f32e7eSjoerg   va_list args;
303206f32e7eSjoerg   va_start(args, fmt);
303306f32e7eSjoerg 
3034*da58b97aSjoerg #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_ZOS || GTEST_OS_IOS || \
3035*da58b97aSjoerg     GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT || defined(ESP_PLATFORM)
303606f32e7eSjoerg   const bool use_color = AlwaysFalse();
303706f32e7eSjoerg #else
303806f32e7eSjoerg   static const bool in_color_mode =
303906f32e7eSjoerg       ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
304006f32e7eSjoerg   const bool use_color = in_color_mode && (color != COLOR_DEFAULT);
3041*da58b97aSjoerg #endif  // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_ZOS
304206f32e7eSjoerg 
304306f32e7eSjoerg   if (!use_color) {
304406f32e7eSjoerg     vprintf(fmt, args);
304506f32e7eSjoerg     va_end(args);
304606f32e7eSjoerg     return;
304706f32e7eSjoerg   }
304806f32e7eSjoerg 
304906f32e7eSjoerg #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \
3050*da58b97aSjoerg     !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
305106f32e7eSjoerg   const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
305206f32e7eSjoerg 
305306f32e7eSjoerg   // Gets the current text color.
305406f32e7eSjoerg   CONSOLE_SCREEN_BUFFER_INFO buffer_info;
305506f32e7eSjoerg   GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
305606f32e7eSjoerg   const WORD old_color_attrs = buffer_info.wAttributes;
3057*da58b97aSjoerg   const WORD new_color = GetNewColor(color, old_color_attrs);
305806f32e7eSjoerg 
305906f32e7eSjoerg   // We need to flush the stream buffers into the console before each
306006f32e7eSjoerg   // SetConsoleTextAttribute call lest it affect the text that is already
306106f32e7eSjoerg   // printed but has not yet reached the console.
306206f32e7eSjoerg   fflush(stdout);
3063*da58b97aSjoerg   SetConsoleTextAttribute(stdout_handle, new_color);
3064*da58b97aSjoerg 
306506f32e7eSjoerg   vprintf(fmt, args);
306606f32e7eSjoerg 
306706f32e7eSjoerg   fflush(stdout);
306806f32e7eSjoerg   // Restores the text color.
306906f32e7eSjoerg   SetConsoleTextAttribute(stdout_handle, old_color_attrs);
307006f32e7eSjoerg #else
307106f32e7eSjoerg   printf("\033[0;3%sm", GetAnsiColorCode(color));
307206f32e7eSjoerg   vprintf(fmt, args);
307306f32e7eSjoerg   printf("\033[m");  // Resets the terminal to default.
307406f32e7eSjoerg #endif  // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
307506f32e7eSjoerg   va_end(args);
307606f32e7eSjoerg }
307706f32e7eSjoerg 
3078*da58b97aSjoerg // Text printed in Google Test's text output and --gtest_list_tests
307906f32e7eSjoerg // output to label the type parameter and value parameter for a test.
308006f32e7eSjoerg static const char kTypeParamLabel[] = "TypeParam";
308106f32e7eSjoerg static const char kValueParamLabel[] = "GetParam()";
308206f32e7eSjoerg 
PrintFullTestCommentIfPresent(const TestInfo & test_info)3083*da58b97aSjoerg static void PrintFullTestCommentIfPresent(const TestInfo& test_info) {
308406f32e7eSjoerg   const char* const type_param = test_info.type_param();
308506f32e7eSjoerg   const char* const value_param = test_info.value_param();
308606f32e7eSjoerg 
3087*da58b97aSjoerg   if (type_param != nullptr || value_param != nullptr) {
308806f32e7eSjoerg     printf(", where ");
3089*da58b97aSjoerg     if (type_param != nullptr) {
309006f32e7eSjoerg       printf("%s = %s", kTypeParamLabel, type_param);
3091*da58b97aSjoerg       if (value_param != nullptr) printf(" and ");
309206f32e7eSjoerg     }
3093*da58b97aSjoerg     if (value_param != nullptr) {
309406f32e7eSjoerg       printf("%s = %s", kValueParamLabel, value_param);
309506f32e7eSjoerg     }
309606f32e7eSjoerg   }
309706f32e7eSjoerg }
309806f32e7eSjoerg 
309906f32e7eSjoerg // This class implements the TestEventListener interface.
310006f32e7eSjoerg //
310106f32e7eSjoerg // Class PrettyUnitTestResultPrinter is copyable.
310206f32e7eSjoerg class PrettyUnitTestResultPrinter : public TestEventListener {
310306f32e7eSjoerg  public:
PrettyUnitTestResultPrinter()310406f32e7eSjoerg   PrettyUnitTestResultPrinter() {}
PrintTestName(const char * test_suite,const char * test)3105*da58b97aSjoerg   static void PrintTestName(const char* test_suite, const char* test) {
3106*da58b97aSjoerg     printf("%s.%s", test_suite, test);
310706f32e7eSjoerg   }
310806f32e7eSjoerg 
310906f32e7eSjoerg   // The following methods override what's in the TestEventListener class.
OnTestProgramStart(const UnitTest &)3110*da58b97aSjoerg   void OnTestProgramStart(const UnitTest& /*unit_test*/) override {}
3111*da58b97aSjoerg   void OnTestIterationStart(const UnitTest& unit_test, int iteration) override;
3112*da58b97aSjoerg   void OnEnvironmentsSetUpStart(const UnitTest& unit_test) override;
OnEnvironmentsSetUpEnd(const UnitTest &)3113*da58b97aSjoerg   void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) override {}
3114*da58b97aSjoerg #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3115*da58b97aSjoerg   void OnTestCaseStart(const TestCase& test_case) override;
3116*da58b97aSjoerg #else
3117*da58b97aSjoerg   void OnTestSuiteStart(const TestSuite& test_suite) override;
3118*da58b97aSjoerg #endif  // OnTestCaseStart
3119*da58b97aSjoerg 
3120*da58b97aSjoerg   void OnTestStart(const TestInfo& test_info) override;
3121*da58b97aSjoerg 
3122*da58b97aSjoerg   void OnTestPartResult(const TestPartResult& result) override;
3123*da58b97aSjoerg   void OnTestEnd(const TestInfo& test_info) override;
3124*da58b97aSjoerg #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3125*da58b97aSjoerg   void OnTestCaseEnd(const TestCase& test_case) override;
3126*da58b97aSjoerg #else
3127*da58b97aSjoerg   void OnTestSuiteEnd(const TestSuite& test_suite) override;
3128*da58b97aSjoerg #endif  // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3129*da58b97aSjoerg 
3130*da58b97aSjoerg   void OnEnvironmentsTearDownStart(const UnitTest& unit_test) override;
OnEnvironmentsTearDownEnd(const UnitTest &)3131*da58b97aSjoerg   void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) override {}
3132*da58b97aSjoerg   void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
OnTestProgramEnd(const UnitTest &)3133*da58b97aSjoerg   void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {}
313406f32e7eSjoerg 
313506f32e7eSjoerg  private:
313606f32e7eSjoerg   static void PrintFailedTests(const UnitTest& unit_test);
3137*da58b97aSjoerg   static void PrintSkippedTests(const UnitTest& unit_test);
313806f32e7eSjoerg };
313906f32e7eSjoerg 
314006f32e7eSjoerg   // Fired before each iteration of tests starts.
OnTestIterationStart(const UnitTest & unit_test,int iteration)314106f32e7eSjoerg void PrettyUnitTestResultPrinter::OnTestIterationStart(
314206f32e7eSjoerg     const UnitTest& unit_test, int iteration) {
314306f32e7eSjoerg   if (GTEST_FLAG(repeat) != 1)
314406f32e7eSjoerg     printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
314506f32e7eSjoerg 
314606f32e7eSjoerg   const char* const filter = GTEST_FLAG(filter).c_str();
314706f32e7eSjoerg 
314806f32e7eSjoerg   // Prints the filter if it's not *.  This reminds the user that some
314906f32e7eSjoerg   // tests may be skipped.
315006f32e7eSjoerg   if (!String::CStringEquals(filter, kUniversalFilter)) {
315106f32e7eSjoerg     ColoredPrintf(COLOR_YELLOW,
315206f32e7eSjoerg                   "Note: %s filter = %s\n", GTEST_NAME_, filter);
315306f32e7eSjoerg   }
315406f32e7eSjoerg 
315506f32e7eSjoerg   if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
315606f32e7eSjoerg     const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
315706f32e7eSjoerg     ColoredPrintf(COLOR_YELLOW,
315806f32e7eSjoerg                   "Note: This is test shard %d of %s.\n",
315906f32e7eSjoerg                   static_cast<int>(shard_index) + 1,
316006f32e7eSjoerg                   internal::posix::GetEnv(kTestTotalShards));
316106f32e7eSjoerg   }
316206f32e7eSjoerg 
316306f32e7eSjoerg   if (GTEST_FLAG(shuffle)) {
316406f32e7eSjoerg     ColoredPrintf(COLOR_YELLOW,
316506f32e7eSjoerg                   "Note: Randomizing tests' orders with a seed of %d .\n",
316606f32e7eSjoerg                   unit_test.random_seed());
316706f32e7eSjoerg   }
316806f32e7eSjoerg 
316906f32e7eSjoerg   ColoredPrintf(COLOR_GREEN,  "[==========] ");
317006f32e7eSjoerg   printf("Running %s from %s.\n",
317106f32e7eSjoerg          FormatTestCount(unit_test.test_to_run_count()).c_str(),
3172*da58b97aSjoerg          FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str());
317306f32e7eSjoerg   fflush(stdout);
317406f32e7eSjoerg }
317506f32e7eSjoerg 
OnEnvironmentsSetUpStart(const UnitTest &)317606f32e7eSjoerg void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
317706f32e7eSjoerg     const UnitTest& /*unit_test*/) {
317806f32e7eSjoerg   ColoredPrintf(COLOR_GREEN,  "[----------] ");
317906f32e7eSjoerg   printf("Global test environment set-up.\n");
318006f32e7eSjoerg   fflush(stdout);
318106f32e7eSjoerg }
318206f32e7eSjoerg 
3183*da58b97aSjoerg #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
OnTestCaseStart(const TestCase & test_case)318406f32e7eSjoerg void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {
318506f32e7eSjoerg   const std::string counts =
318606f32e7eSjoerg       FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
318706f32e7eSjoerg   ColoredPrintf(COLOR_GREEN, "[----------] ");
318806f32e7eSjoerg   printf("%s from %s", counts.c_str(), test_case.name());
3189*da58b97aSjoerg   if (test_case.type_param() == nullptr) {
319006f32e7eSjoerg     printf("\n");
319106f32e7eSjoerg   } else {
319206f32e7eSjoerg     printf(", where %s = %s\n", kTypeParamLabel, test_case.type_param());
319306f32e7eSjoerg   }
319406f32e7eSjoerg   fflush(stdout);
319506f32e7eSjoerg }
3196*da58b97aSjoerg #else
OnTestSuiteStart(const TestSuite & test_suite)3197*da58b97aSjoerg void PrettyUnitTestResultPrinter::OnTestSuiteStart(
3198*da58b97aSjoerg     const TestSuite& test_suite) {
3199*da58b97aSjoerg   const std::string counts =
3200*da58b97aSjoerg       FormatCountableNoun(test_suite.test_to_run_count(), "test", "tests");
3201*da58b97aSjoerg   ColoredPrintf(COLOR_GREEN, "[----------] ");
3202*da58b97aSjoerg   printf("%s from %s", counts.c_str(), test_suite.name());
3203*da58b97aSjoerg   if (test_suite.type_param() == nullptr) {
3204*da58b97aSjoerg     printf("\n");
3205*da58b97aSjoerg   } else {
3206*da58b97aSjoerg     printf(", where %s = %s\n", kTypeParamLabel, test_suite.type_param());
3207*da58b97aSjoerg   }
3208*da58b97aSjoerg   fflush(stdout);
3209*da58b97aSjoerg }
3210*da58b97aSjoerg #endif  // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
321106f32e7eSjoerg 
OnTestStart(const TestInfo & test_info)321206f32e7eSjoerg void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
321306f32e7eSjoerg   ColoredPrintf(COLOR_GREEN,  "[ RUN      ] ");
3214*da58b97aSjoerg   PrintTestName(test_info.test_suite_name(), test_info.name());
321506f32e7eSjoerg   printf("\n");
321606f32e7eSjoerg   fflush(stdout);
321706f32e7eSjoerg }
321806f32e7eSjoerg 
321906f32e7eSjoerg // Called after an assertion failure.
OnTestPartResult(const TestPartResult & result)322006f32e7eSjoerg void PrettyUnitTestResultPrinter::OnTestPartResult(
322106f32e7eSjoerg     const TestPartResult& result) {
3222*da58b97aSjoerg   switch (result.type()) {
3223*da58b97aSjoerg     // If the test part succeeded, or was skipped,
3224*da58b97aSjoerg     // we don't need to do anything.
3225*da58b97aSjoerg     case TestPartResult::kSkip:
3226*da58b97aSjoerg     case TestPartResult::kSuccess:
322706f32e7eSjoerg       return;
3228*da58b97aSjoerg     default:
3229*da58b97aSjoerg       // Print failure message from the assertion
3230*da58b97aSjoerg       // (e.g. expected this and got that).
323106f32e7eSjoerg       PrintTestPartResult(result);
323206f32e7eSjoerg       fflush(stdout);
323306f32e7eSjoerg   }
3234*da58b97aSjoerg }
323506f32e7eSjoerg 
OnTestEnd(const TestInfo & test_info)323606f32e7eSjoerg void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
323706f32e7eSjoerg   if (test_info.result()->Passed()) {
323806f32e7eSjoerg     ColoredPrintf(COLOR_GREEN, "[       OK ] ");
3239*da58b97aSjoerg   } else if (test_info.result()->Skipped()) {
3240*da58b97aSjoerg     ColoredPrintf(COLOR_GREEN, "[  SKIPPED ] ");
324106f32e7eSjoerg   } else {
324206f32e7eSjoerg     ColoredPrintf(COLOR_RED, "[  FAILED  ] ");
324306f32e7eSjoerg   }
3244*da58b97aSjoerg   PrintTestName(test_info.test_suite_name(), test_info.name());
324506f32e7eSjoerg   if (test_info.result()->Failed())
324606f32e7eSjoerg     PrintFullTestCommentIfPresent(test_info);
324706f32e7eSjoerg 
324806f32e7eSjoerg   if (GTEST_FLAG(print_time)) {
324906f32e7eSjoerg     printf(" (%s ms)\n", internal::StreamableToString(
325006f32e7eSjoerg            test_info.result()->elapsed_time()).c_str());
325106f32e7eSjoerg   } else {
325206f32e7eSjoerg     printf("\n");
325306f32e7eSjoerg   }
325406f32e7eSjoerg   fflush(stdout);
325506f32e7eSjoerg }
325606f32e7eSjoerg 
3257*da58b97aSjoerg #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
OnTestCaseEnd(const TestCase & test_case)325806f32e7eSjoerg void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {
325906f32e7eSjoerg   if (!GTEST_FLAG(print_time)) return;
326006f32e7eSjoerg 
326106f32e7eSjoerg   const std::string counts =
326206f32e7eSjoerg       FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
326306f32e7eSjoerg   ColoredPrintf(COLOR_GREEN, "[----------] ");
3264*da58b97aSjoerg   printf("%s from %s (%s ms total)\n\n", counts.c_str(), test_case.name(),
326506f32e7eSjoerg          internal::StreamableToString(test_case.elapsed_time()).c_str());
326606f32e7eSjoerg   fflush(stdout);
326706f32e7eSjoerg }
3268*da58b97aSjoerg #else
OnTestSuiteEnd(const TestSuite & test_suite)3269*da58b97aSjoerg void PrettyUnitTestResultPrinter::OnTestSuiteEnd(const TestSuite& test_suite) {
3270*da58b97aSjoerg   if (!GTEST_FLAG(print_time)) return;
3271*da58b97aSjoerg 
3272*da58b97aSjoerg   const std::string counts =
3273*da58b97aSjoerg       FormatCountableNoun(test_suite.test_to_run_count(), "test", "tests");
3274*da58b97aSjoerg   ColoredPrintf(COLOR_GREEN, "[----------] ");
3275*da58b97aSjoerg   printf("%s from %s (%s ms total)\n\n", counts.c_str(), test_suite.name(),
3276*da58b97aSjoerg          internal::StreamableToString(test_suite.elapsed_time()).c_str());
3277*da58b97aSjoerg   fflush(stdout);
3278*da58b97aSjoerg }
3279*da58b97aSjoerg #endif  // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
328006f32e7eSjoerg 
OnEnvironmentsTearDownStart(const UnitTest &)328106f32e7eSjoerg void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
328206f32e7eSjoerg     const UnitTest& /*unit_test*/) {
328306f32e7eSjoerg   ColoredPrintf(COLOR_GREEN,  "[----------] ");
328406f32e7eSjoerg   printf("Global test environment tear-down\n");
328506f32e7eSjoerg   fflush(stdout);
328606f32e7eSjoerg }
328706f32e7eSjoerg 
328806f32e7eSjoerg // Internal helper for printing the list of failed tests.
PrintFailedTests(const UnitTest & unit_test)328906f32e7eSjoerg void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
329006f32e7eSjoerg   const int failed_test_count = unit_test.failed_test_count();
329106f32e7eSjoerg   if (failed_test_count == 0) {
329206f32e7eSjoerg     return;
329306f32e7eSjoerg   }
329406f32e7eSjoerg 
3295*da58b97aSjoerg   for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
3296*da58b97aSjoerg     const TestSuite& test_suite = *unit_test.GetTestSuite(i);
3297*da58b97aSjoerg     if (!test_suite.should_run() || (test_suite.failed_test_count() == 0)) {
329806f32e7eSjoerg       continue;
329906f32e7eSjoerg     }
3300*da58b97aSjoerg     for (int j = 0; j < test_suite.total_test_count(); ++j) {
3301*da58b97aSjoerg       const TestInfo& test_info = *test_suite.GetTestInfo(j);
3302*da58b97aSjoerg       if (!test_info.should_run() || !test_info.result()->Failed()) {
330306f32e7eSjoerg         continue;
330406f32e7eSjoerg       }
330506f32e7eSjoerg       ColoredPrintf(COLOR_RED, "[  FAILED  ] ");
3306*da58b97aSjoerg       printf("%s.%s", test_suite.name(), test_info.name());
330706f32e7eSjoerg       PrintFullTestCommentIfPresent(test_info);
330806f32e7eSjoerg       printf("\n");
330906f32e7eSjoerg     }
331006f32e7eSjoerg   }
331106f32e7eSjoerg }
331206f32e7eSjoerg 
3313*da58b97aSjoerg // Internal helper for printing the list of skipped tests.
PrintSkippedTests(const UnitTest & unit_test)3314*da58b97aSjoerg void PrettyUnitTestResultPrinter::PrintSkippedTests(const UnitTest& unit_test) {
3315*da58b97aSjoerg   const int skipped_test_count = unit_test.skipped_test_count();
3316*da58b97aSjoerg   if (skipped_test_count == 0) {
3317*da58b97aSjoerg     return;
3318*da58b97aSjoerg   }
3319*da58b97aSjoerg 
3320*da58b97aSjoerg   for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
3321*da58b97aSjoerg     const TestSuite& test_suite = *unit_test.GetTestSuite(i);
3322*da58b97aSjoerg     if (!test_suite.should_run() || (test_suite.skipped_test_count() == 0)) {
3323*da58b97aSjoerg       continue;
3324*da58b97aSjoerg     }
3325*da58b97aSjoerg     for (int j = 0; j < test_suite.total_test_count(); ++j) {
3326*da58b97aSjoerg       const TestInfo& test_info = *test_suite.GetTestInfo(j);
3327*da58b97aSjoerg       if (!test_info.should_run() || !test_info.result()->Skipped()) {
3328*da58b97aSjoerg         continue;
3329*da58b97aSjoerg       }
3330*da58b97aSjoerg       ColoredPrintf(COLOR_GREEN, "[  SKIPPED ] ");
3331*da58b97aSjoerg       printf("%s.%s", test_suite.name(), test_info.name());
3332*da58b97aSjoerg       printf("\n");
3333*da58b97aSjoerg     }
3334*da58b97aSjoerg   }
3335*da58b97aSjoerg }
3336*da58b97aSjoerg 
OnTestIterationEnd(const UnitTest & unit_test,int)333706f32e7eSjoerg void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
333806f32e7eSjoerg                                                      int /*iteration*/) {
333906f32e7eSjoerg   ColoredPrintf(COLOR_GREEN,  "[==========] ");
334006f32e7eSjoerg   printf("%s from %s ran.",
334106f32e7eSjoerg          FormatTestCount(unit_test.test_to_run_count()).c_str(),
3342*da58b97aSjoerg          FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str());
334306f32e7eSjoerg   if (GTEST_FLAG(print_time)) {
334406f32e7eSjoerg     printf(" (%s ms total)",
334506f32e7eSjoerg            internal::StreamableToString(unit_test.elapsed_time()).c_str());
334606f32e7eSjoerg   }
334706f32e7eSjoerg   printf("\n");
334806f32e7eSjoerg   ColoredPrintf(COLOR_GREEN,  "[  PASSED  ] ");
334906f32e7eSjoerg   printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
335006f32e7eSjoerg 
3351*da58b97aSjoerg   const int skipped_test_count = unit_test.skipped_test_count();
3352*da58b97aSjoerg   if (skipped_test_count > 0) {
3353*da58b97aSjoerg     ColoredPrintf(COLOR_GREEN, "[  SKIPPED ] ");
3354*da58b97aSjoerg     printf("%s, listed below:\n", FormatTestCount(skipped_test_count).c_str());
3355*da58b97aSjoerg     PrintSkippedTests(unit_test);
3356*da58b97aSjoerg   }
3357*da58b97aSjoerg 
335806f32e7eSjoerg   int num_failures = unit_test.failed_test_count();
335906f32e7eSjoerg   if (!unit_test.Passed()) {
336006f32e7eSjoerg     const int failed_test_count = unit_test.failed_test_count();
336106f32e7eSjoerg     ColoredPrintf(COLOR_RED,  "[  FAILED  ] ");
336206f32e7eSjoerg     printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
336306f32e7eSjoerg     PrintFailedTests(unit_test);
336406f32e7eSjoerg     printf("\n%2d FAILED %s\n", num_failures,
336506f32e7eSjoerg                         num_failures == 1 ? "TEST" : "TESTS");
336606f32e7eSjoerg   }
336706f32e7eSjoerg 
336806f32e7eSjoerg   int num_disabled = unit_test.reportable_disabled_test_count();
336906f32e7eSjoerg   if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
337006f32e7eSjoerg     if (!num_failures) {
337106f32e7eSjoerg       printf("\n");  // Add a spacer if no FAILURE banner is displayed.
337206f32e7eSjoerg     }
337306f32e7eSjoerg     ColoredPrintf(COLOR_YELLOW,
337406f32e7eSjoerg                   "  YOU HAVE %d DISABLED %s\n\n",
337506f32e7eSjoerg                   num_disabled,
337606f32e7eSjoerg                   num_disabled == 1 ? "TEST" : "TESTS");
337706f32e7eSjoerg   }
337806f32e7eSjoerg   // Ensure that Google Test output is printed before, e.g., heapchecker output.
337906f32e7eSjoerg   fflush(stdout);
338006f32e7eSjoerg }
338106f32e7eSjoerg 
338206f32e7eSjoerg // End PrettyUnitTestResultPrinter
338306f32e7eSjoerg 
338406f32e7eSjoerg // class TestEventRepeater
338506f32e7eSjoerg //
338606f32e7eSjoerg // This class forwards events to other event listeners.
338706f32e7eSjoerg class TestEventRepeater : public TestEventListener {
338806f32e7eSjoerg  public:
TestEventRepeater()338906f32e7eSjoerg   TestEventRepeater() : forwarding_enabled_(true) {}
3390*da58b97aSjoerg   ~TestEventRepeater() override;
339106f32e7eSjoerg   void Append(TestEventListener *listener);
339206f32e7eSjoerg   TestEventListener* Release(TestEventListener* listener);
339306f32e7eSjoerg 
339406f32e7eSjoerg   // Controls whether events will be forwarded to listeners_. Set to false
339506f32e7eSjoerg   // in death test child processes.
forwarding_enabled() const339606f32e7eSjoerg   bool forwarding_enabled() const { return forwarding_enabled_; }
set_forwarding_enabled(bool enable)339706f32e7eSjoerg   void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }
339806f32e7eSjoerg 
3399*da58b97aSjoerg   void OnTestProgramStart(const UnitTest& unit_test) override;
3400*da58b97aSjoerg   void OnTestIterationStart(const UnitTest& unit_test, int iteration) override;
3401*da58b97aSjoerg   void OnEnvironmentsSetUpStart(const UnitTest& unit_test) override;
3402*da58b97aSjoerg   void OnEnvironmentsSetUpEnd(const UnitTest& unit_test) override;
3403*da58b97aSjoerg //  Legacy API is deprecated but still available
3404*da58b97aSjoerg #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3405*da58b97aSjoerg   void OnTestCaseStart(const TestSuite& parameter) override;
3406*da58b97aSjoerg #endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3407*da58b97aSjoerg   void OnTestSuiteStart(const TestSuite& parameter) override;
3408*da58b97aSjoerg   void OnTestStart(const TestInfo& test_info) override;
3409*da58b97aSjoerg   void OnTestPartResult(const TestPartResult& result) override;
3410*da58b97aSjoerg   void OnTestEnd(const TestInfo& test_info) override;
3411*da58b97aSjoerg //  Legacy API is deprecated but still available
3412*da58b97aSjoerg #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3413*da58b97aSjoerg   void OnTestCaseEnd(const TestCase& parameter) override;
3414*da58b97aSjoerg #endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3415*da58b97aSjoerg   void OnTestSuiteEnd(const TestSuite& parameter) override;
3416*da58b97aSjoerg   void OnEnvironmentsTearDownStart(const UnitTest& unit_test) override;
3417*da58b97aSjoerg   void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) override;
3418*da58b97aSjoerg   void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
3419*da58b97aSjoerg   void OnTestProgramEnd(const UnitTest& unit_test) override;
342006f32e7eSjoerg 
342106f32e7eSjoerg  private:
342206f32e7eSjoerg   // Controls whether events will be forwarded to listeners_. Set to false
342306f32e7eSjoerg   // in death test child processes.
342406f32e7eSjoerg   bool forwarding_enabled_;
342506f32e7eSjoerg   // The list of listeners that receive events.
342606f32e7eSjoerg   std::vector<TestEventListener*> listeners_;
342706f32e7eSjoerg 
342806f32e7eSjoerg   GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater);
342906f32e7eSjoerg };
343006f32e7eSjoerg 
~TestEventRepeater()343106f32e7eSjoerg TestEventRepeater::~TestEventRepeater() {
343206f32e7eSjoerg   ForEach(listeners_, Delete<TestEventListener>);
343306f32e7eSjoerg }
343406f32e7eSjoerg 
Append(TestEventListener * listener)343506f32e7eSjoerg void TestEventRepeater::Append(TestEventListener *listener) {
343606f32e7eSjoerg   listeners_.push_back(listener);
343706f32e7eSjoerg }
343806f32e7eSjoerg 
Release(TestEventListener * listener)343906f32e7eSjoerg TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {
344006f32e7eSjoerg   for (size_t i = 0; i < listeners_.size(); ++i) {
344106f32e7eSjoerg     if (listeners_[i] == listener) {
3442*da58b97aSjoerg       listeners_.erase(listeners_.begin() + static_cast<int>(i));
344306f32e7eSjoerg       return listener;
344406f32e7eSjoerg     }
344506f32e7eSjoerg   }
344606f32e7eSjoerg 
3447*da58b97aSjoerg   return nullptr;
344806f32e7eSjoerg }
344906f32e7eSjoerg 
345006f32e7eSjoerg // Since most methods are very similar, use macros to reduce boilerplate.
345106f32e7eSjoerg // This defines a member that forwards the call to all listeners.
345206f32e7eSjoerg #define GTEST_REPEATER_METHOD_(Name, Type) \
345306f32e7eSjoerg void TestEventRepeater::Name(const Type& parameter) { \
345406f32e7eSjoerg   if (forwarding_enabled_) { \
345506f32e7eSjoerg     for (size_t i = 0; i < listeners_.size(); i++) { \
345606f32e7eSjoerg       listeners_[i]->Name(parameter); \
345706f32e7eSjoerg     } \
345806f32e7eSjoerg   } \
345906f32e7eSjoerg }
346006f32e7eSjoerg // This defines a member that forwards the call to all listeners in reverse
346106f32e7eSjoerg // order.
346206f32e7eSjoerg #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type)      \
346306f32e7eSjoerg   void TestEventRepeater::Name(const Type& parameter) { \
346406f32e7eSjoerg     if (forwarding_enabled_) {                          \
3465*da58b97aSjoerg       for (size_t i = listeners_.size(); i != 0; i--) { \
3466*da58b97aSjoerg         listeners_[i - 1]->Name(parameter);             \
346706f32e7eSjoerg       }                                                 \
346806f32e7eSjoerg     }                                                   \
346906f32e7eSjoerg   }
347006f32e7eSjoerg 
GTEST_REPEATER_METHOD_(OnTestProgramStart,UnitTest)347106f32e7eSjoerg GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)
347206f32e7eSjoerg GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)
3473*da58b97aSjoerg //  Legacy API is deprecated but still available
3474*da58b97aSjoerg #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3475*da58b97aSjoerg GTEST_REPEATER_METHOD_(OnTestCaseStart, TestSuite)
3476*da58b97aSjoerg #endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3477*da58b97aSjoerg GTEST_REPEATER_METHOD_(OnTestSuiteStart, TestSuite)
347806f32e7eSjoerg GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
347906f32e7eSjoerg GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)
348006f32e7eSjoerg GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)
348106f32e7eSjoerg GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)
348206f32e7eSjoerg GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)
348306f32e7eSjoerg GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)
3484*da58b97aSjoerg //  Legacy API is deprecated but still available
3485*da58b97aSjoerg #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3486*da58b97aSjoerg GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestSuite)
3487*da58b97aSjoerg #endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3488*da58b97aSjoerg GTEST_REVERSE_REPEATER_METHOD_(OnTestSuiteEnd, TestSuite)
348906f32e7eSjoerg GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)
349006f32e7eSjoerg 
349106f32e7eSjoerg #undef GTEST_REPEATER_METHOD_
349206f32e7eSjoerg #undef GTEST_REVERSE_REPEATER_METHOD_
349306f32e7eSjoerg 
349406f32e7eSjoerg void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,
349506f32e7eSjoerg                                              int iteration) {
349606f32e7eSjoerg   if (forwarding_enabled_) {
349706f32e7eSjoerg     for (size_t i = 0; i < listeners_.size(); i++) {
349806f32e7eSjoerg       listeners_[i]->OnTestIterationStart(unit_test, iteration);
349906f32e7eSjoerg     }
350006f32e7eSjoerg   }
350106f32e7eSjoerg }
350206f32e7eSjoerg 
OnTestIterationEnd(const UnitTest & unit_test,int iteration)350306f32e7eSjoerg void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,
350406f32e7eSjoerg                                            int iteration) {
350506f32e7eSjoerg   if (forwarding_enabled_) {
3506*da58b97aSjoerg     for (size_t i = listeners_.size(); i > 0; i--) {
3507*da58b97aSjoerg       listeners_[i - 1]->OnTestIterationEnd(unit_test, iteration);
350806f32e7eSjoerg     }
350906f32e7eSjoerg   }
351006f32e7eSjoerg }
351106f32e7eSjoerg 
351206f32e7eSjoerg // End TestEventRepeater
351306f32e7eSjoerg 
351406f32e7eSjoerg // This class generates an XML output file.
351506f32e7eSjoerg class XmlUnitTestResultPrinter : public EmptyTestEventListener {
351606f32e7eSjoerg  public:
351706f32e7eSjoerg   explicit XmlUnitTestResultPrinter(const char* output_file);
351806f32e7eSjoerg 
3519*da58b97aSjoerg   void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
3520*da58b97aSjoerg   void ListTestsMatchingFilter(const std::vector<TestSuite*>& test_suites);
3521*da58b97aSjoerg 
3522*da58b97aSjoerg   // Prints an XML summary of all unit tests.
3523*da58b97aSjoerg   static void PrintXmlTestsList(std::ostream* stream,
3524*da58b97aSjoerg                                 const std::vector<TestSuite*>& test_suites);
352506f32e7eSjoerg 
352606f32e7eSjoerg  private:
352706f32e7eSjoerg   // Is c a whitespace character that is normalized to a space character
352806f32e7eSjoerg   // when it appears in an XML attribute value?
IsNormalizableWhitespace(char c)352906f32e7eSjoerg   static bool IsNormalizableWhitespace(char c) {
353006f32e7eSjoerg     return c == 0x9 || c == 0xA || c == 0xD;
353106f32e7eSjoerg   }
353206f32e7eSjoerg 
353306f32e7eSjoerg   // May c appear in a well-formed XML document?
IsValidXmlCharacter(char c)353406f32e7eSjoerg   static bool IsValidXmlCharacter(char c) {
353506f32e7eSjoerg     return IsNormalizableWhitespace(c) || c >= 0x20;
353606f32e7eSjoerg   }
353706f32e7eSjoerg 
353806f32e7eSjoerg   // Returns an XML-escaped copy of the input string str.  If
353906f32e7eSjoerg   // is_attribute is true, the text is meant to appear as an attribute
354006f32e7eSjoerg   // value, and normalizable whitespace is preserved by replacing it
354106f32e7eSjoerg   // with character references.
354206f32e7eSjoerg   static std::string EscapeXml(const std::string& str, bool is_attribute);
354306f32e7eSjoerg 
354406f32e7eSjoerg   // Returns the given string with all characters invalid in XML removed.
354506f32e7eSjoerg   static std::string RemoveInvalidXmlCharacters(const std::string& str);
354606f32e7eSjoerg 
354706f32e7eSjoerg   // Convenience wrapper around EscapeXml when str is an attribute value.
EscapeXmlAttribute(const std::string & str)354806f32e7eSjoerg   static std::string EscapeXmlAttribute(const std::string& str) {
354906f32e7eSjoerg     return EscapeXml(str, true);
355006f32e7eSjoerg   }
355106f32e7eSjoerg 
355206f32e7eSjoerg   // Convenience wrapper around EscapeXml when str is not an attribute value.
EscapeXmlText(const char * str)355306f32e7eSjoerg   static std::string EscapeXmlText(const char* str) {
355406f32e7eSjoerg     return EscapeXml(str, false);
355506f32e7eSjoerg   }
355606f32e7eSjoerg 
355706f32e7eSjoerg   // Verifies that the given attribute belongs to the given element and
355806f32e7eSjoerg   // streams the attribute as XML.
355906f32e7eSjoerg   static void OutputXmlAttribute(std::ostream* stream,
356006f32e7eSjoerg                                  const std::string& element_name,
356106f32e7eSjoerg                                  const std::string& name,
356206f32e7eSjoerg                                  const std::string& value);
356306f32e7eSjoerg 
356406f32e7eSjoerg   // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
356506f32e7eSjoerg   static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
356606f32e7eSjoerg 
356706f32e7eSjoerg   // Streams an XML representation of a TestInfo object.
356806f32e7eSjoerg   static void OutputXmlTestInfo(::std::ostream* stream,
3569*da58b97aSjoerg                                 const char* test_suite_name,
357006f32e7eSjoerg                                 const TestInfo& test_info);
357106f32e7eSjoerg 
3572*da58b97aSjoerg   // Prints an XML representation of a TestSuite object
3573*da58b97aSjoerg   static void PrintXmlTestSuite(::std::ostream* stream,
3574*da58b97aSjoerg                                 const TestSuite& test_suite);
357506f32e7eSjoerg 
357606f32e7eSjoerg   // Prints an XML summary of unit_test to output stream out.
357706f32e7eSjoerg   static void PrintXmlUnitTest(::std::ostream* stream,
357806f32e7eSjoerg                                const UnitTest& unit_test);
357906f32e7eSjoerg 
358006f32e7eSjoerg   // Produces a string representing the test properties in a result as space
358106f32e7eSjoerg   // delimited XML attributes based on the property key="value" pairs.
358206f32e7eSjoerg   // When the std::string is not empty, it includes a space at the beginning,
358306f32e7eSjoerg   // to delimit this attribute from prior attributes.
358406f32e7eSjoerg   static std::string TestPropertiesAsXmlAttributes(const TestResult& result);
358506f32e7eSjoerg 
3586*da58b97aSjoerg   // Streams an XML representation of the test properties of a TestResult
3587*da58b97aSjoerg   // object.
3588*da58b97aSjoerg   static void OutputXmlTestProperties(std::ostream* stream,
3589*da58b97aSjoerg                                       const TestResult& result);
3590*da58b97aSjoerg 
359106f32e7eSjoerg   // The output file.
359206f32e7eSjoerg   const std::string output_file_;
359306f32e7eSjoerg 
359406f32e7eSjoerg   GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);
359506f32e7eSjoerg };
359606f32e7eSjoerg 
359706f32e7eSjoerg // Creates a new XmlUnitTestResultPrinter.
XmlUnitTestResultPrinter(const char * output_file)359806f32e7eSjoerg XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
359906f32e7eSjoerg     : output_file_(output_file) {
3600*da58b97aSjoerg   if (output_file_.empty()) {
3601*da58b97aSjoerg     GTEST_LOG_(FATAL) << "XML output file may not be null";
360206f32e7eSjoerg   }
360306f32e7eSjoerg }
360406f32e7eSjoerg 
360506f32e7eSjoerg // Called after the unit test ends.
OnTestIterationEnd(const UnitTest & unit_test,int)360606f32e7eSjoerg void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
360706f32e7eSjoerg                                                   int /*iteration*/) {
3608*da58b97aSjoerg   FILE* xmlout = OpenFileForWriting(output_file_);
360906f32e7eSjoerg   std::stringstream stream;
361006f32e7eSjoerg   PrintXmlUnitTest(&stream, unit_test);
361106f32e7eSjoerg   fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
361206f32e7eSjoerg   fclose(xmlout);
361306f32e7eSjoerg }
361406f32e7eSjoerg 
ListTestsMatchingFilter(const std::vector<TestSuite * > & test_suites)3615*da58b97aSjoerg void XmlUnitTestResultPrinter::ListTestsMatchingFilter(
3616*da58b97aSjoerg     const std::vector<TestSuite*>& test_suites) {
3617*da58b97aSjoerg   FILE* xmlout = OpenFileForWriting(output_file_);
3618*da58b97aSjoerg   std::stringstream stream;
3619*da58b97aSjoerg   PrintXmlTestsList(&stream, test_suites);
3620*da58b97aSjoerg   fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
3621*da58b97aSjoerg   fclose(xmlout);
3622*da58b97aSjoerg }
3623*da58b97aSjoerg 
362406f32e7eSjoerg // Returns an XML-escaped copy of the input string str.  If is_attribute
362506f32e7eSjoerg // is true, the text is meant to appear as an attribute value, and
362606f32e7eSjoerg // normalizable whitespace is preserved by replacing it with character
362706f32e7eSjoerg // references.
362806f32e7eSjoerg //
362906f32e7eSjoerg // Invalid XML characters in str, if any, are stripped from the output.
363006f32e7eSjoerg // It is expected that most, if not all, of the text processed by this
363106f32e7eSjoerg // module will consist of ordinary English text.
363206f32e7eSjoerg // If this module is ever modified to produce version 1.1 XML output,
363306f32e7eSjoerg // most invalid characters can be retained using character references.
EscapeXml(const std::string & str,bool is_attribute)363406f32e7eSjoerg std::string XmlUnitTestResultPrinter::EscapeXml(
363506f32e7eSjoerg     const std::string& str, bool is_attribute) {
363606f32e7eSjoerg   Message m;
363706f32e7eSjoerg 
363806f32e7eSjoerg   for (size_t i = 0; i < str.size(); ++i) {
363906f32e7eSjoerg     const char ch = str[i];
364006f32e7eSjoerg     switch (ch) {
364106f32e7eSjoerg       case '<':
364206f32e7eSjoerg         m << "&lt;";
364306f32e7eSjoerg         break;
364406f32e7eSjoerg       case '>':
364506f32e7eSjoerg         m << "&gt;";
364606f32e7eSjoerg         break;
364706f32e7eSjoerg       case '&':
364806f32e7eSjoerg         m << "&amp;";
364906f32e7eSjoerg         break;
365006f32e7eSjoerg       case '\'':
365106f32e7eSjoerg         if (is_attribute)
365206f32e7eSjoerg           m << "&apos;";
365306f32e7eSjoerg         else
365406f32e7eSjoerg           m << '\'';
365506f32e7eSjoerg         break;
365606f32e7eSjoerg       case '"':
365706f32e7eSjoerg         if (is_attribute)
365806f32e7eSjoerg           m << "&quot;";
365906f32e7eSjoerg         else
366006f32e7eSjoerg           m << '"';
366106f32e7eSjoerg         break;
366206f32e7eSjoerg       default:
366306f32e7eSjoerg         if (IsValidXmlCharacter(ch)) {
366406f32e7eSjoerg           if (is_attribute && IsNormalizableWhitespace(ch))
366506f32e7eSjoerg             m << "&#x" << String::FormatByte(static_cast<unsigned char>(ch))
366606f32e7eSjoerg               << ";";
366706f32e7eSjoerg           else
366806f32e7eSjoerg             m << ch;
366906f32e7eSjoerg         }
367006f32e7eSjoerg         break;
367106f32e7eSjoerg     }
367206f32e7eSjoerg   }
367306f32e7eSjoerg 
367406f32e7eSjoerg   return m.GetString();
367506f32e7eSjoerg }
367606f32e7eSjoerg 
367706f32e7eSjoerg // Returns the given string with all characters invalid in XML removed.
367806f32e7eSjoerg // Currently invalid characters are dropped from the string. An
367906f32e7eSjoerg // alternative is to replace them with certain characters such as . or ?.
RemoveInvalidXmlCharacters(const std::string & str)368006f32e7eSjoerg std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(
368106f32e7eSjoerg     const std::string& str) {
368206f32e7eSjoerg   std::string output;
368306f32e7eSjoerg   output.reserve(str.size());
368406f32e7eSjoerg   for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
368506f32e7eSjoerg     if (IsValidXmlCharacter(*it))
368606f32e7eSjoerg       output.push_back(*it);
368706f32e7eSjoerg 
368806f32e7eSjoerg   return output;
368906f32e7eSjoerg }
369006f32e7eSjoerg 
369106f32e7eSjoerg // The following routines generate an XML representation of a UnitTest
369206f32e7eSjoerg // object.
3693*da58b97aSjoerg // GOOGLETEST_CM0009 DO NOT DELETE
369406f32e7eSjoerg //
369506f32e7eSjoerg // This is how Google Test concepts map to the DTD:
369606f32e7eSjoerg //
369706f32e7eSjoerg // <testsuites name="AllTests">        <-- corresponds to a UnitTest object
3698*da58b97aSjoerg //   <testsuite name="testcase-name">  <-- corresponds to a TestSuite object
369906f32e7eSjoerg //     <testcase name="test-name">     <-- corresponds to a TestInfo object
370006f32e7eSjoerg //       <failure message="...">...</failure>
370106f32e7eSjoerg //       <failure message="...">...</failure>
370206f32e7eSjoerg //       <failure message="...">...</failure>
370306f32e7eSjoerg //                                     <-- individual assertion failures
370406f32e7eSjoerg //     </testcase>
370506f32e7eSjoerg //   </testsuite>
370606f32e7eSjoerg // </testsuites>
370706f32e7eSjoerg 
370806f32e7eSjoerg // Formats the given time in milliseconds as seconds.
FormatTimeInMillisAsSeconds(TimeInMillis ms)370906f32e7eSjoerg std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {
371006f32e7eSjoerg   ::std::stringstream ss;
371106f32e7eSjoerg   ss << (static_cast<double>(ms) * 1e-3);
371206f32e7eSjoerg   return ss.str();
371306f32e7eSjoerg }
371406f32e7eSjoerg 
PortableLocaltime(time_t seconds,struct tm * out)371506f32e7eSjoerg static bool PortableLocaltime(time_t seconds, struct tm* out) {
371606f32e7eSjoerg #if defined(_MSC_VER)
371706f32e7eSjoerg   return localtime_s(out, &seconds) == 0;
371806f32e7eSjoerg #elif defined(__MINGW32__) || defined(__MINGW64__)
371906f32e7eSjoerg   // MINGW <time.h> provides neither localtime_r nor localtime_s, but uses
372006f32e7eSjoerg   // Windows' localtime(), which has a thread-local tm buffer.
372106f32e7eSjoerg   struct tm* tm_ptr = localtime(&seconds);  // NOLINT
3722*da58b97aSjoerg   if (tm_ptr == nullptr) return false;
372306f32e7eSjoerg   *out = *tm_ptr;
372406f32e7eSjoerg   return true;
372506f32e7eSjoerg #else
3726*da58b97aSjoerg   return localtime_r(&seconds, out) != nullptr;
372706f32e7eSjoerg #endif
372806f32e7eSjoerg }
372906f32e7eSjoerg 
373006f32e7eSjoerg // Converts the given epoch time in milliseconds to a date string in the ISO
373106f32e7eSjoerg // 8601 format, without the timezone information.
FormatEpochTimeInMillisAsIso8601(TimeInMillis ms)373206f32e7eSjoerg std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) {
373306f32e7eSjoerg   struct tm time_struct;
373406f32e7eSjoerg   if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))
373506f32e7eSjoerg     return "";
373606f32e7eSjoerg   // YYYY-MM-DDThh:mm:ss
373706f32e7eSjoerg   return StreamableToString(time_struct.tm_year + 1900) + "-" +
373806f32e7eSjoerg       String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +
373906f32e7eSjoerg       String::FormatIntWidth2(time_struct.tm_mday) + "T" +
374006f32e7eSjoerg       String::FormatIntWidth2(time_struct.tm_hour) + ":" +
374106f32e7eSjoerg       String::FormatIntWidth2(time_struct.tm_min) + ":" +
374206f32e7eSjoerg       String::FormatIntWidth2(time_struct.tm_sec);
374306f32e7eSjoerg }
374406f32e7eSjoerg 
374506f32e7eSjoerg // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
OutputXmlCDataSection(::std::ostream * stream,const char * data)374606f32e7eSjoerg void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
374706f32e7eSjoerg                                                      const char* data) {
374806f32e7eSjoerg   const char* segment = data;
374906f32e7eSjoerg   *stream << "<![CDATA[";
375006f32e7eSjoerg   for (;;) {
375106f32e7eSjoerg     const char* const next_segment = strstr(segment, "]]>");
3752*da58b97aSjoerg     if (next_segment != nullptr) {
375306f32e7eSjoerg       stream->write(
375406f32e7eSjoerg           segment, static_cast<std::streamsize>(next_segment - segment));
375506f32e7eSjoerg       *stream << "]]>]]&gt;<![CDATA[";
375606f32e7eSjoerg       segment = next_segment + strlen("]]>");
375706f32e7eSjoerg     } else {
375806f32e7eSjoerg       *stream << segment;
375906f32e7eSjoerg       break;
376006f32e7eSjoerg     }
376106f32e7eSjoerg   }
376206f32e7eSjoerg   *stream << "]]>";
376306f32e7eSjoerg }
376406f32e7eSjoerg 
OutputXmlAttribute(std::ostream * stream,const std::string & element_name,const std::string & name,const std::string & value)376506f32e7eSjoerg void XmlUnitTestResultPrinter::OutputXmlAttribute(
376606f32e7eSjoerg     std::ostream* stream,
376706f32e7eSjoerg     const std::string& element_name,
376806f32e7eSjoerg     const std::string& name,
376906f32e7eSjoerg     const std::string& value) {
377006f32e7eSjoerg   const std::vector<std::string>& allowed_names =
3771*da58b97aSjoerg       GetReservedOutputAttributesForElement(element_name);
377206f32e7eSjoerg 
377306f32e7eSjoerg   GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
377406f32e7eSjoerg                    allowed_names.end())
377506f32e7eSjoerg       << "Attribute " << name << " is not allowed for element <" << element_name
377606f32e7eSjoerg       << ">.";
377706f32e7eSjoerg 
377806f32e7eSjoerg   *stream << " " << name << "=\"" << EscapeXmlAttribute(value) << "\"";
377906f32e7eSjoerg }
378006f32e7eSjoerg 
378106f32e7eSjoerg // Prints an XML representation of a TestInfo object.
OutputXmlTestInfo(::std::ostream * stream,const char * test_suite_name,const TestInfo & test_info)378206f32e7eSjoerg void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
3783*da58b97aSjoerg                                                  const char* test_suite_name,
378406f32e7eSjoerg                                                  const TestInfo& test_info) {
378506f32e7eSjoerg   const TestResult& result = *test_info.result();
3786*da58b97aSjoerg   const std::string kTestsuite = "testcase";
3787*da58b97aSjoerg 
3788*da58b97aSjoerg   if (test_info.is_in_another_shard()) {
3789*da58b97aSjoerg     return;
3790*da58b97aSjoerg   }
379106f32e7eSjoerg 
379206f32e7eSjoerg   *stream << "    <testcase";
3793*da58b97aSjoerg   OutputXmlAttribute(stream, kTestsuite, "name", test_info.name());
379406f32e7eSjoerg 
3795*da58b97aSjoerg   if (test_info.value_param() != nullptr) {
3796*da58b97aSjoerg     OutputXmlAttribute(stream, kTestsuite, "value_param",
379706f32e7eSjoerg                        test_info.value_param());
379806f32e7eSjoerg   }
3799*da58b97aSjoerg   if (test_info.type_param() != nullptr) {
3800*da58b97aSjoerg     OutputXmlAttribute(stream, kTestsuite, "type_param",
3801*da58b97aSjoerg                        test_info.type_param());
3802*da58b97aSjoerg   }
3803*da58b97aSjoerg   if (GTEST_FLAG(list_tests)) {
3804*da58b97aSjoerg     OutputXmlAttribute(stream, kTestsuite, "file", test_info.file());
3805*da58b97aSjoerg     OutputXmlAttribute(stream, kTestsuite, "line",
3806*da58b97aSjoerg                        StreamableToString(test_info.line()));
3807*da58b97aSjoerg     *stream << " />\n";
3808*da58b97aSjoerg     return;
380906f32e7eSjoerg   }
381006f32e7eSjoerg 
3811*da58b97aSjoerg   OutputXmlAttribute(stream, kTestsuite, "status",
381206f32e7eSjoerg                      test_info.should_run() ? "run" : "notrun");
3813*da58b97aSjoerg   OutputXmlAttribute(stream, kTestsuite, "result",
3814*da58b97aSjoerg                      test_info.should_run()
3815*da58b97aSjoerg                          ? (result.Skipped() ? "skipped" : "completed")
3816*da58b97aSjoerg                          : "suppressed");
3817*da58b97aSjoerg   OutputXmlAttribute(stream, kTestsuite, "time",
381806f32e7eSjoerg                      FormatTimeInMillisAsSeconds(result.elapsed_time()));
3819*da58b97aSjoerg   OutputXmlAttribute(
3820*da58b97aSjoerg       stream, kTestsuite, "timestamp",
3821*da58b97aSjoerg       FormatEpochTimeInMillisAsIso8601(result.start_timestamp()));
3822*da58b97aSjoerg   OutputXmlAttribute(stream, kTestsuite, "classname", test_suite_name);
382306f32e7eSjoerg 
382406f32e7eSjoerg   int failures = 0;
382506f32e7eSjoerg   for (int i = 0; i < result.total_part_count(); ++i) {
382606f32e7eSjoerg     const TestPartResult& part = result.GetTestPartResult(i);
382706f32e7eSjoerg     if (part.failed()) {
382806f32e7eSjoerg       if (++failures == 1) {
382906f32e7eSjoerg         *stream << ">\n";
383006f32e7eSjoerg       }
3831*da58b97aSjoerg       const std::string location =
3832*da58b97aSjoerg           internal::FormatCompilerIndependentFileLocation(part.file_name(),
3833*da58b97aSjoerg                                                           part.line_number());
3834*da58b97aSjoerg       const std::string summary = location + "\n" + part.summary();
383506f32e7eSjoerg       *stream << "      <failure message=\""
383606f32e7eSjoerg               << EscapeXmlAttribute(summary.c_str())
383706f32e7eSjoerg               << "\" type=\"\">";
3838*da58b97aSjoerg       const std::string detail = location + "\n" + part.message();
383906f32e7eSjoerg       OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
384006f32e7eSjoerg       *stream << "</failure>\n";
384106f32e7eSjoerg     }
384206f32e7eSjoerg   }
384306f32e7eSjoerg 
3844*da58b97aSjoerg   if (failures == 0 && result.test_property_count() == 0) {
384506f32e7eSjoerg     *stream << " />\n";
3846*da58b97aSjoerg   } else {
3847*da58b97aSjoerg     if (failures == 0) {
3848*da58b97aSjoerg       *stream << ">\n";
3849*da58b97aSjoerg     }
3850*da58b97aSjoerg     OutputXmlTestProperties(stream, result);
385106f32e7eSjoerg     *stream << "    </testcase>\n";
385206f32e7eSjoerg   }
3853*da58b97aSjoerg }
385406f32e7eSjoerg 
3855*da58b97aSjoerg // Prints an XML representation of a TestSuite object
PrintXmlTestSuite(std::ostream * stream,const TestSuite & test_suite)3856*da58b97aSjoerg void XmlUnitTestResultPrinter::PrintXmlTestSuite(std::ostream* stream,
3857*da58b97aSjoerg                                                  const TestSuite& test_suite) {
385806f32e7eSjoerg   const std::string kTestsuite = "testsuite";
385906f32e7eSjoerg   *stream << "  <" << kTestsuite;
3860*da58b97aSjoerg   OutputXmlAttribute(stream, kTestsuite, "name", test_suite.name());
386106f32e7eSjoerg   OutputXmlAttribute(stream, kTestsuite, "tests",
3862*da58b97aSjoerg                      StreamableToString(test_suite.reportable_test_count()));
3863*da58b97aSjoerg   if (!GTEST_FLAG(list_tests)) {
386406f32e7eSjoerg     OutputXmlAttribute(stream, kTestsuite, "failures",
3865*da58b97aSjoerg                        StreamableToString(test_suite.failed_test_count()));
386606f32e7eSjoerg     OutputXmlAttribute(
386706f32e7eSjoerg         stream, kTestsuite, "disabled",
3868*da58b97aSjoerg         StreamableToString(test_suite.reportable_disabled_test_count()));
386906f32e7eSjoerg     OutputXmlAttribute(stream, kTestsuite, "errors", "0");
387006f32e7eSjoerg     OutputXmlAttribute(stream, kTestsuite, "time",
3871*da58b97aSjoerg                        FormatTimeInMillisAsSeconds(test_suite.elapsed_time()));
3872*da58b97aSjoerg     OutputXmlAttribute(
3873*da58b97aSjoerg         stream, kTestsuite, "timestamp",
3874*da58b97aSjoerg         FormatEpochTimeInMillisAsIso8601(test_suite.start_timestamp()));
3875*da58b97aSjoerg     *stream << TestPropertiesAsXmlAttributes(test_suite.ad_hoc_test_result());
3876*da58b97aSjoerg   }
3877*da58b97aSjoerg   *stream << ">\n";
3878*da58b97aSjoerg   for (int i = 0; i < test_suite.total_test_count(); ++i) {
3879*da58b97aSjoerg     if (test_suite.GetTestInfo(i)->is_reportable())
3880*da58b97aSjoerg       OutputXmlTestInfo(stream, test_suite.name(), *test_suite.GetTestInfo(i));
388106f32e7eSjoerg   }
388206f32e7eSjoerg   *stream << "  </" << kTestsuite << ">\n";
388306f32e7eSjoerg }
388406f32e7eSjoerg 
388506f32e7eSjoerg // Prints an XML summary of unit_test to output stream out.
PrintXmlUnitTest(std::ostream * stream,const UnitTest & unit_test)388606f32e7eSjoerg void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream,
388706f32e7eSjoerg                                                 const UnitTest& unit_test) {
388806f32e7eSjoerg   const std::string kTestsuites = "testsuites";
388906f32e7eSjoerg 
389006f32e7eSjoerg   *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
389106f32e7eSjoerg   *stream << "<" << kTestsuites;
389206f32e7eSjoerg 
389306f32e7eSjoerg   OutputXmlAttribute(stream, kTestsuites, "tests",
389406f32e7eSjoerg                      StreamableToString(unit_test.reportable_test_count()));
389506f32e7eSjoerg   OutputXmlAttribute(stream, kTestsuites, "failures",
389606f32e7eSjoerg                      StreamableToString(unit_test.failed_test_count()));
389706f32e7eSjoerg   OutputXmlAttribute(
389806f32e7eSjoerg       stream, kTestsuites, "disabled",
389906f32e7eSjoerg       StreamableToString(unit_test.reportable_disabled_test_count()));
390006f32e7eSjoerg   OutputXmlAttribute(stream, kTestsuites, "errors", "0");
3901*da58b97aSjoerg   OutputXmlAttribute(stream, kTestsuites, "time",
3902*da58b97aSjoerg                      FormatTimeInMillisAsSeconds(unit_test.elapsed_time()));
390306f32e7eSjoerg   OutputXmlAttribute(
390406f32e7eSjoerg       stream, kTestsuites, "timestamp",
390506f32e7eSjoerg       FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp()));
390606f32e7eSjoerg 
390706f32e7eSjoerg   if (GTEST_FLAG(shuffle)) {
390806f32e7eSjoerg     OutputXmlAttribute(stream, kTestsuites, "random_seed",
390906f32e7eSjoerg                        StreamableToString(unit_test.random_seed()));
391006f32e7eSjoerg   }
391106f32e7eSjoerg   *stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result());
391206f32e7eSjoerg 
391306f32e7eSjoerg   OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
391406f32e7eSjoerg   *stream << ">\n";
391506f32e7eSjoerg 
3916*da58b97aSjoerg   for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
3917*da58b97aSjoerg     if (unit_test.GetTestSuite(i)->reportable_test_count() > 0)
3918*da58b97aSjoerg       PrintXmlTestSuite(stream, *unit_test.GetTestSuite(i));
3919*da58b97aSjoerg   }
3920*da58b97aSjoerg   *stream << "</" << kTestsuites << ">\n";
3921*da58b97aSjoerg }
3922*da58b97aSjoerg 
PrintXmlTestsList(std::ostream * stream,const std::vector<TestSuite * > & test_suites)3923*da58b97aSjoerg void XmlUnitTestResultPrinter::PrintXmlTestsList(
3924*da58b97aSjoerg     std::ostream* stream, const std::vector<TestSuite*>& test_suites) {
3925*da58b97aSjoerg   const std::string kTestsuites = "testsuites";
3926*da58b97aSjoerg 
3927*da58b97aSjoerg   *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
3928*da58b97aSjoerg   *stream << "<" << kTestsuites;
3929*da58b97aSjoerg 
3930*da58b97aSjoerg   int total_tests = 0;
3931*da58b97aSjoerg   for (auto test_suite : test_suites) {
3932*da58b97aSjoerg     total_tests += test_suite->total_test_count();
3933*da58b97aSjoerg   }
3934*da58b97aSjoerg   OutputXmlAttribute(stream, kTestsuites, "tests",
3935*da58b97aSjoerg                      StreamableToString(total_tests));
3936*da58b97aSjoerg   OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
3937*da58b97aSjoerg   *stream << ">\n";
3938*da58b97aSjoerg 
3939*da58b97aSjoerg   for (auto test_suite : test_suites) {
3940*da58b97aSjoerg     PrintXmlTestSuite(stream, *test_suite);
394106f32e7eSjoerg   }
394206f32e7eSjoerg   *stream << "</" << kTestsuites << ">\n";
394306f32e7eSjoerg }
394406f32e7eSjoerg 
394506f32e7eSjoerg // Produces a string representing the test properties in a result as space
394606f32e7eSjoerg // delimited XML attributes based on the property key="value" pairs.
TestPropertiesAsXmlAttributes(const TestResult & result)394706f32e7eSjoerg std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
394806f32e7eSjoerg     const TestResult& result) {
394906f32e7eSjoerg   Message attributes;
395006f32e7eSjoerg   for (int i = 0; i < result.test_property_count(); ++i) {
395106f32e7eSjoerg     const TestProperty& property = result.GetTestProperty(i);
395206f32e7eSjoerg     attributes << " " << property.key() << "="
395306f32e7eSjoerg         << "\"" << EscapeXmlAttribute(property.value()) << "\"";
395406f32e7eSjoerg   }
395506f32e7eSjoerg   return attributes.GetString();
395606f32e7eSjoerg }
395706f32e7eSjoerg 
OutputXmlTestProperties(std::ostream * stream,const TestResult & result)3958*da58b97aSjoerg void XmlUnitTestResultPrinter::OutputXmlTestProperties(
3959*da58b97aSjoerg     std::ostream* stream, const TestResult& result) {
3960*da58b97aSjoerg   const std::string kProperties = "properties";
3961*da58b97aSjoerg   const std::string kProperty = "property";
3962*da58b97aSjoerg 
3963*da58b97aSjoerg   if (result.test_property_count() <= 0) {
3964*da58b97aSjoerg     return;
3965*da58b97aSjoerg   }
3966*da58b97aSjoerg 
3967*da58b97aSjoerg   *stream << "<" << kProperties << ">\n";
3968*da58b97aSjoerg   for (int i = 0; i < result.test_property_count(); ++i) {
3969*da58b97aSjoerg     const TestProperty& property = result.GetTestProperty(i);
3970*da58b97aSjoerg     *stream << "<" << kProperty;
3971*da58b97aSjoerg     *stream << " name=\"" << EscapeXmlAttribute(property.key()) << "\"";
3972*da58b97aSjoerg     *stream << " value=\"" << EscapeXmlAttribute(property.value()) << "\"";
3973*da58b97aSjoerg     *stream << "/>\n";
3974*da58b97aSjoerg   }
3975*da58b97aSjoerg   *stream << "</" << kProperties << ">\n";
3976*da58b97aSjoerg }
3977*da58b97aSjoerg 
397806f32e7eSjoerg // End XmlUnitTestResultPrinter
397906f32e7eSjoerg 
3980*da58b97aSjoerg // This class generates an JSON output file.
3981*da58b97aSjoerg class JsonUnitTestResultPrinter : public EmptyTestEventListener {
3982*da58b97aSjoerg  public:
3983*da58b97aSjoerg   explicit JsonUnitTestResultPrinter(const char* output_file);
3984*da58b97aSjoerg 
3985*da58b97aSjoerg   void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
3986*da58b97aSjoerg 
3987*da58b97aSjoerg   // Prints an JSON summary of all unit tests.
3988*da58b97aSjoerg   static void PrintJsonTestList(::std::ostream* stream,
3989*da58b97aSjoerg                                 const std::vector<TestSuite*>& test_suites);
3990*da58b97aSjoerg 
3991*da58b97aSjoerg  private:
3992*da58b97aSjoerg   // Returns an JSON-escaped copy of the input string str.
3993*da58b97aSjoerg   static std::string EscapeJson(const std::string& str);
3994*da58b97aSjoerg 
3995*da58b97aSjoerg   //// Verifies that the given attribute belongs to the given element and
3996*da58b97aSjoerg   //// streams the attribute as JSON.
3997*da58b97aSjoerg   static void OutputJsonKey(std::ostream* stream,
3998*da58b97aSjoerg                             const std::string& element_name,
3999*da58b97aSjoerg                             const std::string& name,
4000*da58b97aSjoerg                             const std::string& value,
4001*da58b97aSjoerg                             const std::string& indent,
4002*da58b97aSjoerg                             bool comma = true);
4003*da58b97aSjoerg   static void OutputJsonKey(std::ostream* stream,
4004*da58b97aSjoerg                             const std::string& element_name,
4005*da58b97aSjoerg                             const std::string& name,
4006*da58b97aSjoerg                             int value,
4007*da58b97aSjoerg                             const std::string& indent,
4008*da58b97aSjoerg                             bool comma = true);
4009*da58b97aSjoerg 
4010*da58b97aSjoerg   // Streams a JSON representation of a TestInfo object.
4011*da58b97aSjoerg   static void OutputJsonTestInfo(::std::ostream* stream,
4012*da58b97aSjoerg                                  const char* test_suite_name,
4013*da58b97aSjoerg                                  const TestInfo& test_info);
4014*da58b97aSjoerg 
4015*da58b97aSjoerg   // Prints a JSON representation of a TestSuite object
4016*da58b97aSjoerg   static void PrintJsonTestSuite(::std::ostream* stream,
4017*da58b97aSjoerg                                  const TestSuite& test_suite);
4018*da58b97aSjoerg 
4019*da58b97aSjoerg   // Prints a JSON summary of unit_test to output stream out.
4020*da58b97aSjoerg   static void PrintJsonUnitTest(::std::ostream* stream,
4021*da58b97aSjoerg                                 const UnitTest& unit_test);
4022*da58b97aSjoerg 
4023*da58b97aSjoerg   // Produces a string representing the test properties in a result as
4024*da58b97aSjoerg   // a JSON dictionary.
4025*da58b97aSjoerg   static std::string TestPropertiesAsJson(const TestResult& result,
4026*da58b97aSjoerg                                           const std::string& indent);
4027*da58b97aSjoerg 
4028*da58b97aSjoerg   // The output file.
4029*da58b97aSjoerg   const std::string output_file_;
4030*da58b97aSjoerg 
4031*da58b97aSjoerg   GTEST_DISALLOW_COPY_AND_ASSIGN_(JsonUnitTestResultPrinter);
4032*da58b97aSjoerg };
4033*da58b97aSjoerg 
4034*da58b97aSjoerg // Creates a new JsonUnitTestResultPrinter.
JsonUnitTestResultPrinter(const char * output_file)4035*da58b97aSjoerg JsonUnitTestResultPrinter::JsonUnitTestResultPrinter(const char* output_file)
4036*da58b97aSjoerg     : output_file_(output_file) {
4037*da58b97aSjoerg   if (output_file_.empty()) {
4038*da58b97aSjoerg     GTEST_LOG_(FATAL) << "JSON output file may not be null";
4039*da58b97aSjoerg   }
4040*da58b97aSjoerg }
4041*da58b97aSjoerg 
OnTestIterationEnd(const UnitTest & unit_test,int)4042*da58b97aSjoerg void JsonUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
4043*da58b97aSjoerg                                                   int /*iteration*/) {
4044*da58b97aSjoerg   FILE* jsonout = OpenFileForWriting(output_file_);
4045*da58b97aSjoerg   std::stringstream stream;
4046*da58b97aSjoerg   PrintJsonUnitTest(&stream, unit_test);
4047*da58b97aSjoerg   fprintf(jsonout, "%s", StringStreamToString(&stream).c_str());
4048*da58b97aSjoerg   fclose(jsonout);
4049*da58b97aSjoerg }
4050*da58b97aSjoerg 
4051*da58b97aSjoerg // Returns an JSON-escaped copy of the input string str.
EscapeJson(const std::string & str)4052*da58b97aSjoerg std::string JsonUnitTestResultPrinter::EscapeJson(const std::string& str) {
4053*da58b97aSjoerg   Message m;
4054*da58b97aSjoerg 
4055*da58b97aSjoerg   for (size_t i = 0; i < str.size(); ++i) {
4056*da58b97aSjoerg     const char ch = str[i];
4057*da58b97aSjoerg     switch (ch) {
4058*da58b97aSjoerg       case '\\':
4059*da58b97aSjoerg       case '"':
4060*da58b97aSjoerg       case '/':
4061*da58b97aSjoerg         m << '\\' << ch;
4062*da58b97aSjoerg         break;
4063*da58b97aSjoerg       case '\b':
4064*da58b97aSjoerg         m << "\\b";
4065*da58b97aSjoerg         break;
4066*da58b97aSjoerg       case '\t':
4067*da58b97aSjoerg         m << "\\t";
4068*da58b97aSjoerg         break;
4069*da58b97aSjoerg       case '\n':
4070*da58b97aSjoerg         m << "\\n";
4071*da58b97aSjoerg         break;
4072*da58b97aSjoerg       case '\f':
4073*da58b97aSjoerg         m << "\\f";
4074*da58b97aSjoerg         break;
4075*da58b97aSjoerg       case '\r':
4076*da58b97aSjoerg         m << "\\r";
4077*da58b97aSjoerg         break;
4078*da58b97aSjoerg       default:
4079*da58b97aSjoerg         if (ch < ' ') {
4080*da58b97aSjoerg           m << "\\u00" << String::FormatByte(static_cast<unsigned char>(ch));
4081*da58b97aSjoerg         } else {
4082*da58b97aSjoerg           m << ch;
4083*da58b97aSjoerg         }
4084*da58b97aSjoerg         break;
4085*da58b97aSjoerg     }
4086*da58b97aSjoerg   }
4087*da58b97aSjoerg 
4088*da58b97aSjoerg   return m.GetString();
4089*da58b97aSjoerg }
4090*da58b97aSjoerg 
4091*da58b97aSjoerg // The following routines generate an JSON representation of a UnitTest
4092*da58b97aSjoerg // object.
4093*da58b97aSjoerg 
4094*da58b97aSjoerg // Formats the given time in milliseconds as seconds.
FormatTimeInMillisAsDuration(TimeInMillis ms)4095*da58b97aSjoerg static std::string FormatTimeInMillisAsDuration(TimeInMillis ms) {
4096*da58b97aSjoerg   ::std::stringstream ss;
4097*da58b97aSjoerg   ss << (static_cast<double>(ms) * 1e-3) << "s";
4098*da58b97aSjoerg   return ss.str();
4099*da58b97aSjoerg }
4100*da58b97aSjoerg 
4101*da58b97aSjoerg // Converts the given epoch time in milliseconds to a date string in the
4102*da58b97aSjoerg // RFC3339 format, without the timezone information.
FormatEpochTimeInMillisAsRFC3339(TimeInMillis ms)4103*da58b97aSjoerg static std::string FormatEpochTimeInMillisAsRFC3339(TimeInMillis ms) {
4104*da58b97aSjoerg   struct tm time_struct;
4105*da58b97aSjoerg   if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))
4106*da58b97aSjoerg     return "";
4107*da58b97aSjoerg   // YYYY-MM-DDThh:mm:ss
4108*da58b97aSjoerg   return StreamableToString(time_struct.tm_year + 1900) + "-" +
4109*da58b97aSjoerg       String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +
4110*da58b97aSjoerg       String::FormatIntWidth2(time_struct.tm_mday) + "T" +
4111*da58b97aSjoerg       String::FormatIntWidth2(time_struct.tm_hour) + ":" +
4112*da58b97aSjoerg       String::FormatIntWidth2(time_struct.tm_min) + ":" +
4113*da58b97aSjoerg       String::FormatIntWidth2(time_struct.tm_sec) + "Z";
4114*da58b97aSjoerg }
4115*da58b97aSjoerg 
Indent(size_t width)4116*da58b97aSjoerg static inline std::string Indent(size_t width) {
4117*da58b97aSjoerg   return std::string(width, ' ');
4118*da58b97aSjoerg }
4119*da58b97aSjoerg 
OutputJsonKey(std::ostream * stream,const std::string & element_name,const std::string & name,const std::string & value,const std::string & indent,bool comma)4120*da58b97aSjoerg void JsonUnitTestResultPrinter::OutputJsonKey(
4121*da58b97aSjoerg     std::ostream* stream,
4122*da58b97aSjoerg     const std::string& element_name,
4123*da58b97aSjoerg     const std::string& name,
4124*da58b97aSjoerg     const std::string& value,
4125*da58b97aSjoerg     const std::string& indent,
4126*da58b97aSjoerg     bool comma) {
4127*da58b97aSjoerg   const std::vector<std::string>& allowed_names =
4128*da58b97aSjoerg       GetReservedOutputAttributesForElement(element_name);
4129*da58b97aSjoerg 
4130*da58b97aSjoerg   GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
4131*da58b97aSjoerg                    allowed_names.end())
4132*da58b97aSjoerg       << "Key \"" << name << "\" is not allowed for value \"" << element_name
4133*da58b97aSjoerg       << "\".";
4134*da58b97aSjoerg 
4135*da58b97aSjoerg   *stream << indent << "\"" << name << "\": \"" << EscapeJson(value) << "\"";
4136*da58b97aSjoerg   if (comma)
4137*da58b97aSjoerg     *stream << ",\n";
4138*da58b97aSjoerg }
4139*da58b97aSjoerg 
OutputJsonKey(std::ostream * stream,const std::string & element_name,const std::string & name,int value,const std::string & indent,bool comma)4140*da58b97aSjoerg void JsonUnitTestResultPrinter::OutputJsonKey(
4141*da58b97aSjoerg     std::ostream* stream,
4142*da58b97aSjoerg     const std::string& element_name,
4143*da58b97aSjoerg     const std::string& name,
4144*da58b97aSjoerg     int value,
4145*da58b97aSjoerg     const std::string& indent,
4146*da58b97aSjoerg     bool comma) {
4147*da58b97aSjoerg   const std::vector<std::string>& allowed_names =
4148*da58b97aSjoerg       GetReservedOutputAttributesForElement(element_name);
4149*da58b97aSjoerg 
4150*da58b97aSjoerg   GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
4151*da58b97aSjoerg                    allowed_names.end())
4152*da58b97aSjoerg       << "Key \"" << name << "\" is not allowed for value \"" << element_name
4153*da58b97aSjoerg       << "\".";
4154*da58b97aSjoerg 
4155*da58b97aSjoerg   *stream << indent << "\"" << name << "\": " << StreamableToString(value);
4156*da58b97aSjoerg   if (comma)
4157*da58b97aSjoerg     *stream << ",\n";
4158*da58b97aSjoerg }
4159*da58b97aSjoerg 
4160*da58b97aSjoerg // Prints a JSON representation of a TestInfo object.
OutputJsonTestInfo(::std::ostream * stream,const char * test_suite_name,const TestInfo & test_info)4161*da58b97aSjoerg void JsonUnitTestResultPrinter::OutputJsonTestInfo(::std::ostream* stream,
4162*da58b97aSjoerg                                                    const char* test_suite_name,
4163*da58b97aSjoerg                                                    const TestInfo& test_info) {
4164*da58b97aSjoerg   const TestResult& result = *test_info.result();
4165*da58b97aSjoerg   const std::string kTestsuite = "testcase";
4166*da58b97aSjoerg   const std::string kIndent = Indent(10);
4167*da58b97aSjoerg 
4168*da58b97aSjoerg   *stream << Indent(8) << "{\n";
4169*da58b97aSjoerg   OutputJsonKey(stream, kTestsuite, "name", test_info.name(), kIndent);
4170*da58b97aSjoerg 
4171*da58b97aSjoerg   if (test_info.value_param() != nullptr) {
4172*da58b97aSjoerg     OutputJsonKey(stream, kTestsuite, "value_param", test_info.value_param(),
4173*da58b97aSjoerg                   kIndent);
4174*da58b97aSjoerg   }
4175*da58b97aSjoerg   if (test_info.type_param() != nullptr) {
4176*da58b97aSjoerg     OutputJsonKey(stream, kTestsuite, "type_param", test_info.type_param(),
4177*da58b97aSjoerg                   kIndent);
4178*da58b97aSjoerg   }
4179*da58b97aSjoerg   if (GTEST_FLAG(list_tests)) {
4180*da58b97aSjoerg     OutputJsonKey(stream, kTestsuite, "file", test_info.file(), kIndent);
4181*da58b97aSjoerg     OutputJsonKey(stream, kTestsuite, "line", test_info.line(), kIndent, false);
4182*da58b97aSjoerg     *stream << "\n" << Indent(8) << "}";
4183*da58b97aSjoerg     return;
4184*da58b97aSjoerg   }
4185*da58b97aSjoerg 
4186*da58b97aSjoerg   OutputJsonKey(stream, kTestsuite, "status",
4187*da58b97aSjoerg                 test_info.should_run() ? "RUN" : "NOTRUN", kIndent);
4188*da58b97aSjoerg   OutputJsonKey(stream, kTestsuite, "result",
4189*da58b97aSjoerg                 test_info.should_run()
4190*da58b97aSjoerg                     ? (result.Skipped() ? "SKIPPED" : "COMPLETED")
4191*da58b97aSjoerg                     : "SUPPRESSED",
4192*da58b97aSjoerg                 kIndent);
4193*da58b97aSjoerg   OutputJsonKey(stream, kTestsuite, "timestamp",
4194*da58b97aSjoerg                 FormatEpochTimeInMillisAsRFC3339(result.start_timestamp()),
4195*da58b97aSjoerg                 kIndent);
4196*da58b97aSjoerg   OutputJsonKey(stream, kTestsuite, "time",
4197*da58b97aSjoerg                 FormatTimeInMillisAsDuration(result.elapsed_time()), kIndent);
4198*da58b97aSjoerg   OutputJsonKey(stream, kTestsuite, "classname", test_suite_name, kIndent,
4199*da58b97aSjoerg                 false);
4200*da58b97aSjoerg   *stream << TestPropertiesAsJson(result, kIndent);
4201*da58b97aSjoerg 
4202*da58b97aSjoerg   int failures = 0;
4203*da58b97aSjoerg   for (int i = 0; i < result.total_part_count(); ++i) {
4204*da58b97aSjoerg     const TestPartResult& part = result.GetTestPartResult(i);
4205*da58b97aSjoerg     if (part.failed()) {
4206*da58b97aSjoerg       *stream << ",\n";
4207*da58b97aSjoerg       if (++failures == 1) {
4208*da58b97aSjoerg         *stream << kIndent << "\"" << "failures" << "\": [\n";
4209*da58b97aSjoerg       }
4210*da58b97aSjoerg       const std::string location =
4211*da58b97aSjoerg           internal::FormatCompilerIndependentFileLocation(part.file_name(),
4212*da58b97aSjoerg                                                           part.line_number());
4213*da58b97aSjoerg       const std::string message = EscapeJson(location + "\n" + part.message());
4214*da58b97aSjoerg       *stream << kIndent << "  {\n"
4215*da58b97aSjoerg               << kIndent << "    \"failure\": \"" << message << "\",\n"
4216*da58b97aSjoerg               << kIndent << "    \"type\": \"\"\n"
4217*da58b97aSjoerg               << kIndent << "  }";
4218*da58b97aSjoerg     }
4219*da58b97aSjoerg   }
4220*da58b97aSjoerg 
4221*da58b97aSjoerg   if (failures > 0)
4222*da58b97aSjoerg     *stream << "\n" << kIndent << "]";
4223*da58b97aSjoerg   *stream << "\n" << Indent(8) << "}";
4224*da58b97aSjoerg }
4225*da58b97aSjoerg 
4226*da58b97aSjoerg // Prints an JSON representation of a TestSuite object
PrintJsonTestSuite(std::ostream * stream,const TestSuite & test_suite)4227*da58b97aSjoerg void JsonUnitTestResultPrinter::PrintJsonTestSuite(
4228*da58b97aSjoerg     std::ostream* stream, const TestSuite& test_suite) {
4229*da58b97aSjoerg   const std::string kTestsuite = "testsuite";
4230*da58b97aSjoerg   const std::string kIndent = Indent(6);
4231*da58b97aSjoerg 
4232*da58b97aSjoerg   *stream << Indent(4) << "{\n";
4233*da58b97aSjoerg   OutputJsonKey(stream, kTestsuite, "name", test_suite.name(), kIndent);
4234*da58b97aSjoerg   OutputJsonKey(stream, kTestsuite, "tests", test_suite.reportable_test_count(),
4235*da58b97aSjoerg                 kIndent);
4236*da58b97aSjoerg   if (!GTEST_FLAG(list_tests)) {
4237*da58b97aSjoerg     OutputJsonKey(stream, kTestsuite, "failures",
4238*da58b97aSjoerg                   test_suite.failed_test_count(), kIndent);
4239*da58b97aSjoerg     OutputJsonKey(stream, kTestsuite, "disabled",
4240*da58b97aSjoerg                   test_suite.reportable_disabled_test_count(), kIndent);
4241*da58b97aSjoerg     OutputJsonKey(stream, kTestsuite, "errors", 0, kIndent);
4242*da58b97aSjoerg     OutputJsonKey(
4243*da58b97aSjoerg         stream, kTestsuite, "timestamp",
4244*da58b97aSjoerg         FormatEpochTimeInMillisAsRFC3339(test_suite.start_timestamp()),
4245*da58b97aSjoerg         kIndent);
4246*da58b97aSjoerg     OutputJsonKey(stream, kTestsuite, "time",
4247*da58b97aSjoerg                   FormatTimeInMillisAsDuration(test_suite.elapsed_time()),
4248*da58b97aSjoerg                   kIndent, false);
4249*da58b97aSjoerg     *stream << TestPropertiesAsJson(test_suite.ad_hoc_test_result(), kIndent)
4250*da58b97aSjoerg             << ",\n";
4251*da58b97aSjoerg   }
4252*da58b97aSjoerg 
4253*da58b97aSjoerg   *stream << kIndent << "\"" << kTestsuite << "\": [\n";
4254*da58b97aSjoerg 
4255*da58b97aSjoerg   bool comma = false;
4256*da58b97aSjoerg   for (int i = 0; i < test_suite.total_test_count(); ++i) {
4257*da58b97aSjoerg     if (test_suite.GetTestInfo(i)->is_reportable()) {
4258*da58b97aSjoerg       if (comma) {
4259*da58b97aSjoerg         *stream << ",\n";
4260*da58b97aSjoerg       } else {
4261*da58b97aSjoerg         comma = true;
4262*da58b97aSjoerg       }
4263*da58b97aSjoerg       OutputJsonTestInfo(stream, test_suite.name(), *test_suite.GetTestInfo(i));
4264*da58b97aSjoerg     }
4265*da58b97aSjoerg   }
4266*da58b97aSjoerg   *stream << "\n" << kIndent << "]\n" << Indent(4) << "}";
4267*da58b97aSjoerg }
4268*da58b97aSjoerg 
4269*da58b97aSjoerg // Prints a JSON summary of unit_test to output stream out.
PrintJsonUnitTest(std::ostream * stream,const UnitTest & unit_test)4270*da58b97aSjoerg void JsonUnitTestResultPrinter::PrintJsonUnitTest(std::ostream* stream,
4271*da58b97aSjoerg                                                   const UnitTest& unit_test) {
4272*da58b97aSjoerg   const std::string kTestsuites = "testsuites";
4273*da58b97aSjoerg   const std::string kIndent = Indent(2);
4274*da58b97aSjoerg   *stream << "{\n";
4275*da58b97aSjoerg 
4276*da58b97aSjoerg   OutputJsonKey(stream, kTestsuites, "tests", unit_test.reportable_test_count(),
4277*da58b97aSjoerg                 kIndent);
4278*da58b97aSjoerg   OutputJsonKey(stream, kTestsuites, "failures", unit_test.failed_test_count(),
4279*da58b97aSjoerg                 kIndent);
4280*da58b97aSjoerg   OutputJsonKey(stream, kTestsuites, "disabled",
4281*da58b97aSjoerg                 unit_test.reportable_disabled_test_count(), kIndent);
4282*da58b97aSjoerg   OutputJsonKey(stream, kTestsuites, "errors", 0, kIndent);
4283*da58b97aSjoerg   if (GTEST_FLAG(shuffle)) {
4284*da58b97aSjoerg     OutputJsonKey(stream, kTestsuites, "random_seed", unit_test.random_seed(),
4285*da58b97aSjoerg                   kIndent);
4286*da58b97aSjoerg   }
4287*da58b97aSjoerg   OutputJsonKey(stream, kTestsuites, "timestamp",
4288*da58b97aSjoerg                 FormatEpochTimeInMillisAsRFC3339(unit_test.start_timestamp()),
4289*da58b97aSjoerg                 kIndent);
4290*da58b97aSjoerg   OutputJsonKey(stream, kTestsuites, "time",
4291*da58b97aSjoerg                 FormatTimeInMillisAsDuration(unit_test.elapsed_time()), kIndent,
4292*da58b97aSjoerg                 false);
4293*da58b97aSjoerg 
4294*da58b97aSjoerg   *stream << TestPropertiesAsJson(unit_test.ad_hoc_test_result(), kIndent)
4295*da58b97aSjoerg           << ",\n";
4296*da58b97aSjoerg 
4297*da58b97aSjoerg   OutputJsonKey(stream, kTestsuites, "name", "AllTests", kIndent);
4298*da58b97aSjoerg   *stream << kIndent << "\"" << kTestsuites << "\": [\n";
4299*da58b97aSjoerg 
4300*da58b97aSjoerg   bool comma = false;
4301*da58b97aSjoerg   for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
4302*da58b97aSjoerg     if (unit_test.GetTestSuite(i)->reportable_test_count() > 0) {
4303*da58b97aSjoerg       if (comma) {
4304*da58b97aSjoerg         *stream << ",\n";
4305*da58b97aSjoerg       } else {
4306*da58b97aSjoerg         comma = true;
4307*da58b97aSjoerg       }
4308*da58b97aSjoerg       PrintJsonTestSuite(stream, *unit_test.GetTestSuite(i));
4309*da58b97aSjoerg     }
4310*da58b97aSjoerg   }
4311*da58b97aSjoerg 
4312*da58b97aSjoerg   *stream << "\n" << kIndent << "]\n" << "}\n";
4313*da58b97aSjoerg }
4314*da58b97aSjoerg 
PrintJsonTestList(std::ostream * stream,const std::vector<TestSuite * > & test_suites)4315*da58b97aSjoerg void JsonUnitTestResultPrinter::PrintJsonTestList(
4316*da58b97aSjoerg     std::ostream* stream, const std::vector<TestSuite*>& test_suites) {
4317*da58b97aSjoerg   const std::string kTestsuites = "testsuites";
4318*da58b97aSjoerg   const std::string kIndent = Indent(2);
4319*da58b97aSjoerg   *stream << "{\n";
4320*da58b97aSjoerg   int total_tests = 0;
4321*da58b97aSjoerg   for (auto test_suite : test_suites) {
4322*da58b97aSjoerg     total_tests += test_suite->total_test_count();
4323*da58b97aSjoerg   }
4324*da58b97aSjoerg   OutputJsonKey(stream, kTestsuites, "tests", total_tests, kIndent);
4325*da58b97aSjoerg 
4326*da58b97aSjoerg   OutputJsonKey(stream, kTestsuites, "name", "AllTests", kIndent);
4327*da58b97aSjoerg   *stream << kIndent << "\"" << kTestsuites << "\": [\n";
4328*da58b97aSjoerg 
4329*da58b97aSjoerg   for (size_t i = 0; i < test_suites.size(); ++i) {
4330*da58b97aSjoerg     if (i != 0) {
4331*da58b97aSjoerg       *stream << ",\n";
4332*da58b97aSjoerg     }
4333*da58b97aSjoerg     PrintJsonTestSuite(stream, *test_suites[i]);
4334*da58b97aSjoerg   }
4335*da58b97aSjoerg 
4336*da58b97aSjoerg   *stream << "\n"
4337*da58b97aSjoerg           << kIndent << "]\n"
4338*da58b97aSjoerg           << "}\n";
4339*da58b97aSjoerg }
4340*da58b97aSjoerg // Produces a string representing the test properties in a result as
4341*da58b97aSjoerg // a JSON dictionary.
TestPropertiesAsJson(const TestResult & result,const std::string & indent)4342*da58b97aSjoerg std::string JsonUnitTestResultPrinter::TestPropertiesAsJson(
4343*da58b97aSjoerg     const TestResult& result, const std::string& indent) {
4344*da58b97aSjoerg   Message attributes;
4345*da58b97aSjoerg   for (int i = 0; i < result.test_property_count(); ++i) {
4346*da58b97aSjoerg     const TestProperty& property = result.GetTestProperty(i);
4347*da58b97aSjoerg     attributes << ",\n" << indent << "\"" << property.key() << "\": "
4348*da58b97aSjoerg                << "\"" << EscapeJson(property.value()) << "\"";
4349*da58b97aSjoerg   }
4350*da58b97aSjoerg   return attributes.GetString();
4351*da58b97aSjoerg }
4352*da58b97aSjoerg 
4353*da58b97aSjoerg // End JsonUnitTestResultPrinter
4354*da58b97aSjoerg 
435506f32e7eSjoerg #if GTEST_CAN_STREAM_RESULTS_
435606f32e7eSjoerg 
435706f32e7eSjoerg // Checks if str contains '=', '&', '%' or '\n' characters. If yes,
435806f32e7eSjoerg // replaces them by "%xx" where xx is their hexadecimal value. For
435906f32e7eSjoerg // example, replaces "=" with "%3D".  This algorithm is O(strlen(str))
436006f32e7eSjoerg // in both time and space -- important as the input str may contain an
436106f32e7eSjoerg // arbitrarily long test failure message and stack trace.
UrlEncode(const char * str)4362*da58b97aSjoerg std::string StreamingListener::UrlEncode(const char* str) {
4363*da58b97aSjoerg   std::string result;
436406f32e7eSjoerg   result.reserve(strlen(str) + 1);
436506f32e7eSjoerg   for (char ch = *str; ch != '\0'; ch = *++str) {
436606f32e7eSjoerg     switch (ch) {
436706f32e7eSjoerg       case '%':
436806f32e7eSjoerg       case '=':
436906f32e7eSjoerg       case '&':
437006f32e7eSjoerg       case '\n':
437106f32e7eSjoerg         result.append("%" + String::FormatByte(static_cast<unsigned char>(ch)));
437206f32e7eSjoerg         break;
437306f32e7eSjoerg       default:
437406f32e7eSjoerg         result.push_back(ch);
437506f32e7eSjoerg         break;
437606f32e7eSjoerg     }
437706f32e7eSjoerg   }
437806f32e7eSjoerg   return result;
437906f32e7eSjoerg }
438006f32e7eSjoerg 
MakeConnection()438106f32e7eSjoerg void StreamingListener::SocketWriter::MakeConnection() {
438206f32e7eSjoerg   GTEST_CHECK_(sockfd_ == -1)
438306f32e7eSjoerg       << "MakeConnection() can't be called when there is already a connection.";
438406f32e7eSjoerg 
438506f32e7eSjoerg   addrinfo hints;
438606f32e7eSjoerg   memset(&hints, 0, sizeof(hints));
438706f32e7eSjoerg   hints.ai_family = AF_UNSPEC;    // To allow both IPv4 and IPv6 addresses.
438806f32e7eSjoerg   hints.ai_socktype = SOCK_STREAM;
4389*da58b97aSjoerg   addrinfo* servinfo = nullptr;
439006f32e7eSjoerg 
439106f32e7eSjoerg   // Use the getaddrinfo() to get a linked list of IP addresses for
439206f32e7eSjoerg   // the given host name.
439306f32e7eSjoerg   const int error_num = getaddrinfo(
439406f32e7eSjoerg       host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
439506f32e7eSjoerg   if (error_num != 0) {
439606f32e7eSjoerg     GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: "
439706f32e7eSjoerg                         << gai_strerror(error_num);
439806f32e7eSjoerg   }
439906f32e7eSjoerg 
440006f32e7eSjoerg   // Loop through all the results and connect to the first we can.
4401*da58b97aSjoerg   for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != nullptr;
440206f32e7eSjoerg        cur_addr = cur_addr->ai_next) {
440306f32e7eSjoerg     sockfd_ = socket(
440406f32e7eSjoerg         cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol);
440506f32e7eSjoerg     if (sockfd_ != -1) {
440606f32e7eSjoerg       // Connect the client socket to the server socket.
440706f32e7eSjoerg       if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
440806f32e7eSjoerg         close(sockfd_);
440906f32e7eSjoerg         sockfd_ = -1;
441006f32e7eSjoerg       }
441106f32e7eSjoerg     }
441206f32e7eSjoerg   }
441306f32e7eSjoerg 
441406f32e7eSjoerg   freeaddrinfo(servinfo);  // all done with this structure
441506f32e7eSjoerg 
441606f32e7eSjoerg   if (sockfd_ == -1) {
441706f32e7eSjoerg     GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to "
441806f32e7eSjoerg                         << host_name_ << ":" << port_num_;
441906f32e7eSjoerg   }
442006f32e7eSjoerg }
442106f32e7eSjoerg 
442206f32e7eSjoerg // End of class Streaming Listener
442306f32e7eSjoerg #endif  // GTEST_CAN_STREAM_RESULTS__
442406f32e7eSjoerg 
442506f32e7eSjoerg // class OsStackTraceGetter
442606f32e7eSjoerg 
442706f32e7eSjoerg const char* const OsStackTraceGetterInterface::kElidedFramesMarker =
442806f32e7eSjoerg     "... " GTEST_NAME_ " internal frames ...";
442906f32e7eSjoerg 
CurrentStackTrace(int max_depth,int skip_count)4430*da58b97aSjoerg std::string OsStackTraceGetter::CurrentStackTrace(int max_depth, int skip_count)
4431*da58b97aSjoerg     GTEST_LOCK_EXCLUDED_(mutex_) {
4432*da58b97aSjoerg #if GTEST_HAS_ABSL
4433*da58b97aSjoerg   std::string result;
4434*da58b97aSjoerg 
4435*da58b97aSjoerg   if (max_depth <= 0) {
4436*da58b97aSjoerg     return result;
443706f32e7eSjoerg   }
443806f32e7eSjoerg 
4439*da58b97aSjoerg   max_depth = std::min(max_depth, kMaxStackTraceDepth);
4440*da58b97aSjoerg 
4441*da58b97aSjoerg   std::vector<void*> raw_stack(max_depth);
4442*da58b97aSjoerg   // Skips the frames requested by the caller, plus this function.
4443*da58b97aSjoerg   const int raw_stack_size =
4444*da58b97aSjoerg       absl::GetStackTrace(&raw_stack[0], max_depth, skip_count + 1);
4445*da58b97aSjoerg 
4446*da58b97aSjoerg   void* caller_frame = nullptr;
4447*da58b97aSjoerg   {
4448*da58b97aSjoerg     MutexLock lock(&mutex_);
4449*da58b97aSjoerg     caller_frame = caller_frame_;
4450*da58b97aSjoerg   }
4451*da58b97aSjoerg 
4452*da58b97aSjoerg   for (int i = 0; i < raw_stack_size; ++i) {
4453*da58b97aSjoerg     if (raw_stack[i] == caller_frame &&
4454*da58b97aSjoerg         !GTEST_FLAG(show_internal_stack_frames)) {
4455*da58b97aSjoerg       // Add a marker to the trace and stop adding frames.
4456*da58b97aSjoerg       absl::StrAppend(&result, kElidedFramesMarker, "\n");
4457*da58b97aSjoerg       break;
4458*da58b97aSjoerg     }
4459*da58b97aSjoerg 
4460*da58b97aSjoerg     char tmp[1024];
4461*da58b97aSjoerg     const char* symbol = "(unknown)";
4462*da58b97aSjoerg     if (absl::Symbolize(raw_stack[i], tmp, sizeof(tmp))) {
4463*da58b97aSjoerg       symbol = tmp;
4464*da58b97aSjoerg     }
4465*da58b97aSjoerg 
4466*da58b97aSjoerg     char line[1024];
4467*da58b97aSjoerg     snprintf(line, sizeof(line), "  %p: %s\n", raw_stack[i], symbol);
4468*da58b97aSjoerg     result += line;
4469*da58b97aSjoerg   }
4470*da58b97aSjoerg 
4471*da58b97aSjoerg   return result;
4472*da58b97aSjoerg 
4473*da58b97aSjoerg #else  // !GTEST_HAS_ABSL
4474*da58b97aSjoerg   static_cast<void>(max_depth);
4475*da58b97aSjoerg   static_cast<void>(skip_count);
4476*da58b97aSjoerg   return "";
4477*da58b97aSjoerg #endif  // GTEST_HAS_ABSL
4478*da58b97aSjoerg }
4479*da58b97aSjoerg 
UponLeavingGTest()4480*da58b97aSjoerg void OsStackTraceGetter::UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_) {
4481*da58b97aSjoerg #if GTEST_HAS_ABSL
4482*da58b97aSjoerg   void* caller_frame = nullptr;
4483*da58b97aSjoerg   if (absl::GetStackTrace(&caller_frame, 1, 3) <= 0) {
4484*da58b97aSjoerg     caller_frame = nullptr;
4485*da58b97aSjoerg   }
4486*da58b97aSjoerg 
4487*da58b97aSjoerg   MutexLock lock(&mutex_);
4488*da58b97aSjoerg   caller_frame_ = caller_frame;
4489*da58b97aSjoerg #endif  // GTEST_HAS_ABSL
4490*da58b97aSjoerg }
449106f32e7eSjoerg 
449206f32e7eSjoerg // A helper class that creates the premature-exit file in its
449306f32e7eSjoerg // constructor and deletes the file in its destructor.
449406f32e7eSjoerg class ScopedPrematureExitFile {
449506f32e7eSjoerg  public:
ScopedPrematureExitFile(const char * premature_exit_filepath)449606f32e7eSjoerg   explicit ScopedPrematureExitFile(const char* premature_exit_filepath)
4497*da58b97aSjoerg       : premature_exit_filepath_(premature_exit_filepath ?
4498*da58b97aSjoerg                                  premature_exit_filepath : "") {
449906f32e7eSjoerg     // If a path to the premature-exit file is specified...
4500*da58b97aSjoerg     if (!premature_exit_filepath_.empty()) {
450106f32e7eSjoerg       // create the file with a single "0" character in it.  I/O
450206f32e7eSjoerg       // errors are ignored as there's nothing better we can do and we
450306f32e7eSjoerg       // don't want to fail the test because of this.
450406f32e7eSjoerg       FILE* pfile = posix::FOpen(premature_exit_filepath, "w");
450506f32e7eSjoerg       fwrite("0", 1, 1, pfile);
450606f32e7eSjoerg       fclose(pfile);
450706f32e7eSjoerg     }
450806f32e7eSjoerg   }
450906f32e7eSjoerg 
~ScopedPrematureExitFile()451006f32e7eSjoerg   ~ScopedPrematureExitFile() {
4511*da58b97aSjoerg     if (!premature_exit_filepath_.empty()) {
4512*da58b97aSjoerg       int retval = remove(premature_exit_filepath_.c_str());
4513*da58b97aSjoerg       if (retval) {
4514*da58b97aSjoerg         GTEST_LOG_(ERROR) << "Failed to remove premature exit filepath \""
4515*da58b97aSjoerg                           << premature_exit_filepath_ << "\" with error "
4516*da58b97aSjoerg                           << retval;
4517*da58b97aSjoerg       }
451806f32e7eSjoerg     }
451906f32e7eSjoerg   }
452006f32e7eSjoerg 
452106f32e7eSjoerg  private:
4522*da58b97aSjoerg   const std::string premature_exit_filepath_;
452306f32e7eSjoerg 
452406f32e7eSjoerg   GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedPrematureExitFile);
452506f32e7eSjoerg };
452606f32e7eSjoerg 
452706f32e7eSjoerg }  // namespace internal
452806f32e7eSjoerg 
452906f32e7eSjoerg // class TestEventListeners
453006f32e7eSjoerg 
TestEventListeners()453106f32e7eSjoerg TestEventListeners::TestEventListeners()
453206f32e7eSjoerg     : repeater_(new internal::TestEventRepeater()),
4533*da58b97aSjoerg       default_result_printer_(nullptr),
4534*da58b97aSjoerg       default_xml_generator_(nullptr) {}
453506f32e7eSjoerg 
~TestEventListeners()453606f32e7eSjoerg TestEventListeners::~TestEventListeners() { delete repeater_; }
453706f32e7eSjoerg 
453806f32e7eSjoerg // Returns the standard listener responsible for the default console
453906f32e7eSjoerg // output.  Can be removed from the listeners list to shut down default
454006f32e7eSjoerg // console output.  Note that removing this object from the listener list
454106f32e7eSjoerg // with Release transfers its ownership to the user.
Append(TestEventListener * listener)454206f32e7eSjoerg void TestEventListeners::Append(TestEventListener* listener) {
454306f32e7eSjoerg   repeater_->Append(listener);
454406f32e7eSjoerg }
454506f32e7eSjoerg 
454606f32e7eSjoerg // Removes the given event listener from the list and returns it.  It then
454706f32e7eSjoerg // becomes the caller's responsibility to delete the listener. Returns
454806f32e7eSjoerg // NULL if the listener is not found in the list.
Release(TestEventListener * listener)454906f32e7eSjoerg TestEventListener* TestEventListeners::Release(TestEventListener* listener) {
455006f32e7eSjoerg   if (listener == default_result_printer_)
4551*da58b97aSjoerg     default_result_printer_ = nullptr;
455206f32e7eSjoerg   else if (listener == default_xml_generator_)
4553*da58b97aSjoerg     default_xml_generator_ = nullptr;
455406f32e7eSjoerg   return repeater_->Release(listener);
455506f32e7eSjoerg }
455606f32e7eSjoerg 
455706f32e7eSjoerg // Returns repeater that broadcasts the TestEventListener events to all
455806f32e7eSjoerg // subscribers.
repeater()455906f32e7eSjoerg TestEventListener* TestEventListeners::repeater() { return repeater_; }
456006f32e7eSjoerg 
456106f32e7eSjoerg // Sets the default_result_printer attribute to the provided listener.
456206f32e7eSjoerg // The listener is also added to the listener list and previous
456306f32e7eSjoerg // default_result_printer is removed from it and deleted. The listener can
456406f32e7eSjoerg // also be NULL in which case it will not be added to the list. Does
456506f32e7eSjoerg // nothing if the previous and the current listener objects are the same.
SetDefaultResultPrinter(TestEventListener * listener)456606f32e7eSjoerg void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
456706f32e7eSjoerg   if (default_result_printer_ != listener) {
456806f32e7eSjoerg     // It is an error to pass this method a listener that is already in the
456906f32e7eSjoerg     // list.
457006f32e7eSjoerg     delete Release(default_result_printer_);
457106f32e7eSjoerg     default_result_printer_ = listener;
4572*da58b97aSjoerg     if (listener != nullptr) Append(listener);
457306f32e7eSjoerg   }
457406f32e7eSjoerg }
457506f32e7eSjoerg 
457606f32e7eSjoerg // Sets the default_xml_generator attribute to the provided listener.  The
457706f32e7eSjoerg // listener is also added to the listener list and previous
457806f32e7eSjoerg // default_xml_generator is removed from it and deleted. The listener can
457906f32e7eSjoerg // also be NULL in which case it will not be added to the list. Does
458006f32e7eSjoerg // nothing if the previous and the current listener objects are the same.
SetDefaultXmlGenerator(TestEventListener * listener)458106f32e7eSjoerg void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
458206f32e7eSjoerg   if (default_xml_generator_ != listener) {
458306f32e7eSjoerg     // It is an error to pass this method a listener that is already in the
458406f32e7eSjoerg     // list.
458506f32e7eSjoerg     delete Release(default_xml_generator_);
458606f32e7eSjoerg     default_xml_generator_ = listener;
4587*da58b97aSjoerg     if (listener != nullptr) Append(listener);
458806f32e7eSjoerg   }
458906f32e7eSjoerg }
459006f32e7eSjoerg 
459106f32e7eSjoerg // Controls whether events will be forwarded by the repeater to the
459206f32e7eSjoerg // listeners in the list.
EventForwardingEnabled() const459306f32e7eSjoerg bool TestEventListeners::EventForwardingEnabled() const {
459406f32e7eSjoerg   return repeater_->forwarding_enabled();
459506f32e7eSjoerg }
459606f32e7eSjoerg 
SuppressEventForwarding()459706f32e7eSjoerg void TestEventListeners::SuppressEventForwarding() {
459806f32e7eSjoerg   repeater_->set_forwarding_enabled(false);
459906f32e7eSjoerg }
460006f32e7eSjoerg 
460106f32e7eSjoerg // class UnitTest
460206f32e7eSjoerg 
460306f32e7eSjoerg // Gets the singleton UnitTest object.  The first time this method is
460406f32e7eSjoerg // called, a UnitTest object is constructed and returned.  Consecutive
460506f32e7eSjoerg // calls will return the same object.
460606f32e7eSjoerg //
460706f32e7eSjoerg // We don't protect this under mutex_ as a user is not supposed to
460806f32e7eSjoerg // call this before main() starts, from which point on the return
460906f32e7eSjoerg // value will never change.
GetInstance()461006f32e7eSjoerg UnitTest* UnitTest::GetInstance() {
461106f32e7eSjoerg   // CodeGear C++Builder insists on a public destructor for the
461206f32e7eSjoerg   // default implementation.  Use this implementation to keep good OO
461306f32e7eSjoerg   // design with private destructor.
461406f32e7eSjoerg 
4615*da58b97aSjoerg #if defined(__BORLANDC__)
461606f32e7eSjoerg   static UnitTest* const instance = new UnitTest;
461706f32e7eSjoerg   return instance;
461806f32e7eSjoerg #else
461906f32e7eSjoerg   static UnitTest instance;
462006f32e7eSjoerg   return &instance;
4621*da58b97aSjoerg #endif  // defined(__BORLANDC__)
462206f32e7eSjoerg }
462306f32e7eSjoerg 
4624*da58b97aSjoerg // Gets the number of successful test suites.
successful_test_suite_count() const4625*da58b97aSjoerg int UnitTest::successful_test_suite_count() const {
4626*da58b97aSjoerg   return impl()->successful_test_suite_count();
462706f32e7eSjoerg }
462806f32e7eSjoerg 
4629*da58b97aSjoerg // Gets the number of failed test suites.
failed_test_suite_count() const4630*da58b97aSjoerg int UnitTest::failed_test_suite_count() const {
4631*da58b97aSjoerg   return impl()->failed_test_suite_count();
463206f32e7eSjoerg }
463306f32e7eSjoerg 
4634*da58b97aSjoerg // Gets the number of all test suites.
total_test_suite_count() const4635*da58b97aSjoerg int UnitTest::total_test_suite_count() const {
4636*da58b97aSjoerg   return impl()->total_test_suite_count();
463706f32e7eSjoerg }
463806f32e7eSjoerg 
4639*da58b97aSjoerg // Gets the number of all test suites that contain at least one test
464006f32e7eSjoerg // that should run.
test_suite_to_run_count() const4641*da58b97aSjoerg int UnitTest::test_suite_to_run_count() const {
4642*da58b97aSjoerg   return impl()->test_suite_to_run_count();
464306f32e7eSjoerg }
464406f32e7eSjoerg 
4645*da58b97aSjoerg //  Legacy API is deprecated but still available
4646*da58b97aSjoerg #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
successful_test_case_count() const4647*da58b97aSjoerg int UnitTest::successful_test_case_count() const {
4648*da58b97aSjoerg   return impl()->successful_test_suite_count();
4649*da58b97aSjoerg }
failed_test_case_count() const4650*da58b97aSjoerg int UnitTest::failed_test_case_count() const {
4651*da58b97aSjoerg   return impl()->failed_test_suite_count();
4652*da58b97aSjoerg }
total_test_case_count() const4653*da58b97aSjoerg int UnitTest::total_test_case_count() const {
4654*da58b97aSjoerg   return impl()->total_test_suite_count();
4655*da58b97aSjoerg }
test_case_to_run_count() const4656*da58b97aSjoerg int UnitTest::test_case_to_run_count() const {
4657*da58b97aSjoerg   return impl()->test_suite_to_run_count();
4658*da58b97aSjoerg }
4659*da58b97aSjoerg #endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI_
4660*da58b97aSjoerg 
466106f32e7eSjoerg // Gets the number of successful tests.
successful_test_count() const466206f32e7eSjoerg int UnitTest::successful_test_count() const {
466306f32e7eSjoerg   return impl()->successful_test_count();
466406f32e7eSjoerg }
466506f32e7eSjoerg 
4666*da58b97aSjoerg // Gets the number of skipped tests.
skipped_test_count() const4667*da58b97aSjoerg int UnitTest::skipped_test_count() const {
4668*da58b97aSjoerg   return impl()->skipped_test_count();
4669*da58b97aSjoerg }
4670*da58b97aSjoerg 
467106f32e7eSjoerg // Gets the number of failed tests.
failed_test_count() const467206f32e7eSjoerg int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
467306f32e7eSjoerg 
467406f32e7eSjoerg // Gets the number of disabled tests that will be reported in the XML report.
reportable_disabled_test_count() const467506f32e7eSjoerg int UnitTest::reportable_disabled_test_count() const {
467606f32e7eSjoerg   return impl()->reportable_disabled_test_count();
467706f32e7eSjoerg }
467806f32e7eSjoerg 
467906f32e7eSjoerg // Gets the number of disabled tests.
disabled_test_count() const468006f32e7eSjoerg int UnitTest::disabled_test_count() const {
468106f32e7eSjoerg   return impl()->disabled_test_count();
468206f32e7eSjoerg }
468306f32e7eSjoerg 
468406f32e7eSjoerg // Gets the number of tests to be printed in the XML report.
reportable_test_count() const468506f32e7eSjoerg int UnitTest::reportable_test_count() const {
468606f32e7eSjoerg   return impl()->reportable_test_count();
468706f32e7eSjoerg }
468806f32e7eSjoerg 
468906f32e7eSjoerg // Gets the number of all tests.
total_test_count() const469006f32e7eSjoerg int UnitTest::total_test_count() const { return impl()->total_test_count(); }
469106f32e7eSjoerg 
469206f32e7eSjoerg // Gets the number of tests that should run.
test_to_run_count() const469306f32e7eSjoerg int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
469406f32e7eSjoerg 
469506f32e7eSjoerg // Gets the time of the test program start, in ms from the start of the
469606f32e7eSjoerg // UNIX epoch.
start_timestamp() const469706f32e7eSjoerg internal::TimeInMillis UnitTest::start_timestamp() const {
469806f32e7eSjoerg     return impl()->start_timestamp();
469906f32e7eSjoerg }
470006f32e7eSjoerg 
470106f32e7eSjoerg // Gets the elapsed time, in milliseconds.
elapsed_time() const470206f32e7eSjoerg internal::TimeInMillis UnitTest::elapsed_time() const {
470306f32e7eSjoerg   return impl()->elapsed_time();
470406f32e7eSjoerg }
470506f32e7eSjoerg 
4706*da58b97aSjoerg // Returns true if and only if the unit test passed (i.e. all test suites
4707*da58b97aSjoerg // passed).
Passed() const470806f32e7eSjoerg bool UnitTest::Passed() const { return impl()->Passed(); }
470906f32e7eSjoerg 
4710*da58b97aSjoerg // Returns true if and only if the unit test failed (i.e. some test suite
4711*da58b97aSjoerg // failed or something outside of all tests failed).
Failed() const471206f32e7eSjoerg bool UnitTest::Failed() const { return impl()->Failed(); }
471306f32e7eSjoerg 
4714*da58b97aSjoerg // Gets the i-th test suite among all the test suites. i can range from 0 to
4715*da58b97aSjoerg // total_test_suite_count() - 1. If i is not in that range, returns NULL.
GetTestSuite(int i) const4716*da58b97aSjoerg const TestSuite* UnitTest::GetTestSuite(int i) const {
4717*da58b97aSjoerg   return impl()->GetTestSuite(i);
4718*da58b97aSjoerg }
4719*da58b97aSjoerg 
4720*da58b97aSjoerg //  Legacy API is deprecated but still available
4721*da58b97aSjoerg #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
GetTestCase(int i) const472206f32e7eSjoerg const TestCase* UnitTest::GetTestCase(int i) const {
472306f32e7eSjoerg   return impl()->GetTestCase(i);
472406f32e7eSjoerg }
4725*da58b97aSjoerg #endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI_
472606f32e7eSjoerg 
472706f32e7eSjoerg // Returns the TestResult containing information on test failures and
4728*da58b97aSjoerg // properties logged outside of individual test suites.
ad_hoc_test_result() const472906f32e7eSjoerg const TestResult& UnitTest::ad_hoc_test_result() const {
473006f32e7eSjoerg   return *impl()->ad_hoc_test_result();
473106f32e7eSjoerg }
473206f32e7eSjoerg 
4733*da58b97aSjoerg // Gets the i-th test suite among all the test suites. i can range from 0 to
4734*da58b97aSjoerg // total_test_suite_count() - 1. If i is not in that range, returns NULL.
GetMutableTestSuite(int i)4735*da58b97aSjoerg TestSuite* UnitTest::GetMutableTestSuite(int i) {
4736*da58b97aSjoerg   return impl()->GetMutableSuiteCase(i);
473706f32e7eSjoerg }
473806f32e7eSjoerg 
473906f32e7eSjoerg // Returns the list of event listeners that can be used to track events
474006f32e7eSjoerg // inside Google Test.
listeners()474106f32e7eSjoerg TestEventListeners& UnitTest::listeners() {
474206f32e7eSjoerg   return *impl()->listeners();
474306f32e7eSjoerg }
474406f32e7eSjoerg 
474506f32e7eSjoerg // Registers and returns a global test environment.  When a test
474606f32e7eSjoerg // program is run, all global test environments will be set-up in the
474706f32e7eSjoerg // order they were registered.  After all tests in the program have
474806f32e7eSjoerg // finished, all global test environments will be torn-down in the
474906f32e7eSjoerg // *reverse* order they were registered.
475006f32e7eSjoerg //
475106f32e7eSjoerg // The UnitTest object takes ownership of the given environment.
475206f32e7eSjoerg //
475306f32e7eSjoerg // We don't protect this under mutex_, as we only support calling it
475406f32e7eSjoerg // from the main thread.
AddEnvironment(Environment * env)475506f32e7eSjoerg Environment* UnitTest::AddEnvironment(Environment* env) {
4756*da58b97aSjoerg   if (env == nullptr) {
4757*da58b97aSjoerg     return nullptr;
475806f32e7eSjoerg   }
475906f32e7eSjoerg 
476006f32e7eSjoerg   impl_->environments().push_back(env);
476106f32e7eSjoerg   return env;
476206f32e7eSjoerg }
476306f32e7eSjoerg 
476406f32e7eSjoerg // Adds a TestPartResult to the current TestResult object.  All Google Test
476506f32e7eSjoerg // assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
476606f32e7eSjoerg // this to report their results.  The user code should use the
476706f32e7eSjoerg // assertion macros instead of calling this directly.
AddTestPartResult(TestPartResult::Type result_type,const char * file_name,int line_number,const std::string & message,const std::string & os_stack_trace)476806f32e7eSjoerg void UnitTest::AddTestPartResult(
476906f32e7eSjoerg     TestPartResult::Type result_type,
477006f32e7eSjoerg     const char* file_name,
477106f32e7eSjoerg     int line_number,
477206f32e7eSjoerg     const std::string& message,
477306f32e7eSjoerg     const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_) {
477406f32e7eSjoerg   Message msg;
477506f32e7eSjoerg   msg << message;
477606f32e7eSjoerg 
477706f32e7eSjoerg   internal::MutexLock lock(&mutex_);
477806f32e7eSjoerg   if (impl_->gtest_trace_stack().size() > 0) {
477906f32e7eSjoerg     msg << "\n" << GTEST_NAME_ << " trace:";
478006f32e7eSjoerg 
4781*da58b97aSjoerg     for (size_t i = impl_->gtest_trace_stack().size(); i > 0; --i) {
478206f32e7eSjoerg       const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
478306f32e7eSjoerg       msg << "\n" << internal::FormatFileLocation(trace.file, trace.line)
478406f32e7eSjoerg           << " " << trace.message;
478506f32e7eSjoerg     }
478606f32e7eSjoerg   }
478706f32e7eSjoerg 
4788*da58b97aSjoerg   if (os_stack_trace.c_str() != nullptr && !os_stack_trace.empty()) {
478906f32e7eSjoerg     msg << internal::kStackTraceMarker << os_stack_trace;
479006f32e7eSjoerg   }
479106f32e7eSjoerg 
4792*da58b97aSjoerg   const TestPartResult result = TestPartResult(
4793*da58b97aSjoerg       result_type, file_name, line_number, msg.GetString().c_str());
479406f32e7eSjoerg   impl_->GetTestPartResultReporterForCurrentThread()->
479506f32e7eSjoerg       ReportTestPartResult(result);
479606f32e7eSjoerg 
4797*da58b97aSjoerg   if (result_type != TestPartResult::kSuccess &&
4798*da58b97aSjoerg       result_type != TestPartResult::kSkip) {
479906f32e7eSjoerg     // gtest_break_on_failure takes precedence over
480006f32e7eSjoerg     // gtest_throw_on_failure.  This allows a user to set the latter
480106f32e7eSjoerg     // in the code (perhaps in order to use Google Test assertions
480206f32e7eSjoerg     // with another testing framework) and specify the former on the
480306f32e7eSjoerg     // command line for debugging.
480406f32e7eSjoerg     if (GTEST_FLAG(break_on_failure)) {
480506f32e7eSjoerg #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
480606f32e7eSjoerg       // Using DebugBreak on Windows allows gtest to still break into a debugger
480706f32e7eSjoerg       // when a failure happens and both the --gtest_break_on_failure and
480806f32e7eSjoerg       // the --gtest_catch_exceptions flags are specified.
480906f32e7eSjoerg       DebugBreak();
4810*da58b97aSjoerg #elif (!defined(__native_client__)) &&            \
4811*da58b97aSjoerg     ((defined(__clang__) || defined(__GNUC__)) && \
4812*da58b97aSjoerg      (defined(__x86_64__) || defined(__i386__)))
4813*da58b97aSjoerg       // with clang/gcc we can achieve the same effect on x86 by invoking int3
4814*da58b97aSjoerg       asm("int3");
481506f32e7eSjoerg #else
4816*da58b97aSjoerg       // Dereference nullptr through a volatile pointer to prevent the compiler
481706f32e7eSjoerg       // from removing. We use this rather than abort() or __builtin_trap() for
4818*da58b97aSjoerg       // portability: some debuggers don't correctly trap abort().
4819*da58b97aSjoerg       *static_cast<volatile int*>(nullptr) = 1;
482006f32e7eSjoerg #endif  // GTEST_OS_WINDOWS
482106f32e7eSjoerg     } else if (GTEST_FLAG(throw_on_failure)) {
482206f32e7eSjoerg #if GTEST_HAS_EXCEPTIONS
482306f32e7eSjoerg       throw internal::GoogleTestFailureException(result);
482406f32e7eSjoerg #else
482506f32e7eSjoerg       // We cannot call abort() as it generates a pop-up in debug mode
482606f32e7eSjoerg       // that cannot be suppressed in VC 7.1 or below.
482706f32e7eSjoerg       exit(1);
482806f32e7eSjoerg #endif
482906f32e7eSjoerg     }
483006f32e7eSjoerg   }
483106f32e7eSjoerg }
483206f32e7eSjoerg 
483306f32e7eSjoerg // Adds a TestProperty to the current TestResult object when invoked from
4834*da58b97aSjoerg // inside a test, to current TestSuite's ad_hoc_test_result_ when invoked
4835*da58b97aSjoerg // from SetUpTestSuite or TearDownTestSuite, or to the global property set
483606f32e7eSjoerg // when invoked elsewhere.  If the result already contains a property with
483706f32e7eSjoerg // the same key, the value will be updated.
RecordProperty(const std::string & key,const std::string & value)483806f32e7eSjoerg void UnitTest::RecordProperty(const std::string& key,
483906f32e7eSjoerg                               const std::string& value) {
484006f32e7eSjoerg   impl_->RecordProperty(TestProperty(key, value));
484106f32e7eSjoerg }
484206f32e7eSjoerg 
484306f32e7eSjoerg // Runs all tests in this UnitTest object and prints the result.
484406f32e7eSjoerg // Returns 0 if successful, or 1 otherwise.
484506f32e7eSjoerg //
484606f32e7eSjoerg // We don't protect this under mutex_, as we only support calling it
484706f32e7eSjoerg // from the main thread.
Run()484806f32e7eSjoerg int UnitTest::Run() {
484906f32e7eSjoerg   const bool in_death_test_child_process =
485006f32e7eSjoerg       internal::GTEST_FLAG(internal_run_death_test).length() > 0;
485106f32e7eSjoerg 
485206f32e7eSjoerg   // Google Test implements this protocol for catching that a test
485306f32e7eSjoerg   // program exits before returning control to Google Test:
485406f32e7eSjoerg   //
485506f32e7eSjoerg   //   1. Upon start, Google Test creates a file whose absolute path
485606f32e7eSjoerg   //      is specified by the environment variable
485706f32e7eSjoerg   //      TEST_PREMATURE_EXIT_FILE.
485806f32e7eSjoerg   //   2. When Google Test has finished its work, it deletes the file.
485906f32e7eSjoerg   //
486006f32e7eSjoerg   // This allows a test runner to set TEST_PREMATURE_EXIT_FILE before
486106f32e7eSjoerg   // running a Google-Test-based test program and check the existence
486206f32e7eSjoerg   // of the file at the end of the test execution to see if it has
486306f32e7eSjoerg   // exited prematurely.
486406f32e7eSjoerg 
486506f32e7eSjoerg   // If we are in the child process of a death test, don't
486606f32e7eSjoerg   // create/delete the premature exit file, as doing so is unnecessary
486706f32e7eSjoerg   // and will confuse the parent process.  Otherwise, create/delete
486806f32e7eSjoerg   // the file upon entering/leaving this function.  If the program
486906f32e7eSjoerg   // somehow exits before this function has a chance to return, the
487006f32e7eSjoerg   // premature-exit file will be left undeleted, causing a test runner
487106f32e7eSjoerg   // that understands the premature-exit-file protocol to report the
487206f32e7eSjoerg   // test as having failed.
487306f32e7eSjoerg   const internal::ScopedPrematureExitFile premature_exit_file(
4874*da58b97aSjoerg       in_death_test_child_process
4875*da58b97aSjoerg           ? nullptr
4876*da58b97aSjoerg           : internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE"));
487706f32e7eSjoerg 
487806f32e7eSjoerg   // Captures the value of GTEST_FLAG(catch_exceptions).  This value will be
487906f32e7eSjoerg   // used for the duration of the program.
488006f32e7eSjoerg   impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions));
488106f32e7eSjoerg 
4882*da58b97aSjoerg #if GTEST_OS_WINDOWS
488306f32e7eSjoerg   // Either the user wants Google Test to catch exceptions thrown by the
488406f32e7eSjoerg   // tests or this is executing in the context of death test child
488506f32e7eSjoerg   // process. In either case the user does not want to see pop-up dialogs
488606f32e7eSjoerg   // about crashes - they are expected.
488706f32e7eSjoerg   if (impl()->catch_exceptions() || in_death_test_child_process) {
488806f32e7eSjoerg # if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
488906f32e7eSjoerg     // SetErrorMode doesn't exist on CE.
489006f32e7eSjoerg     SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
489106f32e7eSjoerg                  SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
489206f32e7eSjoerg # endif  // !GTEST_OS_WINDOWS_MOBILE
489306f32e7eSjoerg 
489406f32e7eSjoerg # if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
489506f32e7eSjoerg     // Death test children can be terminated with _abort().  On Windows,
489606f32e7eSjoerg     // _abort() can show a dialog with a warning message.  This forces the
489706f32e7eSjoerg     // abort message to go to stderr instead.
489806f32e7eSjoerg     _set_error_mode(_OUT_TO_STDERR);
489906f32e7eSjoerg # endif
490006f32e7eSjoerg 
4901*da58b97aSjoerg # if defined(_MSC_VER) && !GTEST_OS_WINDOWS_MOBILE
490206f32e7eSjoerg     // In the debug version, Visual Studio pops up a separate dialog
490306f32e7eSjoerg     // offering a choice to debug the aborted program. We need to suppress
490406f32e7eSjoerg     // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
490506f32e7eSjoerg     // executed. Google Test will notify the user of any unexpected
490606f32e7eSjoerg     // failure via stderr.
490706f32e7eSjoerg     if (!GTEST_FLAG(break_on_failure))
490806f32e7eSjoerg       _set_abort_behavior(
490906f32e7eSjoerg           0x0,                                    // Clear the following flags:
491006f32e7eSjoerg           _WRITE_ABORT_MSG | _CALL_REPORTFAULT);  // pop-up window, core dump.
491106f32e7eSjoerg # endif
4912*da58b97aSjoerg 
4913*da58b97aSjoerg     // In debug mode, the Windows CRT can crash with an assertion over invalid
4914*da58b97aSjoerg     // input (e.g. passing an invalid file descriptor).  The default handling
4915*da58b97aSjoerg     // for these assertions is to pop up a dialog and wait for user input.
4916*da58b97aSjoerg     // Instead ask the CRT to dump such assertions to stderr non-interactively.
4917*da58b97aSjoerg     if (!IsDebuggerPresent()) {
4918*da58b97aSjoerg       (void)_CrtSetReportMode(_CRT_ASSERT,
4919*da58b97aSjoerg                               _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
4920*da58b97aSjoerg       (void)_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
492106f32e7eSjoerg     }
4922*da58b97aSjoerg   }
4923*da58b97aSjoerg #endif  // GTEST_OS_WINDOWS
492406f32e7eSjoerg 
492506f32e7eSjoerg   return internal::HandleExceptionsInMethodIfSupported(
492606f32e7eSjoerg       impl(),
492706f32e7eSjoerg       &internal::UnitTestImpl::RunAllTests,
492806f32e7eSjoerg       "auxiliary test code (environments or event listeners)") ? 0 : 1;
492906f32e7eSjoerg }
493006f32e7eSjoerg 
493106f32e7eSjoerg // Returns the working directory when the first TEST() or TEST_F() was
493206f32e7eSjoerg // executed.
original_working_dir() const493306f32e7eSjoerg const char* UnitTest::original_working_dir() const {
493406f32e7eSjoerg   return impl_->original_working_dir_.c_str();
493506f32e7eSjoerg }
493606f32e7eSjoerg 
4937*da58b97aSjoerg // Returns the TestSuite object for the test that's currently running,
493806f32e7eSjoerg // or NULL if no test is running.
current_test_suite() const4939*da58b97aSjoerg const TestSuite* UnitTest::current_test_suite() const
4940*da58b97aSjoerg     GTEST_LOCK_EXCLUDED_(mutex_) {
4941*da58b97aSjoerg   internal::MutexLock lock(&mutex_);
4942*da58b97aSjoerg   return impl_->current_test_suite();
4943*da58b97aSjoerg }
4944*da58b97aSjoerg 
4945*da58b97aSjoerg // Legacy API is still available but deprecated
4946*da58b97aSjoerg #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
current_test_case() const494706f32e7eSjoerg const TestCase* UnitTest::current_test_case() const
494806f32e7eSjoerg     GTEST_LOCK_EXCLUDED_(mutex_) {
494906f32e7eSjoerg   internal::MutexLock lock(&mutex_);
4950*da58b97aSjoerg   return impl_->current_test_suite();
495106f32e7eSjoerg }
4952*da58b97aSjoerg #endif
495306f32e7eSjoerg 
495406f32e7eSjoerg // Returns the TestInfo object for the test that's currently running,
495506f32e7eSjoerg // or NULL if no test is running.
current_test_info() const495606f32e7eSjoerg const TestInfo* UnitTest::current_test_info() const
495706f32e7eSjoerg     GTEST_LOCK_EXCLUDED_(mutex_) {
495806f32e7eSjoerg   internal::MutexLock lock(&mutex_);
495906f32e7eSjoerg   return impl_->current_test_info();
496006f32e7eSjoerg }
496106f32e7eSjoerg 
496206f32e7eSjoerg // Returns the random seed used at the start of the current test run.
random_seed() const496306f32e7eSjoerg int UnitTest::random_seed() const { return impl_->random_seed(); }
496406f32e7eSjoerg 
4965*da58b97aSjoerg // Returns ParameterizedTestSuiteRegistry object used to keep track of
496606f32e7eSjoerg // value-parameterized tests and instantiate and register them.
4967*da58b97aSjoerg internal::ParameterizedTestSuiteRegistry&
parameterized_test_registry()4968*da58b97aSjoerg UnitTest::parameterized_test_registry() GTEST_LOCK_EXCLUDED_(mutex_) {
496906f32e7eSjoerg   return impl_->parameterized_test_registry();
497006f32e7eSjoerg }
497106f32e7eSjoerg 
497206f32e7eSjoerg // Creates an empty UnitTest.
UnitTest()497306f32e7eSjoerg UnitTest::UnitTest() {
497406f32e7eSjoerg   impl_ = new internal::UnitTestImpl(this);
497506f32e7eSjoerg }
497606f32e7eSjoerg 
497706f32e7eSjoerg // Destructor of UnitTest.
~UnitTest()497806f32e7eSjoerg UnitTest::~UnitTest() {
497906f32e7eSjoerg   delete impl_;
498006f32e7eSjoerg }
498106f32e7eSjoerg 
498206f32e7eSjoerg // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
498306f32e7eSjoerg // Google Test trace stack.
PushGTestTrace(const internal::TraceInfo & trace)498406f32e7eSjoerg void UnitTest::PushGTestTrace(const internal::TraceInfo& trace)
498506f32e7eSjoerg     GTEST_LOCK_EXCLUDED_(mutex_) {
498606f32e7eSjoerg   internal::MutexLock lock(&mutex_);
498706f32e7eSjoerg   impl_->gtest_trace_stack().push_back(trace);
498806f32e7eSjoerg }
498906f32e7eSjoerg 
499006f32e7eSjoerg // Pops a trace from the per-thread Google Test trace stack.
PopGTestTrace()499106f32e7eSjoerg void UnitTest::PopGTestTrace()
499206f32e7eSjoerg     GTEST_LOCK_EXCLUDED_(mutex_) {
499306f32e7eSjoerg   internal::MutexLock lock(&mutex_);
499406f32e7eSjoerg   impl_->gtest_trace_stack().pop_back();
499506f32e7eSjoerg }
499606f32e7eSjoerg 
499706f32e7eSjoerg namespace internal {
499806f32e7eSjoerg 
UnitTestImpl(UnitTest * parent)499906f32e7eSjoerg UnitTestImpl::UnitTestImpl(UnitTest* parent)
500006f32e7eSjoerg     : parent_(parent),
500106f32e7eSjoerg       GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355 /* using this in initializer */)
500206f32e7eSjoerg           default_global_test_part_result_reporter_(this),
500306f32e7eSjoerg       default_per_thread_test_part_result_reporter_(this),
5004*da58b97aSjoerg       GTEST_DISABLE_MSC_WARNINGS_POP_() global_test_part_result_repoter_(
500506f32e7eSjoerg           &default_global_test_part_result_reporter_),
500606f32e7eSjoerg       per_thread_test_part_result_reporter_(
500706f32e7eSjoerg           &default_per_thread_test_part_result_reporter_),
500806f32e7eSjoerg       parameterized_test_registry_(),
500906f32e7eSjoerg       parameterized_tests_registered_(false),
5010*da58b97aSjoerg       last_death_test_suite_(-1),
5011*da58b97aSjoerg       current_test_suite_(nullptr),
5012*da58b97aSjoerg       current_test_info_(nullptr),
501306f32e7eSjoerg       ad_hoc_test_result_(),
5014*da58b97aSjoerg       os_stack_trace_getter_(nullptr),
501506f32e7eSjoerg       post_flag_parse_init_performed_(false),
501606f32e7eSjoerg       random_seed_(0),  // Will be overridden by the flag before first use.
501706f32e7eSjoerg       random_(0),       // Will be reseeded before first use.
501806f32e7eSjoerg       start_timestamp_(0),
501906f32e7eSjoerg       elapsed_time_(0),
502006f32e7eSjoerg #if GTEST_HAS_DEATH_TEST
502106f32e7eSjoerg       death_test_factory_(new DefaultDeathTestFactory),
502206f32e7eSjoerg #endif
502306f32e7eSjoerg       // Will be overridden by the flag before first use.
502406f32e7eSjoerg       catch_exceptions_(false) {
502506f32e7eSjoerg   listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);
502606f32e7eSjoerg }
502706f32e7eSjoerg 
~UnitTestImpl()502806f32e7eSjoerg UnitTestImpl::~UnitTestImpl() {
5029*da58b97aSjoerg   // Deletes every TestSuite.
5030*da58b97aSjoerg   ForEach(test_suites_, internal::Delete<TestSuite>);
503106f32e7eSjoerg 
503206f32e7eSjoerg   // Deletes every Environment.
503306f32e7eSjoerg   ForEach(environments_, internal::Delete<Environment>);
503406f32e7eSjoerg 
503506f32e7eSjoerg   delete os_stack_trace_getter_;
503606f32e7eSjoerg }
503706f32e7eSjoerg 
503806f32e7eSjoerg // Adds a TestProperty to the current TestResult object when invoked in a
5039*da58b97aSjoerg // context of a test, to current test suite's ad_hoc_test_result when invoke
5040*da58b97aSjoerg // from SetUpTestSuite/TearDownTestSuite, or to the global property set
504106f32e7eSjoerg // otherwise.  If the result already contains a property with the same key,
504206f32e7eSjoerg // the value will be updated.
RecordProperty(const TestProperty & test_property)504306f32e7eSjoerg void UnitTestImpl::RecordProperty(const TestProperty& test_property) {
504406f32e7eSjoerg   std::string xml_element;
504506f32e7eSjoerg   TestResult* test_result;  // TestResult appropriate for property recording.
504606f32e7eSjoerg 
5047*da58b97aSjoerg   if (current_test_info_ != nullptr) {
504806f32e7eSjoerg     xml_element = "testcase";
504906f32e7eSjoerg     test_result = &(current_test_info_->result_);
5050*da58b97aSjoerg   } else if (current_test_suite_ != nullptr) {
505106f32e7eSjoerg     xml_element = "testsuite";
5052*da58b97aSjoerg     test_result = &(current_test_suite_->ad_hoc_test_result_);
505306f32e7eSjoerg   } else {
505406f32e7eSjoerg     xml_element = "testsuites";
505506f32e7eSjoerg     test_result = &ad_hoc_test_result_;
505606f32e7eSjoerg   }
505706f32e7eSjoerg   test_result->RecordProperty(xml_element, test_property);
505806f32e7eSjoerg }
505906f32e7eSjoerg 
506006f32e7eSjoerg #if GTEST_HAS_DEATH_TEST
506106f32e7eSjoerg // Disables event forwarding if the control is currently in a death test
506206f32e7eSjoerg // subprocess. Must not be called before InitGoogleTest.
SuppressTestEventsIfInSubprocess()506306f32e7eSjoerg void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
5064*da58b97aSjoerg   if (internal_run_death_test_flag_.get() != nullptr)
506506f32e7eSjoerg     listeners()->SuppressEventForwarding();
506606f32e7eSjoerg }
506706f32e7eSjoerg #endif  // GTEST_HAS_DEATH_TEST
506806f32e7eSjoerg 
506906f32e7eSjoerg // Initializes event listeners performing XML output as specified by
507006f32e7eSjoerg // UnitTestOptions. Must not be called before InitGoogleTest.
ConfigureXmlOutput()507106f32e7eSjoerg void UnitTestImpl::ConfigureXmlOutput() {
507206f32e7eSjoerg   const std::string& output_format = UnitTestOptions::GetOutputFormat();
507306f32e7eSjoerg   if (output_format == "xml") {
507406f32e7eSjoerg     listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
507506f32e7eSjoerg         UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
5076*da58b97aSjoerg   } else if (output_format == "json") {
5077*da58b97aSjoerg     listeners()->SetDefaultXmlGenerator(new JsonUnitTestResultPrinter(
5078*da58b97aSjoerg         UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
507906f32e7eSjoerg   } else if (output_format != "") {
5080*da58b97aSjoerg     GTEST_LOG_(WARNING) << "WARNING: unrecognized output format \""
5081*da58b97aSjoerg                         << output_format << "\" ignored.";
508206f32e7eSjoerg   }
508306f32e7eSjoerg }
508406f32e7eSjoerg 
508506f32e7eSjoerg #if GTEST_CAN_STREAM_RESULTS_
508606f32e7eSjoerg // Initializes event listeners for streaming test results in string form.
508706f32e7eSjoerg // Must not be called before InitGoogleTest.
ConfigureStreamingOutput()508806f32e7eSjoerg void UnitTestImpl::ConfigureStreamingOutput() {
508906f32e7eSjoerg   const std::string& target = GTEST_FLAG(stream_result_to);
509006f32e7eSjoerg   if (!target.empty()) {
509106f32e7eSjoerg     const size_t pos = target.find(':');
509206f32e7eSjoerg     if (pos != std::string::npos) {
509306f32e7eSjoerg       listeners()->Append(new StreamingListener(target.substr(0, pos),
509406f32e7eSjoerg                                                 target.substr(pos+1)));
509506f32e7eSjoerg     } else {
5096*da58b97aSjoerg       GTEST_LOG_(WARNING) << "unrecognized streaming target \"" << target
5097*da58b97aSjoerg                           << "\" ignored.";
509806f32e7eSjoerg     }
509906f32e7eSjoerg   }
510006f32e7eSjoerg }
510106f32e7eSjoerg #endif  // GTEST_CAN_STREAM_RESULTS_
510206f32e7eSjoerg 
510306f32e7eSjoerg // Performs initialization dependent upon flag values obtained in
510406f32e7eSjoerg // ParseGoogleTestFlagsOnly.  Is called from InitGoogleTest after the call to
510506f32e7eSjoerg // ParseGoogleTestFlagsOnly.  In case a user neglects to call InitGoogleTest
510606f32e7eSjoerg // this function is also called from RunAllTests.  Since this function can be
510706f32e7eSjoerg // called more than once, it has to be idempotent.
PostFlagParsingInit()510806f32e7eSjoerg void UnitTestImpl::PostFlagParsingInit() {
510906f32e7eSjoerg   // Ensures that this function does not execute more than once.
511006f32e7eSjoerg   if (!post_flag_parse_init_performed_) {
511106f32e7eSjoerg     post_flag_parse_init_performed_ = true;
511206f32e7eSjoerg 
511306f32e7eSjoerg #if defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
511406f32e7eSjoerg     // Register to send notifications about key process state changes.
511506f32e7eSjoerg     listeners()->Append(new GTEST_CUSTOM_TEST_EVENT_LISTENER_());
511606f32e7eSjoerg #endif  // defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
511706f32e7eSjoerg 
511806f32e7eSjoerg #if GTEST_HAS_DEATH_TEST
511906f32e7eSjoerg     InitDeathTestSubprocessControlInfo();
512006f32e7eSjoerg     SuppressTestEventsIfInSubprocess();
512106f32e7eSjoerg #endif  // GTEST_HAS_DEATH_TEST
512206f32e7eSjoerg 
512306f32e7eSjoerg     // Registers parameterized tests. This makes parameterized tests
512406f32e7eSjoerg     // available to the UnitTest reflection API without running
512506f32e7eSjoerg     // RUN_ALL_TESTS.
512606f32e7eSjoerg     RegisterParameterizedTests();
512706f32e7eSjoerg 
512806f32e7eSjoerg     // Configures listeners for XML output. This makes it possible for users
512906f32e7eSjoerg     // to shut down the default XML output before invoking RUN_ALL_TESTS.
513006f32e7eSjoerg     ConfigureXmlOutput();
513106f32e7eSjoerg 
513206f32e7eSjoerg #if GTEST_CAN_STREAM_RESULTS_
513306f32e7eSjoerg     // Configures listeners for streaming test results to the specified server.
513406f32e7eSjoerg     ConfigureStreamingOutput();
513506f32e7eSjoerg #endif  // GTEST_CAN_STREAM_RESULTS_
5136*da58b97aSjoerg 
5137*da58b97aSjoerg #if GTEST_HAS_ABSL
5138*da58b97aSjoerg     if (GTEST_FLAG(install_failure_signal_handler)) {
5139*da58b97aSjoerg       absl::FailureSignalHandlerOptions options;
5140*da58b97aSjoerg       absl::InstallFailureSignalHandler(options);
5141*da58b97aSjoerg     }
5142*da58b97aSjoerg #endif  // GTEST_HAS_ABSL
514306f32e7eSjoerg   }
514406f32e7eSjoerg }
514506f32e7eSjoerg 
5146*da58b97aSjoerg // A predicate that checks the name of a TestSuite against a known
514706f32e7eSjoerg // value.
514806f32e7eSjoerg //
514906f32e7eSjoerg // This is used for implementation of the UnitTest class only.  We put
515006f32e7eSjoerg // it in the anonymous namespace to prevent polluting the outer
515106f32e7eSjoerg // namespace.
515206f32e7eSjoerg //
5153*da58b97aSjoerg // TestSuiteNameIs is copyable.
5154*da58b97aSjoerg class TestSuiteNameIs {
515506f32e7eSjoerg  public:
515606f32e7eSjoerg   // Constructor.
TestSuiteNameIs(const std::string & name)5157*da58b97aSjoerg   explicit TestSuiteNameIs(const std::string& name) : name_(name) {}
515806f32e7eSjoerg 
5159*da58b97aSjoerg   // Returns true if and only if the name of test_suite matches name_.
operator ()(const TestSuite * test_suite) const5160*da58b97aSjoerg   bool operator()(const TestSuite* test_suite) const {
5161*da58b97aSjoerg     return test_suite != nullptr &&
5162*da58b97aSjoerg            strcmp(test_suite->name(), name_.c_str()) == 0;
516306f32e7eSjoerg   }
516406f32e7eSjoerg 
516506f32e7eSjoerg  private:
516606f32e7eSjoerg   std::string name_;
516706f32e7eSjoerg };
516806f32e7eSjoerg 
5169*da58b97aSjoerg // Finds and returns a TestSuite with the given name.  If one doesn't
517006f32e7eSjoerg // exist, creates one and returns it.  It's the CALLER'S
517106f32e7eSjoerg // RESPONSIBILITY to ensure that this function is only called WHEN THE
517206f32e7eSjoerg // TESTS ARE NOT SHUFFLED.
517306f32e7eSjoerg //
517406f32e7eSjoerg // Arguments:
517506f32e7eSjoerg //
5176*da58b97aSjoerg //   test_suite_name: name of the test suite
5177*da58b97aSjoerg //   type_param:     the name of the test suite's type parameter, or NULL if
5178*da58b97aSjoerg //                   this is not a typed or a type-parameterized test suite.
5179*da58b97aSjoerg //   set_up_tc:      pointer to the function that sets up the test suite
5180*da58b97aSjoerg //   tear_down_tc:   pointer to the function that tears down the test suite
GetTestSuite(const char * test_suite_name,const char * type_param,internal::SetUpTestSuiteFunc set_up_tc,internal::TearDownTestSuiteFunc tear_down_tc)5181*da58b97aSjoerg TestSuite* UnitTestImpl::GetTestSuite(
5182*da58b97aSjoerg     const char* test_suite_name, const char* type_param,
5183*da58b97aSjoerg     internal::SetUpTestSuiteFunc set_up_tc,
5184*da58b97aSjoerg     internal::TearDownTestSuiteFunc tear_down_tc) {
5185*da58b97aSjoerg   // Can we find a TestSuite with the given name?
5186*da58b97aSjoerg   const auto test_suite =
5187*da58b97aSjoerg       std::find_if(test_suites_.rbegin(), test_suites_.rend(),
5188*da58b97aSjoerg                    TestSuiteNameIs(test_suite_name));
518906f32e7eSjoerg 
5190*da58b97aSjoerg   if (test_suite != test_suites_.rend()) return *test_suite;
519106f32e7eSjoerg 
519206f32e7eSjoerg   // No.  Let's create one.
5193*da58b97aSjoerg   auto* const new_test_suite =
5194*da58b97aSjoerg       new TestSuite(test_suite_name, type_param, set_up_tc, tear_down_tc);
519506f32e7eSjoerg 
5196*da58b97aSjoerg   // Is this a death test suite?
5197*da58b97aSjoerg   if (internal::UnitTestOptions::MatchesFilter(test_suite_name,
5198*da58b97aSjoerg                                                kDeathTestSuiteFilter)) {
5199*da58b97aSjoerg     // Yes.  Inserts the test suite after the last death test suite
5200*da58b97aSjoerg     // defined so far.  This only works when the test suites haven't
520106f32e7eSjoerg     // been shuffled.  Otherwise we may end up running a death test
520206f32e7eSjoerg     // after a non-death test.
5203*da58b97aSjoerg     ++last_death_test_suite_;
5204*da58b97aSjoerg     test_suites_.insert(test_suites_.begin() + last_death_test_suite_,
5205*da58b97aSjoerg                         new_test_suite);
520606f32e7eSjoerg   } else {
520706f32e7eSjoerg     // No.  Appends to the end of the list.
5208*da58b97aSjoerg     test_suites_.push_back(new_test_suite);
520906f32e7eSjoerg   }
521006f32e7eSjoerg 
5211*da58b97aSjoerg   test_suite_indices_.push_back(static_cast<int>(test_suite_indices_.size()));
5212*da58b97aSjoerg   return new_test_suite;
521306f32e7eSjoerg }
521406f32e7eSjoerg 
521506f32e7eSjoerg // Helpers for setting up / tearing down the given environment.  They
521606f32e7eSjoerg // are for use in the ForEach() function.
SetUpEnvironment(Environment * env)521706f32e7eSjoerg static void SetUpEnvironment(Environment* env) { env->SetUp(); }
TearDownEnvironment(Environment * env)521806f32e7eSjoerg static void TearDownEnvironment(Environment* env) { env->TearDown(); }
521906f32e7eSjoerg 
522006f32e7eSjoerg // Runs all tests in this UnitTest object, prints the result, and
522106f32e7eSjoerg // returns true if all tests are successful.  If any exception is
522206f32e7eSjoerg // thrown during a test, the test is considered to be failed, but the
522306f32e7eSjoerg // rest of the tests will still be run.
522406f32e7eSjoerg //
522506f32e7eSjoerg // When parameterized tests are enabled, it expands and registers
522606f32e7eSjoerg // parameterized tests first in RegisterParameterizedTests().
522706f32e7eSjoerg // All other functions called from RunAllTests() may safely assume that
522806f32e7eSjoerg // parameterized tests are ready to be counted and run.
RunAllTests()522906f32e7eSjoerg bool UnitTestImpl::RunAllTests() {
5230*da58b97aSjoerg   // True if and only if Google Test is initialized before RUN_ALL_TESTS() is
5231*da58b97aSjoerg   // called.
5232*da58b97aSjoerg   const bool gtest_is_initialized_before_run_all_tests = GTestIsInitialized();
523306f32e7eSjoerg 
523406f32e7eSjoerg   // Do not run any test if the --help flag was specified.
523506f32e7eSjoerg   if (g_help_flag)
523606f32e7eSjoerg     return true;
523706f32e7eSjoerg 
523806f32e7eSjoerg   // Repeats the call to the post-flag parsing initialization in case the
523906f32e7eSjoerg   // user didn't call InitGoogleTest.
524006f32e7eSjoerg   PostFlagParsingInit();
524106f32e7eSjoerg 
524206f32e7eSjoerg   // Even if sharding is not on, test runners may want to use the
524306f32e7eSjoerg   // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
524406f32e7eSjoerg   // protocol.
524506f32e7eSjoerg   internal::WriteToShardStatusFileIfNeeded();
524606f32e7eSjoerg 
5247*da58b97aSjoerg   // True if and only if we are in a subprocess for running a thread-safe-style
524806f32e7eSjoerg   // death test.
524906f32e7eSjoerg   bool in_subprocess_for_death_test = false;
525006f32e7eSjoerg 
525106f32e7eSjoerg #if GTEST_HAS_DEATH_TEST
5252*da58b97aSjoerg   in_subprocess_for_death_test =
5253*da58b97aSjoerg       (internal_run_death_test_flag_.get() != nullptr);
525406f32e7eSjoerg # if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
525506f32e7eSjoerg   if (in_subprocess_for_death_test) {
525606f32e7eSjoerg     GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_();
525706f32e7eSjoerg   }
525806f32e7eSjoerg # endif  // defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
525906f32e7eSjoerg #endif  // GTEST_HAS_DEATH_TEST
526006f32e7eSjoerg 
526106f32e7eSjoerg   const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
526206f32e7eSjoerg                                         in_subprocess_for_death_test);
526306f32e7eSjoerg 
526406f32e7eSjoerg   // Compares the full test names with the filter to decide which
526506f32e7eSjoerg   // tests to run.
526606f32e7eSjoerg   const bool has_tests_to_run = FilterTests(should_shard
526706f32e7eSjoerg                                               ? HONOR_SHARDING_PROTOCOL
526806f32e7eSjoerg                                               : IGNORE_SHARDING_PROTOCOL) > 0;
526906f32e7eSjoerg 
527006f32e7eSjoerg   // Lists the tests and exits if the --gtest_list_tests flag was specified.
527106f32e7eSjoerg   if (GTEST_FLAG(list_tests)) {
527206f32e7eSjoerg     // This must be called *after* FilterTests() has been called.
527306f32e7eSjoerg     ListTestsMatchingFilter();
527406f32e7eSjoerg     return true;
527506f32e7eSjoerg   }
527606f32e7eSjoerg 
527706f32e7eSjoerg   random_seed_ = GTEST_FLAG(shuffle) ?
527806f32e7eSjoerg       GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;
527906f32e7eSjoerg 
5280*da58b97aSjoerg   // True if and only if at least one test has failed.
528106f32e7eSjoerg   bool failed = false;
528206f32e7eSjoerg 
528306f32e7eSjoerg   TestEventListener* repeater = listeners()->repeater();
528406f32e7eSjoerg 
528506f32e7eSjoerg   start_timestamp_ = GetTimeInMillis();
528606f32e7eSjoerg   repeater->OnTestProgramStart(*parent_);
528706f32e7eSjoerg 
528806f32e7eSjoerg   // How many times to repeat the tests?  We don't want to repeat them
528906f32e7eSjoerg   // when we are inside the subprocess of a death test.
529006f32e7eSjoerg   const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);
529106f32e7eSjoerg   // Repeats forever if the repeat count is negative.
5292*da58b97aSjoerg   const bool gtest_repeat_forever = repeat < 0;
5293*da58b97aSjoerg   for (int i = 0; gtest_repeat_forever || i != repeat; i++) {
529406f32e7eSjoerg     // We want to preserve failures generated by ad-hoc test
529506f32e7eSjoerg     // assertions executed before RUN_ALL_TESTS().
529606f32e7eSjoerg     ClearNonAdHocTestResult();
529706f32e7eSjoerg 
529806f32e7eSjoerg     const TimeInMillis start = GetTimeInMillis();
529906f32e7eSjoerg 
5300*da58b97aSjoerg     // Shuffles test suites and tests if requested.
530106f32e7eSjoerg     if (has_tests_to_run && GTEST_FLAG(shuffle)) {
5302*da58b97aSjoerg       random()->Reseed(static_cast<UInt32>(random_seed_));
530306f32e7eSjoerg       // This should be done before calling OnTestIterationStart(),
530406f32e7eSjoerg       // such that a test event listener can see the actual test order
530506f32e7eSjoerg       // in the event.
530606f32e7eSjoerg       ShuffleTests();
530706f32e7eSjoerg     }
530806f32e7eSjoerg 
530906f32e7eSjoerg     // Tells the unit test event listeners that the tests are about to start.
531006f32e7eSjoerg     repeater->OnTestIterationStart(*parent_, i);
531106f32e7eSjoerg 
5312*da58b97aSjoerg     // Runs each test suite if there is at least one test to run.
531306f32e7eSjoerg     if (has_tests_to_run) {
531406f32e7eSjoerg       // Sets up all environments beforehand.
531506f32e7eSjoerg       repeater->OnEnvironmentsSetUpStart(*parent_);
531606f32e7eSjoerg       ForEach(environments_, SetUpEnvironment);
531706f32e7eSjoerg       repeater->OnEnvironmentsSetUpEnd(*parent_);
531806f32e7eSjoerg 
5319*da58b97aSjoerg       // Runs the tests only if there was no fatal failure or skip triggered
5320*da58b97aSjoerg       // during global set-up.
5321*da58b97aSjoerg       if (Test::IsSkipped()) {
5322*da58b97aSjoerg         // Emit diagnostics when global set-up calls skip, as it will not be
5323*da58b97aSjoerg         // emitted by default.
5324*da58b97aSjoerg         TestResult& test_result =
5325*da58b97aSjoerg             *internal::GetUnitTestImpl()->current_test_result();
5326*da58b97aSjoerg         for (int j = 0; j < test_result.total_part_count(); ++j) {
5327*da58b97aSjoerg           const TestPartResult& test_part_result =
5328*da58b97aSjoerg               test_result.GetTestPartResult(j);
5329*da58b97aSjoerg           if (test_part_result.type() == TestPartResult::kSkip) {
5330*da58b97aSjoerg             const std::string& result = test_part_result.message();
5331*da58b97aSjoerg             printf("%s\n", result.c_str());
5332*da58b97aSjoerg           }
5333*da58b97aSjoerg         }
5334*da58b97aSjoerg         fflush(stdout);
5335*da58b97aSjoerg       } else if (!Test::HasFatalFailure()) {
5336*da58b97aSjoerg         for (int test_index = 0; test_index < total_test_suite_count();
533706f32e7eSjoerg              test_index++) {
5338*da58b97aSjoerg           GetMutableSuiteCase(test_index)->Run();
533906f32e7eSjoerg         }
534006f32e7eSjoerg       }
534106f32e7eSjoerg 
534206f32e7eSjoerg       // Tears down all environments in reverse order afterwards.
534306f32e7eSjoerg       repeater->OnEnvironmentsTearDownStart(*parent_);
534406f32e7eSjoerg       std::for_each(environments_.rbegin(), environments_.rend(),
534506f32e7eSjoerg                     TearDownEnvironment);
534606f32e7eSjoerg       repeater->OnEnvironmentsTearDownEnd(*parent_);
534706f32e7eSjoerg     }
534806f32e7eSjoerg 
534906f32e7eSjoerg     elapsed_time_ = GetTimeInMillis() - start;
535006f32e7eSjoerg 
535106f32e7eSjoerg     // Tells the unit test event listener that the tests have just finished.
535206f32e7eSjoerg     repeater->OnTestIterationEnd(*parent_, i);
535306f32e7eSjoerg 
535406f32e7eSjoerg     // Gets the result and clears it.
535506f32e7eSjoerg     if (!Passed()) {
535606f32e7eSjoerg       failed = true;
535706f32e7eSjoerg     }
535806f32e7eSjoerg 
535906f32e7eSjoerg     // Restores the original test order after the iteration.  This
536006f32e7eSjoerg     // allows the user to quickly repro a failure that happens in the
536106f32e7eSjoerg     // N-th iteration without repeating the first (N - 1) iterations.
536206f32e7eSjoerg     // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in
536306f32e7eSjoerg     // case the user somehow changes the value of the flag somewhere
536406f32e7eSjoerg     // (it's always safe to unshuffle the tests).
536506f32e7eSjoerg     UnshuffleTests();
536606f32e7eSjoerg 
536706f32e7eSjoerg     if (GTEST_FLAG(shuffle)) {
536806f32e7eSjoerg       // Picks a new random seed for each iteration.
536906f32e7eSjoerg       random_seed_ = GetNextRandomSeed(random_seed_);
537006f32e7eSjoerg     }
537106f32e7eSjoerg   }
537206f32e7eSjoerg 
537306f32e7eSjoerg   repeater->OnTestProgramEnd(*parent_);
537406f32e7eSjoerg 
5375*da58b97aSjoerg   if (!gtest_is_initialized_before_run_all_tests) {
5376*da58b97aSjoerg     ColoredPrintf(
5377*da58b97aSjoerg         COLOR_RED,
5378*da58b97aSjoerg         "\nIMPORTANT NOTICE - DO NOT IGNORE:\n"
5379*da58b97aSjoerg         "This test program did NOT call " GTEST_INIT_GOOGLE_TEST_NAME_
5380*da58b97aSjoerg         "() before calling RUN_ALL_TESTS(). This is INVALID. Soon " GTEST_NAME_
5381*da58b97aSjoerg         " will start to enforce the valid usage. "
5382*da58b97aSjoerg         "Please fix it ASAP, or IT WILL START TO FAIL.\n");  // NOLINT
5383*da58b97aSjoerg #if GTEST_FOR_GOOGLE_
5384*da58b97aSjoerg     ColoredPrintf(COLOR_RED,
5385*da58b97aSjoerg                   "For more details, see http://wiki/Main/ValidGUnitMain.\n");
5386*da58b97aSjoerg #endif  // GTEST_FOR_GOOGLE_
5387*da58b97aSjoerg   }
5388*da58b97aSjoerg 
538906f32e7eSjoerg   return !failed;
539006f32e7eSjoerg }
539106f32e7eSjoerg 
539206f32e7eSjoerg // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
539306f32e7eSjoerg // if the variable is present. If a file already exists at this location, this
539406f32e7eSjoerg // function will write over it. If the variable is present, but the file cannot
539506f32e7eSjoerg // be created, prints an error and exits.
WriteToShardStatusFileIfNeeded()539606f32e7eSjoerg void WriteToShardStatusFileIfNeeded() {
539706f32e7eSjoerg   const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);
5398*da58b97aSjoerg   if (test_shard_file != nullptr) {
539906f32e7eSjoerg     FILE* const file = posix::FOpen(test_shard_file, "w");
5400*da58b97aSjoerg     if (file == nullptr) {
540106f32e7eSjoerg       ColoredPrintf(COLOR_RED,
540206f32e7eSjoerg                     "Could not write to the test shard status file \"%s\" "
540306f32e7eSjoerg                     "specified by the %s environment variable.\n",
540406f32e7eSjoerg                     test_shard_file, kTestShardStatusFile);
540506f32e7eSjoerg       fflush(stdout);
540606f32e7eSjoerg       exit(EXIT_FAILURE);
540706f32e7eSjoerg     }
540806f32e7eSjoerg     fclose(file);
540906f32e7eSjoerg   }
541006f32e7eSjoerg }
541106f32e7eSjoerg 
541206f32e7eSjoerg // Checks whether sharding is enabled by examining the relevant
541306f32e7eSjoerg // environment variable values. If the variables are present,
541406f32e7eSjoerg // but inconsistent (i.e., shard_index >= total_shards), prints
541506f32e7eSjoerg // an error and exits. If in_subprocess_for_death_test, sharding is
541606f32e7eSjoerg // disabled because it must only be applied to the original test
541706f32e7eSjoerg // process. Otherwise, we could filter out death tests we intended to execute.
ShouldShard(const char * total_shards_env,const char * shard_index_env,bool in_subprocess_for_death_test)541806f32e7eSjoerg bool ShouldShard(const char* total_shards_env,
541906f32e7eSjoerg                  const char* shard_index_env,
542006f32e7eSjoerg                  bool in_subprocess_for_death_test) {
542106f32e7eSjoerg   if (in_subprocess_for_death_test) {
542206f32e7eSjoerg     return false;
542306f32e7eSjoerg   }
542406f32e7eSjoerg 
542506f32e7eSjoerg   const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1);
542606f32e7eSjoerg   const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1);
542706f32e7eSjoerg 
542806f32e7eSjoerg   if (total_shards == -1 && shard_index == -1) {
542906f32e7eSjoerg     return false;
543006f32e7eSjoerg   } else if (total_shards == -1 && shard_index != -1) {
543106f32e7eSjoerg     const Message msg = Message()
543206f32e7eSjoerg       << "Invalid environment variables: you have "
543306f32e7eSjoerg       << kTestShardIndex << " = " << shard_index
543406f32e7eSjoerg       << ", but have left " << kTestTotalShards << " unset.\n";
5435*da58b97aSjoerg     ColoredPrintf(COLOR_RED, "%s", msg.GetString().c_str());
543606f32e7eSjoerg     fflush(stdout);
543706f32e7eSjoerg     exit(EXIT_FAILURE);
543806f32e7eSjoerg   } else if (total_shards != -1 && shard_index == -1) {
543906f32e7eSjoerg     const Message msg = Message()
544006f32e7eSjoerg       << "Invalid environment variables: you have "
544106f32e7eSjoerg       << kTestTotalShards << " = " << total_shards
544206f32e7eSjoerg       << ", but have left " << kTestShardIndex << " unset.\n";
5443*da58b97aSjoerg     ColoredPrintf(COLOR_RED, "%s", msg.GetString().c_str());
544406f32e7eSjoerg     fflush(stdout);
544506f32e7eSjoerg     exit(EXIT_FAILURE);
544606f32e7eSjoerg   } else if (shard_index < 0 || shard_index >= total_shards) {
544706f32e7eSjoerg     const Message msg = Message()
544806f32e7eSjoerg       << "Invalid environment variables: we require 0 <= "
544906f32e7eSjoerg       << kTestShardIndex << " < " << kTestTotalShards
545006f32e7eSjoerg       << ", but you have " << kTestShardIndex << "=" << shard_index
545106f32e7eSjoerg       << ", " << kTestTotalShards << "=" << total_shards << ".\n";
5452*da58b97aSjoerg     ColoredPrintf(COLOR_RED, "%s", msg.GetString().c_str());
545306f32e7eSjoerg     fflush(stdout);
545406f32e7eSjoerg     exit(EXIT_FAILURE);
545506f32e7eSjoerg   }
545606f32e7eSjoerg 
545706f32e7eSjoerg   return total_shards > 1;
545806f32e7eSjoerg }
545906f32e7eSjoerg 
546006f32e7eSjoerg // Parses the environment variable var as an Int32. If it is unset,
546106f32e7eSjoerg // returns default_val. If it is not an Int32, prints an error
546206f32e7eSjoerg // and aborts.
Int32FromEnvOrDie(const char * var,Int32 default_val)546306f32e7eSjoerg Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) {
546406f32e7eSjoerg   const char* str_val = posix::GetEnv(var);
5465*da58b97aSjoerg   if (str_val == nullptr) {
546606f32e7eSjoerg     return default_val;
546706f32e7eSjoerg   }
546806f32e7eSjoerg 
546906f32e7eSjoerg   Int32 result;
547006f32e7eSjoerg   if (!ParseInt32(Message() << "The value of environment variable " << var,
547106f32e7eSjoerg                   str_val, &result)) {
547206f32e7eSjoerg     exit(EXIT_FAILURE);
547306f32e7eSjoerg   }
547406f32e7eSjoerg   return result;
547506f32e7eSjoerg }
547606f32e7eSjoerg 
547706f32e7eSjoerg // Given the total number of shards, the shard index, and the test id,
5478*da58b97aSjoerg // returns true if and only if the test should be run on this shard. The test id
5479*da58b97aSjoerg // is some arbitrary but unique non-negative integer assigned to each test
548006f32e7eSjoerg // method. Assumes that 0 <= shard_index < total_shards.
ShouldRunTestOnShard(int total_shards,int shard_index,int test_id)548106f32e7eSjoerg bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
548206f32e7eSjoerg   return (test_id % total_shards) == shard_index;
548306f32e7eSjoerg }
548406f32e7eSjoerg 
548506f32e7eSjoerg // Compares the name of each test with the user-specified filter to
548606f32e7eSjoerg // decide whether the test should be run, then records the result in
5487*da58b97aSjoerg // each TestSuite and TestInfo object.
548806f32e7eSjoerg // If shard_tests == true, further filters tests based on sharding
548906f32e7eSjoerg // variables in the environment - see
5490*da58b97aSjoerg // https://github.com/google/googletest/blob/master/googletest/docs/advanced.md
5491*da58b97aSjoerg // . Returns the number of tests that should run.
FilterTests(ReactionToSharding shard_tests)549206f32e7eSjoerg int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
549306f32e7eSjoerg   const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?
549406f32e7eSjoerg       Int32FromEnvOrDie(kTestTotalShards, -1) : -1;
549506f32e7eSjoerg   const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?
549606f32e7eSjoerg       Int32FromEnvOrDie(kTestShardIndex, -1) : -1;
549706f32e7eSjoerg 
549806f32e7eSjoerg   // num_runnable_tests are the number of tests that will
549906f32e7eSjoerg   // run across all shards (i.e., match filter and are not disabled).
550006f32e7eSjoerg   // num_selected_tests are the number of tests to be run on
550106f32e7eSjoerg   // this shard.
550206f32e7eSjoerg   int num_runnable_tests = 0;
550306f32e7eSjoerg   int num_selected_tests = 0;
5504*da58b97aSjoerg   for (auto* test_suite : test_suites_) {
5505*da58b97aSjoerg     const std::string& test_suite_name = test_suite->name();
5506*da58b97aSjoerg     test_suite->set_should_run(false);
550706f32e7eSjoerg 
5508*da58b97aSjoerg     for (size_t j = 0; j < test_suite->test_info_list().size(); j++) {
5509*da58b97aSjoerg       TestInfo* const test_info = test_suite->test_info_list()[j];
551006f32e7eSjoerg       const std::string test_name(test_info->name());
5511*da58b97aSjoerg       // A test is disabled if test suite name or test name matches
551206f32e7eSjoerg       // kDisableTestFilter.
5513*da58b97aSjoerg       const bool is_disabled = internal::UnitTestOptions::MatchesFilter(
5514*da58b97aSjoerg                                    test_suite_name, kDisableTestFilter) ||
5515*da58b97aSjoerg                                internal::UnitTestOptions::MatchesFilter(
5516*da58b97aSjoerg                                    test_name, kDisableTestFilter);
551706f32e7eSjoerg       test_info->is_disabled_ = is_disabled;
551806f32e7eSjoerg 
5519*da58b97aSjoerg       const bool matches_filter = internal::UnitTestOptions::FilterMatchesTest(
5520*da58b97aSjoerg           test_suite_name, test_name);
552106f32e7eSjoerg       test_info->matches_filter_ = matches_filter;
552206f32e7eSjoerg 
552306f32e7eSjoerg       const bool is_runnable =
552406f32e7eSjoerg           (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
552506f32e7eSjoerg           matches_filter;
552606f32e7eSjoerg 
5527*da58b97aSjoerg       const bool is_in_another_shard =
5528*da58b97aSjoerg           shard_tests != IGNORE_SHARDING_PROTOCOL &&
5529*da58b97aSjoerg           !ShouldRunTestOnShard(total_shards, shard_index, num_runnable_tests);
5530*da58b97aSjoerg       test_info->is_in_another_shard_ = is_in_another_shard;
5531*da58b97aSjoerg       const bool is_selected = is_runnable && !is_in_another_shard;
553206f32e7eSjoerg 
553306f32e7eSjoerg       num_runnable_tests += is_runnable;
553406f32e7eSjoerg       num_selected_tests += is_selected;
553506f32e7eSjoerg 
553606f32e7eSjoerg       test_info->should_run_ = is_selected;
5537*da58b97aSjoerg       test_suite->set_should_run(test_suite->should_run() || is_selected);
553806f32e7eSjoerg     }
553906f32e7eSjoerg   }
554006f32e7eSjoerg   return num_selected_tests;
554106f32e7eSjoerg }
554206f32e7eSjoerg 
554306f32e7eSjoerg // Prints the given C-string on a single line by replacing all '\n'
554406f32e7eSjoerg // characters with string "\\n".  If the output takes more than
554506f32e7eSjoerg // max_length characters, only prints the first max_length characters
554606f32e7eSjoerg // and "...".
PrintOnOneLine(const char * str,int max_length)554706f32e7eSjoerg static void PrintOnOneLine(const char* str, int max_length) {
5548*da58b97aSjoerg   if (str != nullptr) {
554906f32e7eSjoerg     for (int i = 0; *str != '\0'; ++str) {
555006f32e7eSjoerg       if (i >= max_length) {
555106f32e7eSjoerg         printf("...");
555206f32e7eSjoerg         break;
555306f32e7eSjoerg       }
555406f32e7eSjoerg       if (*str == '\n') {
555506f32e7eSjoerg         printf("\\n");
555606f32e7eSjoerg         i += 2;
555706f32e7eSjoerg       } else {
555806f32e7eSjoerg         printf("%c", *str);
555906f32e7eSjoerg         ++i;
556006f32e7eSjoerg       }
556106f32e7eSjoerg     }
556206f32e7eSjoerg   }
556306f32e7eSjoerg }
556406f32e7eSjoerg 
556506f32e7eSjoerg // Prints the names of the tests matching the user-specified filter flag.
ListTestsMatchingFilter()556606f32e7eSjoerg void UnitTestImpl::ListTestsMatchingFilter() {
556706f32e7eSjoerg   // Print at most this many characters for each type/value parameter.
556806f32e7eSjoerg   const int kMaxParamLength = 250;
556906f32e7eSjoerg 
5570*da58b97aSjoerg   for (auto* test_suite : test_suites_) {
5571*da58b97aSjoerg     bool printed_test_suite_name = false;
557206f32e7eSjoerg 
5573*da58b97aSjoerg     for (size_t j = 0; j < test_suite->test_info_list().size(); j++) {
5574*da58b97aSjoerg       const TestInfo* const test_info = test_suite->test_info_list()[j];
557506f32e7eSjoerg       if (test_info->matches_filter_) {
5576*da58b97aSjoerg         if (!printed_test_suite_name) {
5577*da58b97aSjoerg           printed_test_suite_name = true;
5578*da58b97aSjoerg           printf("%s.", test_suite->name());
5579*da58b97aSjoerg           if (test_suite->type_param() != nullptr) {
558006f32e7eSjoerg             printf("  # %s = ", kTypeParamLabel);
558106f32e7eSjoerg             // We print the type parameter on a single line to make
558206f32e7eSjoerg             // the output easy to parse by a program.
5583*da58b97aSjoerg             PrintOnOneLine(test_suite->type_param(), kMaxParamLength);
558406f32e7eSjoerg           }
558506f32e7eSjoerg           printf("\n");
558606f32e7eSjoerg         }
558706f32e7eSjoerg         printf("  %s", test_info->name());
5588*da58b97aSjoerg         if (test_info->value_param() != nullptr) {
558906f32e7eSjoerg           printf("  # %s = ", kValueParamLabel);
559006f32e7eSjoerg           // We print the value parameter on a single line to make the
559106f32e7eSjoerg           // output easy to parse by a program.
559206f32e7eSjoerg           PrintOnOneLine(test_info->value_param(), kMaxParamLength);
559306f32e7eSjoerg         }
559406f32e7eSjoerg         printf("\n");
559506f32e7eSjoerg       }
559606f32e7eSjoerg     }
559706f32e7eSjoerg   }
559806f32e7eSjoerg   fflush(stdout);
5599*da58b97aSjoerg   const std::string& output_format = UnitTestOptions::GetOutputFormat();
5600*da58b97aSjoerg   if (output_format == "xml" || output_format == "json") {
5601*da58b97aSjoerg     FILE* fileout = OpenFileForWriting(
5602*da58b97aSjoerg         UnitTestOptions::GetAbsolutePathToOutputFile().c_str());
5603*da58b97aSjoerg     std::stringstream stream;
5604*da58b97aSjoerg     if (output_format == "xml") {
5605*da58b97aSjoerg       XmlUnitTestResultPrinter(
5606*da58b97aSjoerg           UnitTestOptions::GetAbsolutePathToOutputFile().c_str())
5607*da58b97aSjoerg           .PrintXmlTestsList(&stream, test_suites_);
5608*da58b97aSjoerg     } else if (output_format == "json") {
5609*da58b97aSjoerg       JsonUnitTestResultPrinter(
5610*da58b97aSjoerg           UnitTestOptions::GetAbsolutePathToOutputFile().c_str())
5611*da58b97aSjoerg           .PrintJsonTestList(&stream, test_suites_);
5612*da58b97aSjoerg     }
5613*da58b97aSjoerg     fprintf(fileout, "%s", StringStreamToString(&stream).c_str());
5614*da58b97aSjoerg     fclose(fileout);
5615*da58b97aSjoerg   }
561606f32e7eSjoerg }
561706f32e7eSjoerg 
561806f32e7eSjoerg // Sets the OS stack trace getter.
561906f32e7eSjoerg //
562006f32e7eSjoerg // Does nothing if the input and the current OS stack trace getter are
562106f32e7eSjoerg // the same; otherwise, deletes the old getter and makes the input the
562206f32e7eSjoerg // current getter.
set_os_stack_trace_getter(OsStackTraceGetterInterface * getter)562306f32e7eSjoerg void UnitTestImpl::set_os_stack_trace_getter(
562406f32e7eSjoerg     OsStackTraceGetterInterface* getter) {
562506f32e7eSjoerg   if (os_stack_trace_getter_ != getter) {
562606f32e7eSjoerg     delete os_stack_trace_getter_;
562706f32e7eSjoerg     os_stack_trace_getter_ = getter;
562806f32e7eSjoerg   }
562906f32e7eSjoerg }
563006f32e7eSjoerg 
563106f32e7eSjoerg // Returns the current OS stack trace getter if it is not NULL;
563206f32e7eSjoerg // otherwise, creates an OsStackTraceGetter, makes it the current
563306f32e7eSjoerg // getter, and returns it.
os_stack_trace_getter()563406f32e7eSjoerg OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
5635*da58b97aSjoerg   if (os_stack_trace_getter_ == nullptr) {
563606f32e7eSjoerg #ifdef GTEST_OS_STACK_TRACE_GETTER_
563706f32e7eSjoerg     os_stack_trace_getter_ = new GTEST_OS_STACK_TRACE_GETTER_;
563806f32e7eSjoerg #else
563906f32e7eSjoerg     os_stack_trace_getter_ = new OsStackTraceGetter;
564006f32e7eSjoerg #endif  // GTEST_OS_STACK_TRACE_GETTER_
564106f32e7eSjoerg   }
564206f32e7eSjoerg 
564306f32e7eSjoerg   return os_stack_trace_getter_;
564406f32e7eSjoerg }
564506f32e7eSjoerg 
5646*da58b97aSjoerg // Returns the most specific TestResult currently running.
current_test_result()564706f32e7eSjoerg TestResult* UnitTestImpl::current_test_result() {
5648*da58b97aSjoerg   if (current_test_info_ != nullptr) {
5649*da58b97aSjoerg     return &current_test_info_->result_;
5650*da58b97aSjoerg   }
5651*da58b97aSjoerg   if (current_test_suite_ != nullptr) {
5652*da58b97aSjoerg     return &current_test_suite_->ad_hoc_test_result_;
5653*da58b97aSjoerg   }
5654*da58b97aSjoerg   return &ad_hoc_test_result_;
565506f32e7eSjoerg }
565606f32e7eSjoerg 
5657*da58b97aSjoerg // Shuffles all test suites, and the tests within each test suite,
565806f32e7eSjoerg // making sure that death tests are still run first.
ShuffleTests()565906f32e7eSjoerg void UnitTestImpl::ShuffleTests() {
5660*da58b97aSjoerg   // Shuffles the death test suites.
5661*da58b97aSjoerg   ShuffleRange(random(), 0, last_death_test_suite_ + 1, &test_suite_indices_);
566206f32e7eSjoerg 
5663*da58b97aSjoerg   // Shuffles the non-death test suites.
5664*da58b97aSjoerg   ShuffleRange(random(), last_death_test_suite_ + 1,
5665*da58b97aSjoerg                static_cast<int>(test_suites_.size()), &test_suite_indices_);
566606f32e7eSjoerg 
5667*da58b97aSjoerg   // Shuffles the tests inside each test suite.
5668*da58b97aSjoerg   for (auto& test_suite : test_suites_) {
5669*da58b97aSjoerg     test_suite->ShuffleTests(random());
567006f32e7eSjoerg   }
567106f32e7eSjoerg }
567206f32e7eSjoerg 
5673*da58b97aSjoerg // Restores the test suites and tests to their order before the first shuffle.
UnshuffleTests()567406f32e7eSjoerg void UnitTestImpl::UnshuffleTests() {
5675*da58b97aSjoerg   for (size_t i = 0; i < test_suites_.size(); i++) {
5676*da58b97aSjoerg     // Unshuffles the tests in each test suite.
5677*da58b97aSjoerg     test_suites_[i]->UnshuffleTests();
5678*da58b97aSjoerg     // Resets the index of each test suite.
5679*da58b97aSjoerg     test_suite_indices_[i] = static_cast<int>(i);
568006f32e7eSjoerg   }
568106f32e7eSjoerg }
568206f32e7eSjoerg 
568306f32e7eSjoerg // Returns the current OS stack trace as an std::string.
568406f32e7eSjoerg //
568506f32e7eSjoerg // The maximum number of stack frames to be included is specified by
568606f32e7eSjoerg // the gtest_stack_trace_depth flag.  The skip_count parameter
568706f32e7eSjoerg // specifies the number of top frames to be skipped, which doesn't
568806f32e7eSjoerg // count against the number of frames to be included.
568906f32e7eSjoerg //
569006f32e7eSjoerg // For example, if Foo() calls Bar(), which in turn calls
569106f32e7eSjoerg // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
569206f32e7eSjoerg // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
GetCurrentOsStackTraceExceptTop(UnitTest *,int skip_count)569306f32e7eSjoerg std::string GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/,
569406f32e7eSjoerg                                             int skip_count) {
569506f32e7eSjoerg   // We pass skip_count + 1 to skip this wrapper function in addition
569606f32e7eSjoerg   // to what the user really wants to skip.
569706f32e7eSjoerg   return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
569806f32e7eSjoerg }
569906f32e7eSjoerg 
570006f32e7eSjoerg // Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to
570106f32e7eSjoerg // suppress unreachable code warnings.
570206f32e7eSjoerg namespace {
570306f32e7eSjoerg class ClassUniqueToAlwaysTrue {};
570406f32e7eSjoerg }
570506f32e7eSjoerg 
IsTrue(bool condition)570606f32e7eSjoerg bool IsTrue(bool condition) { return condition; }
570706f32e7eSjoerg 
AlwaysTrue()570806f32e7eSjoerg bool AlwaysTrue() {
570906f32e7eSjoerg #if GTEST_HAS_EXCEPTIONS
571006f32e7eSjoerg   // This condition is always false so AlwaysTrue() never actually throws,
571106f32e7eSjoerg   // but it makes the compiler think that it may throw.
571206f32e7eSjoerg   if (IsTrue(false))
571306f32e7eSjoerg     throw ClassUniqueToAlwaysTrue();
571406f32e7eSjoerg #endif  // GTEST_HAS_EXCEPTIONS
571506f32e7eSjoerg   return true;
571606f32e7eSjoerg }
571706f32e7eSjoerg 
571806f32e7eSjoerg // If *pstr starts with the given prefix, modifies *pstr to be right
571906f32e7eSjoerg // past the prefix and returns true; otherwise leaves *pstr unchanged
572006f32e7eSjoerg // and returns false.  None of pstr, *pstr, and prefix can be NULL.
SkipPrefix(const char * prefix,const char ** pstr)572106f32e7eSjoerg bool SkipPrefix(const char* prefix, const char** pstr) {
572206f32e7eSjoerg   const size_t prefix_len = strlen(prefix);
572306f32e7eSjoerg   if (strncmp(*pstr, prefix, prefix_len) == 0) {
572406f32e7eSjoerg     *pstr += prefix_len;
572506f32e7eSjoerg     return true;
572606f32e7eSjoerg   }
572706f32e7eSjoerg   return false;
572806f32e7eSjoerg }
572906f32e7eSjoerg 
573006f32e7eSjoerg // Parses a string as a command line flag.  The string should have
573106f32e7eSjoerg // the format "--flag=value".  When def_optional is true, the "=value"
573206f32e7eSjoerg // part can be omitted.
573306f32e7eSjoerg //
573406f32e7eSjoerg // Returns the value of the flag, or NULL if the parsing failed.
ParseFlagValue(const char * str,const char * flag,bool def_optional)5735*da58b97aSjoerg static const char* ParseFlagValue(const char* str, const char* flag,
573606f32e7eSjoerg                                   bool def_optional) {
573706f32e7eSjoerg   // str and flag must not be NULL.
5738*da58b97aSjoerg   if (str == nullptr || flag == nullptr) return nullptr;
573906f32e7eSjoerg 
574006f32e7eSjoerg   // The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
574106f32e7eSjoerg   const std::string flag_str = std::string("--") + GTEST_FLAG_PREFIX_ + flag;
574206f32e7eSjoerg   const size_t flag_len = flag_str.length();
5743*da58b97aSjoerg   if (strncmp(str, flag_str.c_str(), flag_len) != 0) return nullptr;
574406f32e7eSjoerg 
574506f32e7eSjoerg   // Skips the flag name.
574606f32e7eSjoerg   const char* flag_end = str + flag_len;
574706f32e7eSjoerg 
574806f32e7eSjoerg   // When def_optional is true, it's OK to not have a "=value" part.
574906f32e7eSjoerg   if (def_optional && (flag_end[0] == '\0')) {
575006f32e7eSjoerg     return flag_end;
575106f32e7eSjoerg   }
575206f32e7eSjoerg 
575306f32e7eSjoerg   // If def_optional is true and there are more characters after the
575406f32e7eSjoerg   // flag name, or if def_optional is false, there must be a '=' after
575506f32e7eSjoerg   // the flag name.
5756*da58b97aSjoerg   if (flag_end[0] != '=') return nullptr;
575706f32e7eSjoerg 
575806f32e7eSjoerg   // Returns the string after "=".
575906f32e7eSjoerg   return flag_end + 1;
576006f32e7eSjoerg }
576106f32e7eSjoerg 
576206f32e7eSjoerg // Parses a string for a bool flag, in the form of either
576306f32e7eSjoerg // "--flag=value" or "--flag".
576406f32e7eSjoerg //
576506f32e7eSjoerg // In the former case, the value is taken as true as long as it does
576606f32e7eSjoerg // not start with '0', 'f', or 'F'.
576706f32e7eSjoerg //
576806f32e7eSjoerg // In the latter case, the value is taken as true.
576906f32e7eSjoerg //
577006f32e7eSjoerg // On success, stores the value of the flag in *value, and returns
577106f32e7eSjoerg // true.  On failure, returns false without changing *value.
ParseBoolFlag(const char * str,const char * flag,bool * value)5772*da58b97aSjoerg static bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
577306f32e7eSjoerg   // Gets the value of the flag as a string.
577406f32e7eSjoerg   const char* const value_str = ParseFlagValue(str, flag, true);
577506f32e7eSjoerg 
577606f32e7eSjoerg   // Aborts if the parsing failed.
5777*da58b97aSjoerg   if (value_str == nullptr) return false;
577806f32e7eSjoerg 
577906f32e7eSjoerg   // Converts the string value to a bool.
578006f32e7eSjoerg   *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
578106f32e7eSjoerg   return true;
578206f32e7eSjoerg }
578306f32e7eSjoerg 
578406f32e7eSjoerg // Parses a string for an Int32 flag, in the form of
578506f32e7eSjoerg // "--flag=value".
578606f32e7eSjoerg //
578706f32e7eSjoerg // On success, stores the value of the flag in *value, and returns
578806f32e7eSjoerg // true.  On failure, returns false without changing *value.
ParseInt32Flag(const char * str,const char * flag,Int32 * value)578906f32e7eSjoerg bool ParseInt32Flag(const char* str, const char* flag, Int32* value) {
579006f32e7eSjoerg   // Gets the value of the flag as a string.
579106f32e7eSjoerg   const char* const value_str = ParseFlagValue(str, flag, false);
579206f32e7eSjoerg 
579306f32e7eSjoerg   // Aborts if the parsing failed.
5794*da58b97aSjoerg   if (value_str == nullptr) return false;
579506f32e7eSjoerg 
579606f32e7eSjoerg   // Sets *value to the value of the flag.
579706f32e7eSjoerg   return ParseInt32(Message() << "The value of flag --" << flag,
579806f32e7eSjoerg                     value_str, value);
579906f32e7eSjoerg }
580006f32e7eSjoerg 
580106f32e7eSjoerg // Parses a string for a string flag, in the form of
580206f32e7eSjoerg // "--flag=value".
580306f32e7eSjoerg //
580406f32e7eSjoerg // On success, stores the value of the flag in *value, and returns
580506f32e7eSjoerg // true.  On failure, returns false without changing *value.
5806*da58b97aSjoerg template <typename String>
ParseStringFlag(const char * str,const char * flag,String * value)5807*da58b97aSjoerg static bool ParseStringFlag(const char* str, const char* flag, String* value) {
580806f32e7eSjoerg   // Gets the value of the flag as a string.
580906f32e7eSjoerg   const char* const value_str = ParseFlagValue(str, flag, false);
581006f32e7eSjoerg 
581106f32e7eSjoerg   // Aborts if the parsing failed.
5812*da58b97aSjoerg   if (value_str == nullptr) return false;
581306f32e7eSjoerg 
581406f32e7eSjoerg   // Sets *value to the value of the flag.
581506f32e7eSjoerg   *value = value_str;
581606f32e7eSjoerg   return true;
581706f32e7eSjoerg }
581806f32e7eSjoerg 
581906f32e7eSjoerg // Determines whether a string has a prefix that Google Test uses for its
582006f32e7eSjoerg // flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.
582106f32e7eSjoerg // If Google Test detects that a command line flag has its prefix but is not
582206f32e7eSjoerg // recognized, it will print its help message. Flags starting with
582306f32e7eSjoerg // GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
582406f32e7eSjoerg // internal flags and do not trigger the help message.
HasGoogleTestFlagPrefix(const char * str)582506f32e7eSjoerg static bool HasGoogleTestFlagPrefix(const char* str) {
582606f32e7eSjoerg   return (SkipPrefix("--", &str) ||
582706f32e7eSjoerg           SkipPrefix("-", &str) ||
582806f32e7eSjoerg           SkipPrefix("/", &str)) &&
582906f32e7eSjoerg          !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
583006f32e7eSjoerg          (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
583106f32e7eSjoerg           SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str));
583206f32e7eSjoerg }
583306f32e7eSjoerg 
583406f32e7eSjoerg // Prints a string containing code-encoded text.  The following escape
583506f32e7eSjoerg // sequences can be used in the string to control the text color:
583606f32e7eSjoerg //
583706f32e7eSjoerg //   @@    prints a single '@' character.
583806f32e7eSjoerg //   @R    changes the color to red.
583906f32e7eSjoerg //   @G    changes the color to green.
584006f32e7eSjoerg //   @Y    changes the color to yellow.
584106f32e7eSjoerg //   @D    changes to the default terminal text color.
584206f32e7eSjoerg //
PrintColorEncoded(const char * str)584306f32e7eSjoerg static void PrintColorEncoded(const char* str) {
584406f32e7eSjoerg   GTestColor color = COLOR_DEFAULT;  // The current color.
584506f32e7eSjoerg 
584606f32e7eSjoerg   // Conceptually, we split the string into segments divided by escape
584706f32e7eSjoerg   // sequences.  Then we print one segment at a time.  At the end of
584806f32e7eSjoerg   // each iteration, the str pointer advances to the beginning of the
584906f32e7eSjoerg   // next segment.
585006f32e7eSjoerg   for (;;) {
585106f32e7eSjoerg     const char* p = strchr(str, '@');
5852*da58b97aSjoerg     if (p == nullptr) {
585306f32e7eSjoerg       ColoredPrintf(color, "%s", str);
585406f32e7eSjoerg       return;
585506f32e7eSjoerg     }
585606f32e7eSjoerg 
585706f32e7eSjoerg     ColoredPrintf(color, "%s", std::string(str, p).c_str());
585806f32e7eSjoerg 
585906f32e7eSjoerg     const char ch = p[1];
586006f32e7eSjoerg     str = p + 2;
586106f32e7eSjoerg     if (ch == '@') {
586206f32e7eSjoerg       ColoredPrintf(color, "@");
586306f32e7eSjoerg     } else if (ch == 'D') {
586406f32e7eSjoerg       color = COLOR_DEFAULT;
586506f32e7eSjoerg     } else if (ch == 'R') {
586606f32e7eSjoerg       color = COLOR_RED;
586706f32e7eSjoerg     } else if (ch == 'G') {
586806f32e7eSjoerg       color = COLOR_GREEN;
586906f32e7eSjoerg     } else if (ch == 'Y') {
587006f32e7eSjoerg       color = COLOR_YELLOW;
587106f32e7eSjoerg     } else {
587206f32e7eSjoerg       --str;
587306f32e7eSjoerg     }
587406f32e7eSjoerg   }
587506f32e7eSjoerg }
587606f32e7eSjoerg 
587706f32e7eSjoerg static const char kColorEncodedHelpMessage[] =
587806f32e7eSjoerg "This program contains tests written using " GTEST_NAME_ ". You can use the\n"
587906f32e7eSjoerg "following command line flags to control its behavior:\n"
588006f32e7eSjoerg "\n"
588106f32e7eSjoerg "Test Selection:\n"
588206f32e7eSjoerg "  @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n"
588306f32e7eSjoerg "      List the names of all tests instead of running them. The name of\n"
588406f32e7eSjoerg "      TEST(Foo, Bar) is \"Foo.Bar\".\n"
588506f32e7eSjoerg "  @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS"
588606f32e7eSjoerg     "[@G-@YNEGATIVE_PATTERNS]@D\n"
588706f32e7eSjoerg "      Run only the tests whose name matches one of the positive patterns but\n"
588806f32e7eSjoerg "      none of the negative patterns. '?' matches any single character; '*'\n"
588906f32e7eSjoerg "      matches any substring; ':' separates two patterns.\n"
589006f32e7eSjoerg "  @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n"
589106f32e7eSjoerg "      Run all disabled tests too.\n"
589206f32e7eSjoerg "\n"
589306f32e7eSjoerg "Test Execution:\n"
589406f32e7eSjoerg "  @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n"
589506f32e7eSjoerg "      Run the tests repeatedly; use a negative count to repeat forever.\n"
589606f32e7eSjoerg "  @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n"
589706f32e7eSjoerg "      Randomize tests' orders on every iteration.\n"
589806f32e7eSjoerg "  @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n"
589906f32e7eSjoerg "      Random number seed to use for shuffling test orders (between 1 and\n"
590006f32e7eSjoerg "      99999, or 0 to use a seed based on the current time).\n"
590106f32e7eSjoerg "\n"
590206f32e7eSjoerg "Test Output:\n"
590306f32e7eSjoerg "  @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
590406f32e7eSjoerg "      Enable/disable colored output. The default is @Gauto@D.\n"
590506f32e7eSjoerg "  -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n"
590606f32e7eSjoerg "      Don't print the elapsed time of each test.\n"
5907*da58b97aSjoerg "  @G--" GTEST_FLAG_PREFIX_ "output=@Y(@Gjson@Y|@Gxml@Y)[@G:@YDIRECTORY_PATH@G"
590806f32e7eSjoerg     GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n"
5909*da58b97aSjoerg "      Generate a JSON or XML report in the given directory or with the given\n"
5910*da58b97aSjoerg "      file name. @YFILE_PATH@D defaults to @Gtest_detail.xml@D.\n"
591106f32e7eSjoerg # if GTEST_CAN_STREAM_RESULTS_
591206f32e7eSjoerg "  @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n"
591306f32e7eSjoerg "      Stream test results to the given server.\n"
591406f32e7eSjoerg # endif  // GTEST_CAN_STREAM_RESULTS_
591506f32e7eSjoerg "\n"
591606f32e7eSjoerg "Assertion Behavior:\n"
591706f32e7eSjoerg # if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
591806f32e7eSjoerg "  @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
591906f32e7eSjoerg "      Set the default death test style.\n"
592006f32e7eSjoerg # endif  // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
592106f32e7eSjoerg "  @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n"
592206f32e7eSjoerg "      Turn assertion failures into debugger break-points.\n"
592306f32e7eSjoerg "  @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n"
5924*da58b97aSjoerg "      Turn assertion failures into C++ exceptions for use by an external\n"
5925*da58b97aSjoerg "      test framework.\n"
592606f32e7eSjoerg "  @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n"
592706f32e7eSjoerg "      Do not report exceptions as test failures. Instead, allow them\n"
592806f32e7eSjoerg "      to crash the program or throw a pop-up (on Windows).\n"
592906f32e7eSjoerg "\n"
593006f32e7eSjoerg "Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set "
593106f32e7eSjoerg     "the corresponding\n"
593206f32e7eSjoerg "environment variable of a flag (all letters in upper-case). For example, to\n"
593306f32e7eSjoerg "disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_
593406f32e7eSjoerg     "color=no@D or set\n"
593506f32e7eSjoerg "the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n"
593606f32e7eSjoerg "\n"
593706f32e7eSjoerg "For more information, please read the " GTEST_NAME_ " documentation at\n"
593806f32e7eSjoerg "@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n"
593906f32e7eSjoerg "(not one in your own code or tests), please report it to\n"
594006f32e7eSjoerg "@G<" GTEST_DEV_EMAIL_ ">@D.\n";
594106f32e7eSjoerg 
ParseGoogleTestFlag(const char * const arg)5942*da58b97aSjoerg static bool ParseGoogleTestFlag(const char* const arg) {
594306f32e7eSjoerg   return ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,
594406f32e7eSjoerg                        &GTEST_FLAG(also_run_disabled_tests)) ||
594506f32e7eSjoerg       ParseBoolFlag(arg, kBreakOnFailureFlag,
594606f32e7eSjoerg                     &GTEST_FLAG(break_on_failure)) ||
594706f32e7eSjoerg       ParseBoolFlag(arg, kCatchExceptionsFlag,
594806f32e7eSjoerg                     &GTEST_FLAG(catch_exceptions)) ||
594906f32e7eSjoerg       ParseStringFlag(arg, kColorFlag, &GTEST_FLAG(color)) ||
595006f32e7eSjoerg       ParseStringFlag(arg, kDeathTestStyleFlag,
595106f32e7eSjoerg                       &GTEST_FLAG(death_test_style)) ||
595206f32e7eSjoerg       ParseBoolFlag(arg, kDeathTestUseFork,
595306f32e7eSjoerg                     &GTEST_FLAG(death_test_use_fork)) ||
595406f32e7eSjoerg       ParseStringFlag(arg, kFilterFlag, &GTEST_FLAG(filter)) ||
595506f32e7eSjoerg       ParseStringFlag(arg, kInternalRunDeathTestFlag,
595606f32e7eSjoerg                       &GTEST_FLAG(internal_run_death_test)) ||
595706f32e7eSjoerg       ParseBoolFlag(arg, kListTestsFlag, &GTEST_FLAG(list_tests)) ||
595806f32e7eSjoerg       ParseStringFlag(arg, kOutputFlag, &GTEST_FLAG(output)) ||
595906f32e7eSjoerg       ParseBoolFlag(arg, kPrintTimeFlag, &GTEST_FLAG(print_time)) ||
5960*da58b97aSjoerg       ParseBoolFlag(arg, kPrintUTF8Flag, &GTEST_FLAG(print_utf8)) ||
596106f32e7eSjoerg       ParseInt32Flag(arg, kRandomSeedFlag, &GTEST_FLAG(random_seed)) ||
596206f32e7eSjoerg       ParseInt32Flag(arg, kRepeatFlag, &GTEST_FLAG(repeat)) ||
596306f32e7eSjoerg       ParseBoolFlag(arg, kShuffleFlag, &GTEST_FLAG(shuffle)) ||
596406f32e7eSjoerg       ParseInt32Flag(arg, kStackTraceDepthFlag,
596506f32e7eSjoerg                      &GTEST_FLAG(stack_trace_depth)) ||
596606f32e7eSjoerg       ParseStringFlag(arg, kStreamResultToFlag,
596706f32e7eSjoerg                       &GTEST_FLAG(stream_result_to)) ||
596806f32e7eSjoerg       ParseBoolFlag(arg, kThrowOnFailureFlag,
596906f32e7eSjoerg                     &GTEST_FLAG(throw_on_failure));
597006f32e7eSjoerg }
597106f32e7eSjoerg 
597206f32e7eSjoerg #if GTEST_USE_OWN_FLAGFILE_FLAG_
LoadFlagsFromFile(const std::string & path)5973*da58b97aSjoerg static void LoadFlagsFromFile(const std::string& path) {
597406f32e7eSjoerg   FILE* flagfile = posix::FOpen(path.c_str(), "r");
597506f32e7eSjoerg   if (!flagfile) {
5976*da58b97aSjoerg     GTEST_LOG_(FATAL) << "Unable to open file \"" << GTEST_FLAG(flagfile)
5977*da58b97aSjoerg                       << "\"";
597806f32e7eSjoerg   }
597906f32e7eSjoerg   std::string contents(ReadEntireFile(flagfile));
598006f32e7eSjoerg   posix::FClose(flagfile);
598106f32e7eSjoerg   std::vector<std::string> lines;
598206f32e7eSjoerg   SplitString(contents, '\n', &lines);
598306f32e7eSjoerg   for (size_t i = 0; i < lines.size(); ++i) {
598406f32e7eSjoerg     if (lines[i].empty())
598506f32e7eSjoerg       continue;
598606f32e7eSjoerg     if (!ParseGoogleTestFlag(lines[i].c_str()))
598706f32e7eSjoerg       g_help_flag = true;
598806f32e7eSjoerg   }
598906f32e7eSjoerg }
599006f32e7eSjoerg #endif  // GTEST_USE_OWN_FLAGFILE_FLAG_
599106f32e7eSjoerg 
599206f32e7eSjoerg // Parses the command line for Google Test flags, without initializing
599306f32e7eSjoerg // other parts of Google Test.  The type parameter CharType can be
599406f32e7eSjoerg // instantiated to either char or wchar_t.
599506f32e7eSjoerg template <typename CharType>
ParseGoogleTestFlagsOnlyImpl(int * argc,CharType ** argv)599606f32e7eSjoerg void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
599706f32e7eSjoerg   for (int i = 1; i < *argc; i++) {
599806f32e7eSjoerg     const std::string arg_string = StreamableToString(argv[i]);
599906f32e7eSjoerg     const char* const arg = arg_string.c_str();
600006f32e7eSjoerg 
600106f32e7eSjoerg     using internal::ParseBoolFlag;
600206f32e7eSjoerg     using internal::ParseInt32Flag;
600306f32e7eSjoerg     using internal::ParseStringFlag;
600406f32e7eSjoerg 
600506f32e7eSjoerg     bool remove_flag = false;
600606f32e7eSjoerg     if (ParseGoogleTestFlag(arg)) {
600706f32e7eSjoerg       remove_flag = true;
600806f32e7eSjoerg #if GTEST_USE_OWN_FLAGFILE_FLAG_
600906f32e7eSjoerg     } else if (ParseStringFlag(arg, kFlagfileFlag, &GTEST_FLAG(flagfile))) {
601006f32e7eSjoerg       LoadFlagsFromFile(GTEST_FLAG(flagfile));
601106f32e7eSjoerg       remove_flag = true;
601206f32e7eSjoerg #endif  // GTEST_USE_OWN_FLAGFILE_FLAG_
601306f32e7eSjoerg     } else if (arg_string == "--help" || arg_string == "-h" ||
601406f32e7eSjoerg                arg_string == "-?" || arg_string == "/?" ||
601506f32e7eSjoerg                HasGoogleTestFlagPrefix(arg)) {
601606f32e7eSjoerg       // Both help flag and unrecognized Google Test flags (excluding
601706f32e7eSjoerg       // internal ones) trigger help display.
601806f32e7eSjoerg       g_help_flag = true;
601906f32e7eSjoerg     }
602006f32e7eSjoerg 
602106f32e7eSjoerg     if (remove_flag) {
602206f32e7eSjoerg       // Shift the remainder of the argv list left by one.  Note
602306f32e7eSjoerg       // that argv has (*argc + 1) elements, the last one always being
602406f32e7eSjoerg       // NULL.  The following loop moves the trailing NULL element as
602506f32e7eSjoerg       // well.
602606f32e7eSjoerg       for (int j = i; j != *argc; j++) {
602706f32e7eSjoerg         argv[j] = argv[j + 1];
602806f32e7eSjoerg       }
602906f32e7eSjoerg 
603006f32e7eSjoerg       // Decrements the argument count.
603106f32e7eSjoerg       (*argc)--;
603206f32e7eSjoerg 
603306f32e7eSjoerg       // We also need to decrement the iterator as we just removed
603406f32e7eSjoerg       // an element.
603506f32e7eSjoerg       i--;
603606f32e7eSjoerg     }
603706f32e7eSjoerg   }
603806f32e7eSjoerg 
603906f32e7eSjoerg   if (g_help_flag) {
604006f32e7eSjoerg     // We print the help here instead of in RUN_ALL_TESTS(), as the
604106f32e7eSjoerg     // latter may not be called at all if the user is using Google
604206f32e7eSjoerg     // Test with another testing framework.
604306f32e7eSjoerg     PrintColorEncoded(kColorEncodedHelpMessage);
604406f32e7eSjoerg   }
604506f32e7eSjoerg }
604606f32e7eSjoerg 
604706f32e7eSjoerg // Parses the command line for Google Test flags, without initializing
604806f32e7eSjoerg // other parts of Google Test.
ParseGoogleTestFlagsOnly(int * argc,char ** argv)604906f32e7eSjoerg void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
605006f32e7eSjoerg   ParseGoogleTestFlagsOnlyImpl(argc, argv);
6051*da58b97aSjoerg 
6052*da58b97aSjoerg   // Fix the value of *_NSGetArgc() on macOS, but if and only if
6053*da58b97aSjoerg   // *_NSGetArgv() == argv
6054*da58b97aSjoerg   // Only applicable to char** version of argv
6055*da58b97aSjoerg #if GTEST_OS_MAC
6056*da58b97aSjoerg #ifndef GTEST_OS_IOS
6057*da58b97aSjoerg   if (*_NSGetArgv() == argv) {
6058*da58b97aSjoerg     *_NSGetArgc() = *argc;
6059*da58b97aSjoerg   }
6060*da58b97aSjoerg #endif
6061*da58b97aSjoerg #endif
606206f32e7eSjoerg }
ParseGoogleTestFlagsOnly(int * argc,wchar_t ** argv)606306f32e7eSjoerg void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {
606406f32e7eSjoerg   ParseGoogleTestFlagsOnlyImpl(argc, argv);
606506f32e7eSjoerg }
606606f32e7eSjoerg 
606706f32e7eSjoerg // The internal implementation of InitGoogleTest().
606806f32e7eSjoerg //
606906f32e7eSjoerg // The type parameter CharType can be instantiated to either char or
607006f32e7eSjoerg // wchar_t.
607106f32e7eSjoerg template <typename CharType>
InitGoogleTestImpl(int * argc,CharType ** argv)607206f32e7eSjoerg void InitGoogleTestImpl(int* argc, CharType** argv) {
607306f32e7eSjoerg   // We don't want to run the initialization code twice.
607406f32e7eSjoerg   if (GTestIsInitialized()) return;
607506f32e7eSjoerg 
607606f32e7eSjoerg   if (*argc <= 0) return;
607706f32e7eSjoerg 
607806f32e7eSjoerg   g_argvs.clear();
607906f32e7eSjoerg   for (int i = 0; i != *argc; i++) {
608006f32e7eSjoerg     g_argvs.push_back(StreamableToString(argv[i]));
608106f32e7eSjoerg   }
608206f32e7eSjoerg 
6083*da58b97aSjoerg #if GTEST_HAS_ABSL
6084*da58b97aSjoerg   absl::InitializeSymbolizer(g_argvs[0].c_str());
6085*da58b97aSjoerg #endif  // GTEST_HAS_ABSL
6086*da58b97aSjoerg 
608706f32e7eSjoerg   ParseGoogleTestFlagsOnly(argc, argv);
608806f32e7eSjoerg   GetUnitTestImpl()->PostFlagParsingInit();
608906f32e7eSjoerg }
609006f32e7eSjoerg 
609106f32e7eSjoerg }  // namespace internal
609206f32e7eSjoerg 
609306f32e7eSjoerg // Initializes Google Test.  This must be called before calling
609406f32e7eSjoerg // RUN_ALL_TESTS().  In particular, it parses a command line for the
609506f32e7eSjoerg // flags that Google Test recognizes.  Whenever a Google Test flag is
609606f32e7eSjoerg // seen, it is removed from argv, and *argc is decremented.
609706f32e7eSjoerg //
609806f32e7eSjoerg // No value is returned.  Instead, the Google Test flag variables are
609906f32e7eSjoerg // updated.
610006f32e7eSjoerg //
610106f32e7eSjoerg // Calling the function for the second time has no user-visible effect.
InitGoogleTest(int * argc,char ** argv)610206f32e7eSjoerg void InitGoogleTest(int* argc, char** argv) {
610306f32e7eSjoerg #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
610406f32e7eSjoerg   GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
610506f32e7eSjoerg #else  // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
610606f32e7eSjoerg   internal::InitGoogleTestImpl(argc, argv);
610706f32e7eSjoerg #endif  // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
610806f32e7eSjoerg }
610906f32e7eSjoerg 
611006f32e7eSjoerg // This overloaded version can be used in Windows programs compiled in
611106f32e7eSjoerg // UNICODE mode.
InitGoogleTest(int * argc,wchar_t ** argv)611206f32e7eSjoerg void InitGoogleTest(int* argc, wchar_t** argv) {
611306f32e7eSjoerg #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
611406f32e7eSjoerg   GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
611506f32e7eSjoerg #else  // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
611606f32e7eSjoerg   internal::InitGoogleTestImpl(argc, argv);
611706f32e7eSjoerg #endif  // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
611806f32e7eSjoerg }
611906f32e7eSjoerg 
6120*da58b97aSjoerg // This overloaded version can be used on Arduino/embedded platforms where
6121*da58b97aSjoerg // there is no argc/argv.
InitGoogleTest()6122*da58b97aSjoerg void InitGoogleTest() {
6123*da58b97aSjoerg   // Since Arduino doesn't have a command line, fake out the argc/argv arguments
6124*da58b97aSjoerg   int argc = 1;
6125*da58b97aSjoerg   const auto arg0 = "dummy";
6126*da58b97aSjoerg   char* argv0 = const_cast<char*>(arg0);
6127*da58b97aSjoerg   char** argv = &argv0;
6128*da58b97aSjoerg 
6129*da58b97aSjoerg #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6130*da58b97aSjoerg   GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(&argc, argv);
6131*da58b97aSjoerg #else  // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6132*da58b97aSjoerg   internal::InitGoogleTestImpl(&argc, argv);
6133*da58b97aSjoerg #endif  // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6134*da58b97aSjoerg }
6135*da58b97aSjoerg 
TempDir()6136*da58b97aSjoerg std::string TempDir() {
6137*da58b97aSjoerg #if defined(GTEST_CUSTOM_TEMPDIR_FUNCTION_)
6138*da58b97aSjoerg   return GTEST_CUSTOM_TEMPDIR_FUNCTION_();
6139*da58b97aSjoerg #endif
6140*da58b97aSjoerg 
6141*da58b97aSjoerg #if GTEST_OS_WINDOWS_MOBILE
6142*da58b97aSjoerg   return "\\temp\\";
6143*da58b97aSjoerg #elif GTEST_OS_WINDOWS
6144*da58b97aSjoerg   const char* temp_dir = internal::posix::GetEnv("TEMP");
6145*da58b97aSjoerg   if (temp_dir == nullptr || temp_dir[0] == '\0')
6146*da58b97aSjoerg     return "\\temp\\";
6147*da58b97aSjoerg   else if (temp_dir[strlen(temp_dir) - 1] == '\\')
6148*da58b97aSjoerg     return temp_dir;
6149*da58b97aSjoerg   else
6150*da58b97aSjoerg     return std::string(temp_dir) + "\\";
6151*da58b97aSjoerg #elif GTEST_OS_LINUX_ANDROID
6152*da58b97aSjoerg   return "/sdcard/";
6153*da58b97aSjoerg #else
6154*da58b97aSjoerg   return "/tmp/";
6155*da58b97aSjoerg #endif  // GTEST_OS_WINDOWS_MOBILE
6156*da58b97aSjoerg }
6157*da58b97aSjoerg 
6158*da58b97aSjoerg // Class ScopedTrace
6159*da58b97aSjoerg 
6160*da58b97aSjoerg // Pushes the given source file location and message onto a per-thread
6161*da58b97aSjoerg // trace stack maintained by Google Test.
PushTrace(const char * file,int line,std::string message)6162*da58b97aSjoerg void ScopedTrace::PushTrace(const char* file, int line, std::string message) {
6163*da58b97aSjoerg   internal::TraceInfo trace;
6164*da58b97aSjoerg   trace.file = file;
6165*da58b97aSjoerg   trace.line = line;
6166*da58b97aSjoerg   trace.message.swap(message);
6167*da58b97aSjoerg 
6168*da58b97aSjoerg   UnitTest::GetInstance()->PushGTestTrace(trace);
6169*da58b97aSjoerg }
6170*da58b97aSjoerg 
6171*da58b97aSjoerg // Pops the info pushed by the c'tor.
~ScopedTrace()6172*da58b97aSjoerg ScopedTrace::~ScopedTrace()
6173*da58b97aSjoerg     GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
6174*da58b97aSjoerg   UnitTest::GetInstance()->PopGTestTrace();
6175*da58b97aSjoerg }
6176*da58b97aSjoerg 
617706f32e7eSjoerg }  // namespace testing
6178