1// Copyright 2005, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31//
32// The Google C++ Testing Framework (Google Test)
33
34#include "gtest/gtest.h"
35#include "gtest/internal/custom/gtest.h"
36#include "gtest/gtest-spi.h"
37
38#include <ctype.h>
39#include <math.h>
40#include <stdarg.h>
41#include <stdio.h>
42#include <stdlib.h>
43#include <time.h>
44#include <wchar.h>
45#include <wctype.h>
46
47#include <algorithm>
48#include <iomanip>
49#include <limits>
50#include <list>
51#include <map>
52#include <ostream>  // NOLINT
53#include <sstream>
54#include <vector>
55
56#if GTEST_OS_LINUX
57
58// TODO(kenton@google.com): Use autoconf to detect availability of
59// gettimeofday().
60# define GTEST_HAS_GETTIMEOFDAY_ 1
61
62# include <fcntl.h>  // NOLINT
63# include <limits.h>  // NOLINT
64# include <sched.h>  // NOLINT
65// Declares vsnprintf().  This header is not available on Windows.
66# include <strings.h>  // NOLINT
67# include <sys/mman.h>  // NOLINT
68# include <sys/time.h>  // NOLINT
69# include <unistd.h>  // NOLINT
70# include <string>
71
72#elif GTEST_OS_SYMBIAN
73# define GTEST_HAS_GETTIMEOFDAY_ 1
74# include <sys/time.h>  // NOLINT
75
76#elif GTEST_OS_ZOS
77# define GTEST_HAS_GETTIMEOFDAY_ 1
78# include <sys/time.h>  // NOLINT
79
80// On z/OS we additionally need strings.h for strcasecmp.
81# include <strings.h>  // NOLINT
82
83#elif GTEST_OS_WINDOWS_MOBILE  // We are on Windows CE.
84
85# include <windows.h>  // NOLINT
86# undef min
87
88#elif GTEST_OS_WINDOWS  // We are on Windows proper.
89
90# include <io.h>  // NOLINT
91# include <sys/timeb.h>  // NOLINT
92# include <sys/types.h>  // NOLINT
93# include <sys/stat.h>  // NOLINT
94
95# if GTEST_OS_WINDOWS_MINGW
96// MinGW has gettimeofday() but not _ftime64().
97// TODO(kenton@google.com): Use autoconf to detect availability of
98//   gettimeofday().
99// TODO(kenton@google.com): There are other ways to get the time on
100//   Windows, like GetTickCount() or GetSystemTimeAsFileTime().  MinGW
101//   supports these.  consider using them instead.
102#  define GTEST_HAS_GETTIMEOFDAY_ 1
103#  include <sys/time.h>  // NOLINT
104# endif  // GTEST_OS_WINDOWS_MINGW
105
106// cpplint thinks that the header is already included, so we want to
107// silence it.
108# include <windows.h>  // NOLINT
109# undef min
110
111#else
112
113// Assume other platforms have gettimeofday().
114// TODO(kenton@google.com): Use autoconf to detect availability of
115//   gettimeofday().
116# define GTEST_HAS_GETTIMEOFDAY_ 1
117
118// cpplint thinks that the header is already included, so we want to
119// silence it.
120# include <sys/time.h>  // NOLINT
121# include <unistd.h>  // NOLINT
122
123#endif  // GTEST_OS_LINUX
124
125#if GTEST_HAS_EXCEPTIONS
126# include <stdexcept>
127#endif
128
129#if GTEST_CAN_STREAM_RESULTS_
130# include <arpa/inet.h>  // NOLINT
131# include <netdb.h>  // NOLINT
132# include <sys/socket.h>  // NOLINT
133# include <sys/types.h>  // NOLINT
134#endif
135
136// Indicates that this translation unit is part of Google Test's
137// implementation.  It must come before gtest-internal-inl.h is
138// included, or there will be a compiler error.  This trick is to
139// prevent a user from accidentally including gtest-internal-inl.h in
140// his code.
141#define GTEST_IMPLEMENTATION_ 1
142#include "src/gtest-internal-inl.h"
143#undef GTEST_IMPLEMENTATION_
144
145#if GTEST_OS_WINDOWS
146# define vsnprintf _vsnprintf
147#endif  // GTEST_OS_WINDOWS
148
149namespace testing {
150
151using internal::CountIf;
152using internal::ForEach;
153using internal::GetElementOr;
154using internal::Shuffle;
155
156// Constants.
157
158// A test whose test case name or test name matches this filter is
159// disabled and not run.
160static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
161
162// A test case whose name matches this filter is considered a death
163// test case and will be run before test cases whose name doesn't
164// match this filter.
165static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*";
166
167// A test filter that matches everything.
168static const char kUniversalFilter[] = "*";
169
170// The default output file for XML output.
171static const char kDefaultOutputFile[] = "test_detail.xml";
172
173// The environment variable name for the test shard index.
174static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
175// The environment variable name for the total number of test shards.
176static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
177// The environment variable name for the test shard status file.
178static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
179
180namespace internal {
181
182// The text used in failure messages to indicate the start of the
183// stack trace.
184const char kStackTraceMarker[] = "\nStack trace:\n";
185
186// g_help_flag is true iff the --help flag or an equivalent form is
187// specified on the command line.
188bool g_help_flag = false;
189
190}  // namespace internal
191
192static const char* GetDefaultFilter() {
193#ifdef GTEST_TEST_FILTER_ENV_VAR_
194  const char* const testbridge_test_only = getenv(GTEST_TEST_FILTER_ENV_VAR_);
195  if (testbridge_test_only != NULL) {
196    return testbridge_test_only;
197  }
198#endif  // GTEST_TEST_FILTER_ENV_VAR_
199  return kUniversalFilter;
200}
201
202GTEST_DEFINE_bool_(
203    also_run_disabled_tests,
204    internal::BoolFromGTestEnv("also_run_disabled_tests", false),
205    "Run disabled tests too, in addition to the tests normally being run.");
206
207GTEST_DEFINE_bool_(
208    break_on_failure,
209    internal::BoolFromGTestEnv("break_on_failure", false),
210    "True iff a failed assertion should be a debugger break-point.");
211
212GTEST_DEFINE_bool_(
213    catch_exceptions,
214    internal::BoolFromGTestEnv("catch_exceptions", true),
215    "True iff " GTEST_NAME_
216    " should catch exceptions and treat them as test failures.");
217
218GTEST_DEFINE_string_(
219    color,
220    internal::StringFromGTestEnv("color", "auto"),
221    "Whether to use colors in the output.  Valid values: yes, no, "
222    "and auto.  'auto' means to use colors if the output is "
223    "being sent to a terminal and the TERM environment variable "
224    "is set to a terminal type that supports colors.");
225
226GTEST_DEFINE_string_(
227    filter,
228    internal::StringFromGTestEnv("filter", GetDefaultFilter()),
229    "A colon-separated list of glob (not regex) patterns "
230    "for filtering the tests to run, optionally followed by a "
231    "'-' and a : separated list of negative patterns (tests to "
232    "exclude).  A test is run if it matches one of the positive "
233    "patterns and does not match any of the negative patterns.");
234
235GTEST_DEFINE_bool_(list_tests, false,
236                   "List all tests without running them.");
237
238GTEST_DEFINE_string_(
239    output,
240    internal::StringFromGTestEnv("output", ""),
241    "A format (currently must be \"xml\"), optionally followed "
242    "by a colon and an output file name or directory. A directory "
243    "is indicated by a trailing pathname separator. "
244    "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
245    "If a directory is specified, output files will be created "
246    "within that directory, with file-names based on the test "
247    "executable's name and, if necessary, made unique by adding "
248    "digits.");
249
250GTEST_DEFINE_bool_(
251    print_time,
252    internal::BoolFromGTestEnv("print_time", true),
253    "True iff " GTEST_NAME_
254    " should display elapsed time in text output.");
255
256GTEST_DEFINE_int32_(
257    random_seed,
258    internal::Int32FromGTestEnv("random_seed", 0),
259    "Random number seed to use when shuffling test orders.  Must be in range "
260    "[1, 99999], or 0 to use a seed based on the current time.");
261
262GTEST_DEFINE_int32_(
263    repeat,
264    internal::Int32FromGTestEnv("repeat", 1),
265    "How many times to repeat each test.  Specify a negative number "
266    "for repeating forever.  Useful for shaking out flaky tests.");
267
268GTEST_DEFINE_bool_(
269    show_internal_stack_frames, false,
270    "True iff " GTEST_NAME_ " should include internal stack frames when "
271    "printing test failure stack traces.");
272
273GTEST_DEFINE_bool_(
274    shuffle,
275    internal::BoolFromGTestEnv("shuffle", false),
276    "True iff " GTEST_NAME_
277    " should randomize tests' order on every run.");
278
279GTEST_DEFINE_int32_(
280    stack_trace_depth,
281    internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
282    "The maximum number of stack frames to print when an "
283    "assertion fails.  The valid range is 0 through 100, inclusive.");
284
285GTEST_DEFINE_string_(
286    stream_result_to,
287    internal::StringFromGTestEnv("stream_result_to", ""),
288    "This flag specifies the host name and the port number on which to stream "
289    "test results. Example: \"localhost:555\". The flag is effective only on "
290    "Linux.");
291
292GTEST_DEFINE_bool_(
293    throw_on_failure,
294    internal::BoolFromGTestEnv("throw_on_failure", false),
295    "When this flag is specified, a failed assertion will throw an exception "
296    "if exceptions are enabled or exit the program with a non-zero code "
297    "otherwise.");
298
299#if GTEST_USE_OWN_FLAGFILE_FLAG_
300GTEST_DEFINE_string_(
301    flagfile,
302    internal::StringFromGTestEnv("flagfile", ""),
303    "This flag specifies the flagfile to read command-line flags from.");
304#endif  // GTEST_USE_OWN_FLAGFILE_FLAG_
305
306namespace internal {
307
308// Generates a random number from [0, range), using a Linear
309// Congruential Generator (LCG).  Crashes if 'range' is 0 or greater
310// than kMaxRange.
311UInt32 Random::Generate(UInt32 range) {
312  // These constants are the same as are used in glibc's rand(3).
313  state_ = (1103515245U*state_ + 12345U) % kMaxRange;
314
315  GTEST_CHECK_(range > 0)
316      << "Cannot generate a number in the range [0, 0).";
317  GTEST_CHECK_(range <= kMaxRange)
318      << "Generation of a number in [0, " << range << ") was requested, "
319      << "but this can only generate numbers in [0, " << kMaxRange << ").";
320
321  // Converting via modulus introduces a bit of downward bias, but
322  // it's simple, and a linear congruential generator isn't too good
323  // to begin with.
324  return state_ % range;
325}
326
327// GTestIsInitialized() returns true iff the user has initialized
328// Google Test.  Useful for catching the user mistake of not initializing
329// Google Test before calling RUN_ALL_TESTS().
330static bool GTestIsInitialized() { return GetArgvs().size() > 0; }
331
332// Iterates over a vector of TestCases, keeping a running sum of the
333// results of calling a given int-returning method on each.
334// Returns the sum.
335static int SumOverTestCaseList(const std::vector<TestCase*>& case_list,
336                               int (TestCase::*method)() const) {
337  int sum = 0;
338  for (size_t i = 0; i < case_list.size(); i++) {
339    sum += (case_list[i]->*method)();
340  }
341  return sum;
342}
343
344// Returns true iff the test case passed.
345static bool TestCasePassed(const TestCase* test_case) {
346  return test_case->should_run() && test_case->Passed();
347}
348
349// Returns true iff the test case failed.
350static bool TestCaseFailed(const TestCase* test_case) {
351  return test_case->should_run() && test_case->Failed();
352}
353
354// Returns true iff test_case contains at least one test that should
355// run.
356static bool ShouldRunTestCase(const TestCase* test_case) {
357  return test_case->should_run();
358}
359
360// AssertHelper constructor.
361AssertHelper::AssertHelper(TestPartResult::Type type,
362                           const char* file,
363                           int line,
364                           const char* message)
365    : data_(new AssertHelperData(type, file, line, message)) {
366}
367
368AssertHelper::~AssertHelper() {
369  delete data_;
370}
371
372// Message assignment, for assertion streaming support.
373void AssertHelper::operator=(const Message& message) const {
374  UnitTest::GetInstance()->
375    AddTestPartResult(data_->type, data_->file, data_->line,
376                      AppendUserMessage(data_->message, message),
377                      UnitTest::GetInstance()->impl()
378                      ->CurrentOsStackTraceExceptTop(1)
379                      // Skips the stack frame for this function itself.
380                      );  // NOLINT
381}
382
383// Mutex for linked pointers.
384GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex);
385
386// A copy of all command line arguments.  Set by InitGoogleTest().
387::std::vector<testing::internal::string> g_argvs;
388
389const ::std::vector<testing::internal::string>& GetArgvs() {
390#if defined(GTEST_CUSTOM_GET_ARGVS_)
391  return GTEST_CUSTOM_GET_ARGVS_();
392#else  // defined(GTEST_CUSTOM_GET_ARGVS_)
393  return g_argvs;
394#endif  // defined(GTEST_CUSTOM_GET_ARGVS_)
395}
396
397// Returns the current application's name, removing directory path if that
398// is present.
399FilePath GetCurrentExecutableName() {
400  FilePath result;
401
402#if GTEST_OS_WINDOWS
403  result.Set(FilePath(GetArgvs()[0]).RemoveExtension("exe"));
404#else
405  result.Set(FilePath(GetArgvs()[0]));
406#endif  // GTEST_OS_WINDOWS
407
408  return result.RemoveDirectoryName();
409}
410
411// Functions for processing the gtest_output flag.
412
413// Returns the output format, or "" for normal printed output.
414std::string UnitTestOptions::GetOutputFormat() {
415  const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
416  if (gtest_output_flag == NULL) return std::string("");
417
418  const char* const colon = strchr(gtest_output_flag, ':');
419  return (colon == NULL) ?
420      std::string(gtest_output_flag) :
421      std::string(gtest_output_flag, colon - gtest_output_flag);
422}
423
424// Returns the name of the requested output file, or the default if none
425// was explicitly specified.
426std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
427  const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
428  if (gtest_output_flag == NULL)
429    return "";
430
431  const char* const colon = strchr(gtest_output_flag, ':');
432  if (colon == NULL)
433    return internal::FilePath::ConcatPaths(
434        internal::FilePath(
435            UnitTest::GetInstance()->original_working_dir()),
436        internal::FilePath(kDefaultOutputFile)).string();
437
438  internal::FilePath output_name(colon + 1);
439  if (!output_name.IsAbsolutePath())
440    // TODO(wan@google.com): on Windows \some\path is not an absolute
441    // path (as its meaning depends on the current drive), yet the
442    // following logic for turning it into an absolute path is wrong.
443    // Fix it.
444    output_name = internal::FilePath::ConcatPaths(
445        internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
446        internal::FilePath(colon + 1));
447
448  if (!output_name.IsDirectory())
449    return output_name.string();
450
451  internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
452      output_name, internal::GetCurrentExecutableName(),
453      GetOutputFormat().c_str()));
454  return result.string();
455}
456
457// Returns true iff the wildcard pattern matches the string.  The
458// first ':' or '\0' character in pattern marks the end of it.
459//
460// This recursive algorithm isn't very efficient, but is clear and
461// works well enough for matching test names, which are short.
462bool UnitTestOptions::PatternMatchesString(const char *pattern,
463                                           const char *str) {
464  switch (*pattern) {
465    case '\0':
466    case ':':  // Either ':' or '\0' marks the end of the pattern.
467      return *str == '\0';
468    case '?':  // Matches any single character.
469      return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);
470    case '*':  // Matches any string (possibly empty) of characters.
471      return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||
472          PatternMatchesString(pattern + 1, str);
473    default:  // Non-special character.  Matches itself.
474      return *pattern == *str &&
475          PatternMatchesString(pattern + 1, str + 1);
476  }
477}
478
479bool UnitTestOptions::MatchesFilter(
480    const std::string& name, const char* filter) {
481  const char *cur_pattern = filter;
482  for (;;) {
483    if (PatternMatchesString(cur_pattern, name.c_str())) {
484      return true;
485    }
486
487    // Finds the next pattern in the filter.
488    cur_pattern = strchr(cur_pattern, ':');
489
490    // Returns if no more pattern can be found.
491    if (cur_pattern == NULL) {
492      return false;
493    }
494
495    // Skips the pattern separater (the ':' character).
496    cur_pattern++;
497  }
498}
499
500// Returns true iff the user-specified filter matches the test case
501// name and the test name.
502bool UnitTestOptions::FilterMatchesTest(const std::string &test_case_name,
503                                        const std::string &test_name) {
504  const std::string& full_name = test_case_name + "." + test_name.c_str();
505
506  // Split --gtest_filter at '-', if there is one, to separate into
507  // positive filter and negative filter portions
508  const char* const p = GTEST_FLAG(filter).c_str();
509  const char* const dash = strchr(p, '-');
510  std::string positive;
511  std::string negative;
512  if (dash == NULL) {
513    positive = GTEST_FLAG(filter).c_str();  // Whole string is a positive filter
514    negative = "";
515  } else {
516    positive = std::string(p, dash);   // Everything up to the dash
517    negative = std::string(dash + 1);  // Everything after the dash
518    if (positive.empty()) {
519      // Treat '-test1' as the same as '*-test1'
520      positive = kUniversalFilter;
521    }
522  }
523
524  // A filter is a colon-separated list of patterns.  It matches a
525  // test if any pattern in it matches the test.
526  return (MatchesFilter(full_name, positive.c_str()) &&
527          !MatchesFilter(full_name, negative.c_str()));
528}
529
530#if GTEST_HAS_SEH
531// Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
532// given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
533// This function is useful as an __except condition.
534int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
535  // Google Test should handle a SEH exception if:
536  //   1. the user wants it to, AND
537  //   2. this is not a breakpoint exception, AND
538  //   3. this is not a C++ exception (VC++ implements them via SEH,
539  //      apparently).
540  //
541  // SEH exception code for C++ exceptions.
542  // (see http://support.microsoft.com/kb/185294 for more information).
543  const DWORD kCxxExceptionCode = 0xe06d7363;
544
545  bool should_handle = true;
546
547  if (!GTEST_FLAG(catch_exceptions))
548    should_handle = false;
549  else if (exception_code == EXCEPTION_BREAKPOINT)
550    should_handle = false;
551  else if (exception_code == kCxxExceptionCode)
552    should_handle = false;
553
554  return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
555}
556#endif  // GTEST_HAS_SEH
557
558}  // namespace internal
559
560// The c'tor sets this object as the test part result reporter used by
561// Google Test.  The 'result' parameter specifies where to report the
562// results. Intercepts only failures from the current thread.
563ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
564    TestPartResultArray* result)
565    : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
566      result_(result) {
567  Init();
568}
569
570// The c'tor sets this object as the test part result reporter used by
571// Google Test.  The 'result' parameter specifies where to report the
572// results.
573ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
574    InterceptMode intercept_mode, TestPartResultArray* result)
575    : intercept_mode_(intercept_mode),
576      result_(result) {
577  Init();
578}
579
580void ScopedFakeTestPartResultReporter::Init() {
581  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
582  if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
583    old_reporter_ = impl->GetGlobalTestPartResultReporter();
584    impl->SetGlobalTestPartResultReporter(this);
585  } else {
586    old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
587    impl->SetTestPartResultReporterForCurrentThread(this);
588  }
589}
590
591// The d'tor restores the test part result reporter used by Google Test
592// before.
593ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
594  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
595  if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
596    impl->SetGlobalTestPartResultReporter(old_reporter_);
597  } else {
598    impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
599  }
600}
601
602// Increments the test part result count and remembers the result.
603// This method is from the TestPartResultReporterInterface interface.
604void ScopedFakeTestPartResultReporter::ReportTestPartResult(
605    const TestPartResult& result) {
606  result_->Append(result);
607}
608
609namespace internal {
610
611// Returns the type ID of ::testing::Test.  We should always call this
612// instead of GetTypeId< ::testing::Test>() to get the type ID of
613// testing::Test.  This is to work around a suspected linker bug when
614// using Google Test as a framework on Mac OS X.  The bug causes
615// GetTypeId< ::testing::Test>() to return different values depending
616// on whether the call is from the Google Test framework itself or
617// from user test code.  GetTestTypeId() is guaranteed to always
618// return the same value, as it always calls GetTypeId<>() from the
619// gtest.cc, which is within the Google Test framework.
620TypeId GetTestTypeId() {
621  return GetTypeId<Test>();
622}
623
624// The value of GetTestTypeId() as seen from within the Google Test
625// library.  This is solely for testing GetTestTypeId().
626extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
627
628// This predicate-formatter checks that 'results' contains a test part
629// failure of the given type and that the failure message contains the
630// given substring.
631AssertionResult HasOneFailure(const char* /* results_expr */,
632                              const char* /* type_expr */,
633                              const char* /* substr_expr */,
634                              const TestPartResultArray& results,
635                              TestPartResult::Type type,
636                              const string& substr) {
637  const std::string expected(type == TestPartResult::kFatalFailure ?
638                        "1 fatal failure" :
639                        "1 non-fatal failure");
640  Message msg;
641  if (results.size() != 1) {
642    msg << "Expected: " << expected << "\n"
643        << "  Actual: " << results.size() << " failures";
644    for (int i = 0; i < results.size(); i++) {
645      msg << "\n" << results.GetTestPartResult(i);
646    }
647    return AssertionFailure() << msg;
648  }
649
650  const TestPartResult& r = results.GetTestPartResult(0);
651  if (r.type() != type) {
652    return AssertionFailure() << "Expected: " << expected << "\n"
653                              << "  Actual:\n"
654                              << r;
655  }
656
657  if (strstr(r.message(), substr.c_str()) == NULL) {
658    return AssertionFailure() << "Expected: " << expected << " containing \""
659                              << substr << "\"\n"
660                              << "  Actual:\n"
661                              << r;
662  }
663
664  return AssertionSuccess();
665}
666
667// The constructor of SingleFailureChecker remembers where to look up
668// test part results, what type of failure we expect, and what
669// substring the failure message should contain.
670SingleFailureChecker:: SingleFailureChecker(
671    const TestPartResultArray* results,
672    TestPartResult::Type type,
673    const string& substr)
674    : results_(results),
675      type_(type),
676      substr_(substr) {}
677
678// The destructor of SingleFailureChecker verifies that the given
679// TestPartResultArray contains exactly one failure that has the given
680// type and contains the given substring.  If that's not the case, a
681// non-fatal failure will be generated.
682SingleFailureChecker::~SingleFailureChecker() {
683  EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_);
684}
685
686DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
687    UnitTestImpl* unit_test) : unit_test_(unit_test) {}
688
689void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
690    const TestPartResult& result) {
691  unit_test_->current_test_result()->AddTestPartResult(result);
692  unit_test_->listeners()->repeater()->OnTestPartResult(result);
693}
694
695DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
696    UnitTestImpl* unit_test) : unit_test_(unit_test) {}
697
698void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
699    const TestPartResult& result) {
700  unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
701}
702
703// Returns the global test part result reporter.
704TestPartResultReporterInterface*
705UnitTestImpl::GetGlobalTestPartResultReporter() {
706  internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
707  return global_test_part_result_repoter_;
708}
709
710// Sets the global test part result reporter.
711void UnitTestImpl::SetGlobalTestPartResultReporter(
712    TestPartResultReporterInterface* reporter) {
713  internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
714  global_test_part_result_repoter_ = reporter;
715}
716
717// Returns the test part result reporter for the current thread.
718TestPartResultReporterInterface*
719UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
720  return per_thread_test_part_result_reporter_.get();
721}
722
723// Sets the test part result reporter for the current thread.
724void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
725    TestPartResultReporterInterface* reporter) {
726  per_thread_test_part_result_reporter_.set(reporter);
727}
728
729// Gets the number of successful test cases.
730int UnitTestImpl::successful_test_case_count() const {
731  return CountIf(test_cases_, TestCasePassed);
732}
733
734// Gets the number of failed test cases.
735int UnitTestImpl::failed_test_case_count() const {
736  return CountIf(test_cases_, TestCaseFailed);
737}
738
739// Gets the number of all test cases.
740int UnitTestImpl::total_test_case_count() const {
741  return static_cast<int>(test_cases_.size());
742}
743
744// Gets the number of all test cases that contain at least one test
745// that should run.
746int UnitTestImpl::test_case_to_run_count() const {
747  return CountIf(test_cases_, ShouldRunTestCase);
748}
749
750// Gets the number of successful tests.
751int UnitTestImpl::successful_test_count() const {
752  return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count);
753}
754
755// Gets the number of failed tests.
756int UnitTestImpl::failed_test_count() const {
757  return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count);
758}
759
760// Gets the number of disabled tests that will be reported in the XML report.
761int UnitTestImpl::reportable_disabled_test_count() const {
762  return SumOverTestCaseList(test_cases_,
763                             &TestCase::reportable_disabled_test_count);
764}
765
766// Gets the number of disabled tests.
767int UnitTestImpl::disabled_test_count() const {
768  return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count);
769}
770
771// Gets the number of tests to be printed in the XML report.
772int UnitTestImpl::reportable_test_count() const {
773  return SumOverTestCaseList(test_cases_, &TestCase::reportable_test_count);
774}
775
776// Gets the number of all tests.
777int UnitTestImpl::total_test_count() const {
778  return SumOverTestCaseList(test_cases_, &TestCase::total_test_count);
779}
780
781// Gets the number of tests that should run.
782int UnitTestImpl::test_to_run_count() const {
783  return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count);
784}
785
786// Returns the current OS stack trace as an std::string.
787//
788// The maximum number of stack frames to be included is specified by
789// the gtest_stack_trace_depth flag.  The skip_count parameter
790// specifies the number of top frames to be skipped, which doesn't
791// count against the number of frames to be included.
792//
793// For example, if Foo() calls Bar(), which in turn calls
794// CurrentOsStackTraceExceptTop(1), Foo() will be included in the
795// trace but Bar() and CurrentOsStackTraceExceptTop() won't.
796std::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
797  return os_stack_trace_getter()->CurrentStackTrace(
798      static_cast<int>(GTEST_FLAG(stack_trace_depth)),
799      skip_count + 1
800      // Skips the user-specified number of frames plus this function
801      // itself.
802      );  // NOLINT
803}
804
805// Returns the current time in milliseconds.
806TimeInMillis GetTimeInMillis() {
807#if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__)
808  // Difference between 1970-01-01 and 1601-01-01 in milliseconds.
809  // http://analogous.blogspot.com/2005/04/epoch.html
810  const TimeInMillis kJavaEpochToWinFileTimeDelta =
811    static_cast<TimeInMillis>(116444736UL) * 100000UL;
812  const DWORD kTenthMicrosInMilliSecond = 10000;
813
814  SYSTEMTIME now_systime;
815  FILETIME now_filetime;
816  ULARGE_INTEGER now_int64;
817  // TODO(kenton@google.com): Shouldn't this just use
818  //   GetSystemTimeAsFileTime()?
819  GetSystemTime(&now_systime);
820  if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
821    now_int64.LowPart = now_filetime.dwLowDateTime;
822    now_int64.HighPart = now_filetime.dwHighDateTime;
823    now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
824      kJavaEpochToWinFileTimeDelta;
825    return now_int64.QuadPart;
826  }
827  return 0;
828#elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_
829  __timeb64 now;
830
831  // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996
832  // (deprecated function) there.
833  // TODO(kenton@google.com): Use GetTickCount()?  Or use
834  //   SystemTimeToFileTime()
835  GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996)
836  _ftime64(&now);
837  GTEST_DISABLE_MSC_WARNINGS_POP_()
838
839  return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
840#elif GTEST_HAS_GETTIMEOFDAY_
841  struct timeval now;
842  gettimeofday(&now, NULL);
843  return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
844#else
845# error "Don't know how to get the current time on your system."
846#endif
847}
848
849// Utilities
850
851// class String.
852
853#if GTEST_OS_WINDOWS_MOBILE
854// Creates a UTF-16 wide string from the given ANSI string, allocating
855// memory using new. The caller is responsible for deleting the return
856// value using delete[]. Returns the wide string, or NULL if the
857// input is NULL.
858LPCWSTR String::AnsiToUtf16(const char* ansi) {
859  if (!ansi) return NULL;
860  const int length = strlen(ansi);
861  const int unicode_length =
862      MultiByteToWideChar(CP_ACP, 0, ansi, length,
863                          NULL, 0);
864  WCHAR* unicode = new WCHAR[unicode_length + 1];
865  MultiByteToWideChar(CP_ACP, 0, ansi, length,
866                      unicode, unicode_length);
867  unicode[unicode_length] = 0;
868  return unicode;
869}
870
871// Creates an ANSI string from the given wide string, allocating
872// memory using new. The caller is responsible for deleting the return
873// value using delete[]. Returns the ANSI string, or NULL if the
874// input is NULL.
875const char* String::Utf16ToAnsi(LPCWSTR utf16_str)  {
876  if (!utf16_str) return NULL;
877  const int ansi_length =
878      WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
879                          NULL, 0, NULL, NULL);
880  char* ansi = new char[ansi_length + 1];
881  WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
882                      ansi, ansi_length, NULL, NULL);
883  ansi[ansi_length] = 0;
884  return ansi;
885}
886
887#endif  // GTEST_OS_WINDOWS_MOBILE
888
889// Compares two C strings.  Returns true iff they have the same content.
890//
891// Unlike strcmp(), this function can handle NULL argument(s).  A NULL
892// C string is considered different to any non-NULL C string,
893// including the empty string.
894bool String::CStringEquals(const char * lhs, const char * rhs) {
895  if ( lhs == NULL ) return rhs == NULL;
896
897  if ( rhs == NULL ) return false;
898
899  return strcmp(lhs, rhs) == 0;
900}
901
902#if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
903
904// Converts an array of wide chars to a narrow string using the UTF-8
905// encoding, and streams the result to the given Message object.
906static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
907                                     Message* msg) {
908  for (size_t i = 0; i != length; ) {  // NOLINT
909    if (wstr[i] != L'\0') {
910      *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
911      while (i != length && wstr[i] != L'\0')
912        i++;
913    } else {
914      *msg << '\0';
915      i++;
916    }
917  }
918}
919
920#endif  // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
921
922void SplitString(const ::std::string& str, char delimiter,
923                 ::std::vector< ::std::string>* dest) {
924  ::std::vector< ::std::string> parsed;
925  ::std::string::size_type pos = 0;
926  while (::testing::internal::AlwaysTrue()) {
927    const ::std::string::size_type colon = str.find(delimiter, pos);
928    if (colon == ::std::string::npos) {
929      parsed.push_back(str.substr(pos));
930      break;
931    } else {
932      parsed.push_back(str.substr(pos, colon - pos));
933      pos = colon + 1;
934    }
935  }
936  dest->swap(parsed);
937}
938
939}  // namespace internal
940
941// Constructs an empty Message.
942// We allocate the stringstream separately because otherwise each use of
943// ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's
944// stack frame leading to huge stack frames in some cases; gcc does not reuse
945// the stack space.
946Message::Message() : ss_(new ::std::stringstream) {
947  // By default, we want there to be enough precision when printing
948  // a double to a Message.
949  *ss_ << std::setprecision(std::numeric_limits<double>::digits10 + 2);
950}
951
952// These two overloads allow streaming a wide C string to a Message
953// using the UTF-8 encoding.
954Message& Message::operator <<(const wchar_t* wide_c_str) {
955  return *this << internal::String::ShowWideCString(wide_c_str);
956}
957Message& Message::operator <<(wchar_t* wide_c_str) {
958  return *this << internal::String::ShowWideCString(wide_c_str);
959}
960
961#if GTEST_HAS_STD_WSTRING
962// Converts the given wide string to a narrow string using the UTF-8
963// encoding, and streams the result to this Message object.
964Message& Message::operator <<(const ::std::wstring& wstr) {
965  internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
966  return *this;
967}
968#endif  // GTEST_HAS_STD_WSTRING
969
970#if GTEST_HAS_GLOBAL_WSTRING
971// Converts the given wide string to a narrow string using the UTF-8
972// encoding, and streams the result to this Message object.
973Message& Message::operator <<(const ::wstring& wstr) {
974  internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
975  return *this;
976}
977#endif  // GTEST_HAS_GLOBAL_WSTRING
978
979// Gets the text streamed to this object so far as an std::string.
980// Each '\0' character in the buffer is replaced with "\\0".
981std::string Message::GetString() const {
982  return internal::StringStreamToString(ss_.get());
983}
984
985// AssertionResult constructors.
986// Used in EXPECT_TRUE/FALSE(assertion_result).
987AssertionResult::AssertionResult(const AssertionResult& other)
988    : success_(other.success_),
989      message_(other.message_.get() != NULL ?
990               new ::std::string(*other.message_) :
991               static_cast< ::std::string*>(NULL)) {
992}
993
994// Swaps two AssertionResults.
995void AssertionResult::swap(AssertionResult& other) {
996  using std::swap;
997  swap(success_, other.success_);
998  swap(message_, other.message_);
999}
1000
1001// Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
1002AssertionResult AssertionResult::operator!() const {
1003  AssertionResult negation(!success_);
1004  if (message_.get() != NULL)
1005    negation << *message_;
1006  return negation;
1007}
1008
1009// Makes a successful assertion result.
1010AssertionResult AssertionSuccess() {
1011  return AssertionResult(true);
1012}
1013
1014// Makes a failed assertion result.
1015AssertionResult AssertionFailure() {
1016  return AssertionResult(false);
1017}
1018
1019// Makes a failed assertion result with the given failure message.
1020// Deprecated; use AssertionFailure() << message.
1021AssertionResult AssertionFailure(const Message& message) {
1022  return AssertionFailure() << message;
1023}
1024
1025namespace internal {
1026
1027namespace edit_distance {
1028std::vector<EditType> CalculateOptimalEdits(const std::vector<size_t>& left,
1029                                            const std::vector<size_t>& right) {
1030  std::vector<std::vector<double> > costs(
1031      left.size() + 1, std::vector<double>(right.size() + 1));
1032  std::vector<std::vector<EditType> > best_move(
1033      left.size() + 1, std::vector<EditType>(right.size() + 1));
1034
1035  // Populate for empty right.
1036  for (size_t l_i = 0; l_i < costs.size(); ++l_i) {
1037    costs[l_i][0] = static_cast<double>(l_i);
1038    best_move[l_i][0] = kRemove;
1039  }
1040  // Populate for empty left.
1041  for (size_t r_i = 1; r_i < costs[0].size(); ++r_i) {
1042    costs[0][r_i] = static_cast<double>(r_i);
1043    best_move[0][r_i] = kAdd;
1044  }
1045
1046  for (size_t l_i = 0; l_i < left.size(); ++l_i) {
1047    for (size_t r_i = 0; r_i < right.size(); ++r_i) {
1048      if (left[l_i] == right[r_i]) {
1049        // Found a match. Consume it.
1050        costs[l_i + 1][r_i + 1] = costs[l_i][r_i];
1051        best_move[l_i + 1][r_i + 1] = kMatch;
1052        continue;
1053      }
1054
1055      const double add = costs[l_i + 1][r_i];
1056      const double remove = costs[l_i][r_i + 1];
1057      const double replace = costs[l_i][r_i];
1058      if (add < remove && add < replace) {
1059        costs[l_i + 1][r_i + 1] = add + 1;
1060        best_move[l_i + 1][r_i + 1] = kAdd;
1061      } else if (remove < add && remove < replace) {
1062        costs[l_i + 1][r_i + 1] = remove + 1;
1063        best_move[l_i + 1][r_i + 1] = kRemove;
1064      } else {
1065        // We make replace a little more expensive than add/remove to lower
1066        // their priority.
1067        costs[l_i + 1][r_i + 1] = replace + 1.00001;
1068        best_move[l_i + 1][r_i + 1] = kReplace;
1069      }
1070    }
1071  }
1072
1073  // Reconstruct the best path. We do it in reverse order.
1074  std::vector<EditType> best_path;
1075  for (size_t l_i = left.size(), r_i = right.size(); l_i > 0 || r_i > 0;) {
1076    EditType move = best_move[l_i][r_i];
1077    best_path.push_back(move);
1078    l_i -= move != kAdd;
1079    r_i -= move != kRemove;
1080  }
1081  std::reverse(best_path.begin(), best_path.end());
1082  return best_path;
1083}
1084
1085namespace {
1086
1087// Helper class to convert string into ids with deduplication.
1088class InternalStrings {
1089 public:
1090  size_t GetId(const std::string& str) {
1091    IdMap::iterator it = ids_.find(str);
1092    if (it != ids_.end()) return it->second;
1093    size_t id = ids_.size();
1094    return ids_[str] = id;
1095  }
1096
1097 private:
1098  typedef std::map<std::string, size_t> IdMap;
1099  IdMap ids_;
1100};
1101
1102}  // namespace
1103
1104std::vector<EditType> CalculateOptimalEdits(
1105    const std::vector<std::string>& left,
1106    const std::vector<std::string>& right) {
1107  std::vector<size_t> left_ids, right_ids;
1108  {
1109    InternalStrings intern_table;
1110    for (size_t i = 0; i < left.size(); ++i) {
1111      left_ids.push_back(intern_table.GetId(left[i]));
1112    }
1113    for (size_t i = 0; i < right.size(); ++i) {
1114      right_ids.push_back(intern_table.GetId(right[i]));
1115    }
1116  }
1117  return CalculateOptimalEdits(left_ids, right_ids);
1118}
1119
1120namespace {
1121
1122// Helper class that holds the state for one hunk and prints it out to the
1123// stream.
1124// It reorders adds/removes when possible to group all removes before all
1125// adds. It also adds the hunk header before printint into the stream.
1126class Hunk {
1127 public:
1128  Hunk(size_t left_start, size_t right_start)
1129      : left_start_(left_start),
1130        right_start_(right_start),
1131        adds_(),
1132        removes_(),
1133        common_() {}
1134
1135  void PushLine(char edit, const char* line) {
1136    switch (edit) {
1137      case ' ':
1138        ++common_;
1139        FlushEdits();
1140        hunk_.push_back(std::make_pair(' ', line));
1141        break;
1142      case '-':
1143        ++removes_;
1144        hunk_removes_.push_back(std::make_pair('-', line));
1145        break;
1146      case '+':
1147        ++adds_;
1148        hunk_adds_.push_back(std::make_pair('+', line));
1149        break;
1150    }
1151  }
1152
1153  void PrintTo(std::ostream* os) {
1154    PrintHeader(os);
1155    FlushEdits();
1156    for (std::list<std::pair<char, const char*> >::const_iterator it =
1157             hunk_.begin();
1158         it != hunk_.end(); ++it) {
1159      *os << it->first << it->second << "\n";
1160    }
1161  }
1162
1163  bool has_edits() const { return adds_ || removes_; }
1164
1165 private:
1166  void FlushEdits() {
1167    hunk_.splice(hunk_.end(), hunk_removes_);
1168    hunk_.splice(hunk_.end(), hunk_adds_);
1169  }
1170
1171  // Print a unified diff header for one hunk.
1172  // The format is
1173  //   "@@ -<left_start>,<left_length> +<right_start>,<right_length> @@"
1174  // where the left/right parts are ommitted if unnecessary.
1175  void PrintHeader(std::ostream* ss) const {
1176    *ss << "@@ ";
1177    if (removes_) {
1178      *ss << "-" << left_start_ << "," << (removes_ + common_);
1179    }
1180    if (removes_ && adds_) {
1181      *ss << " ";
1182    }
1183    if (adds_) {
1184      *ss << "+" << right_start_ << "," << (adds_ + common_);
1185    }
1186    *ss << " @@\n";
1187  }
1188
1189  size_t left_start_, right_start_;
1190  size_t adds_, removes_, common_;
1191  std::list<std::pair<char, const char*> > hunk_, hunk_adds_, hunk_removes_;
1192};
1193
1194}  // namespace
1195
1196// Create a list of diff hunks in Unified diff format.
1197// Each hunk has a header generated by PrintHeader above plus a body with
1198// lines prefixed with ' ' for no change, '-' for deletion and '+' for
1199// addition.
1200// 'context' represents the desired unchanged prefix/suffix around the diff.
1201// If two hunks are close enough that their contexts overlap, then they are
1202// joined into one hunk.
1203std::string CreateUnifiedDiff(const std::vector<std::string>& left,
1204                              const std::vector<std::string>& right,
1205                              size_t context) {
1206  const std::vector<EditType> edits = CalculateOptimalEdits(left, right);
1207
1208  size_t l_i = 0, r_i = 0, edit_i = 0;
1209  std::stringstream ss;
1210  while (edit_i < edits.size()) {
1211    // Find first edit.
1212    while (edit_i < edits.size() && edits[edit_i] == kMatch) {
1213      ++l_i;
1214      ++r_i;
1215      ++edit_i;
1216    }
1217
1218    // Find the first line to include in the hunk.
1219    const size_t prefix_context = std::min(l_i, context);
1220    Hunk hunk(l_i - prefix_context + 1, r_i - prefix_context + 1);
1221    for (size_t i = prefix_context; i > 0; --i) {
1222      hunk.PushLine(' ', left[l_i - i].c_str());
1223    }
1224
1225    // Iterate the edits until we found enough suffix for the hunk or the input
1226    // is over.
1227    size_t n_suffix = 0;
1228    for (; edit_i < edits.size(); ++edit_i) {
1229      if (n_suffix >= context) {
1230        // Continue only if the next hunk is very close.
1231        std::vector<EditType>::const_iterator it = edits.begin() + edit_i;
1232        while (it != edits.end() && *it == kMatch) ++it;
1233        if (it == edits.end() || (it - edits.begin()) - edit_i >= context) {
1234          // There is no next edit or it is too far away.
1235          break;
1236        }
1237      }
1238
1239      EditType edit = edits[edit_i];
1240      // Reset count when a non match is found.
1241      n_suffix = edit == kMatch ? n_suffix + 1 : 0;
1242
1243      if (edit == kMatch || edit == kRemove || edit == kReplace) {
1244        hunk.PushLine(edit == kMatch ? ' ' : '-', left[l_i].c_str());
1245      }
1246      if (edit == kAdd || edit == kReplace) {
1247        hunk.PushLine('+', right[r_i].c_str());
1248      }
1249
1250      // Advance indices, depending on edit type.
1251      l_i += edit != kAdd;
1252      r_i += edit != kRemove;
1253    }
1254
1255    if (!hunk.has_edits()) {
1256      // We are done. We don't want this hunk.
1257      break;
1258    }
1259
1260    hunk.PrintTo(&ss);
1261  }
1262  return ss.str();
1263}
1264
1265}  // namespace edit_distance
1266
1267namespace {
1268
1269// The string representation of the values received in EqFailure() are already
1270// escaped. Split them on escaped '\n' boundaries. Leave all other escaped
1271// characters the same.
1272std::vector<std::string> SplitEscapedString(const std::string& str) {
1273  std::vector<std::string> lines;
1274  size_t start = 0, end = str.size();
1275  if (end > 2 && str[0] == '"' && str[end - 1] == '"') {
1276    ++start;
1277    --end;
1278  }
1279  bool escaped = false;
1280  for (size_t i = start; i + 1 < end; ++i) {
1281    if (escaped) {
1282      escaped = false;
1283      if (str[i] == 'n') {
1284        lines.push_back(str.substr(start, i - start - 1));
1285        start = i + 1;
1286      }
1287    } else {
1288      escaped = str[i] == '\\';
1289    }
1290  }
1291  lines.push_back(str.substr(start, end - start));
1292  return lines;
1293}
1294
1295}  // namespace
1296
1297// Constructs and returns the message for an equality assertion
1298// (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
1299//
1300// The first four parameters are the expressions used in the assertion
1301// and their values, as strings.  For example, for ASSERT_EQ(foo, bar)
1302// where foo is 5 and bar is 6, we have:
1303//
1304//   expected_expression: "foo"
1305//   actual_expression:   "bar"
1306//   expected_value:      "5"
1307//   actual_value:        "6"
1308//
1309// The ignoring_case parameter is true iff the assertion is a
1310// *_STRCASEEQ*.  When it's true, the string " (ignoring case)" will
1311// be inserted into the message.
1312AssertionResult EqFailure(const char* expected_expression,
1313                          const char* actual_expression,
1314                          const std::string& expected_value,
1315                          const std::string& actual_value,
1316                          bool ignoring_case) {
1317  Message msg;
1318  msg << "Value of: " << actual_expression;
1319  if (actual_value != actual_expression) {
1320    msg << "\n  Actual: " << actual_value;
1321  }
1322
1323  msg << "\nExpected: " << expected_expression;
1324  if (ignoring_case) {
1325    msg << " (ignoring case)";
1326  }
1327  if (expected_value != expected_expression) {
1328    msg << "\nWhich is: " << expected_value;
1329  }
1330
1331  if (!expected_value.empty() && !actual_value.empty()) {
1332    const std::vector<std::string> expected_lines =
1333        SplitEscapedString(expected_value);
1334    const std::vector<std::string> actual_lines =
1335        SplitEscapedString(actual_value);
1336    if (expected_lines.size() > 1 || actual_lines.size() > 1) {
1337      msg << "\nWith diff:\n"
1338          << edit_distance::CreateUnifiedDiff(expected_lines, actual_lines);
1339    }
1340  }
1341
1342  return AssertionFailure() << msg;
1343}
1344
1345// Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
1346std::string GetBoolAssertionFailureMessage(
1347    const AssertionResult& assertion_result,
1348    const char* expression_text,
1349    const char* actual_predicate_value,
1350    const char* expected_predicate_value) {
1351  const char* actual_message = assertion_result.message();
1352  Message msg;
1353  msg << "Value of: " << expression_text
1354      << "\n  Actual: " << actual_predicate_value;
1355  if (actual_message[0] != '\0')
1356    msg << " (" << actual_message << ")";
1357  msg << "\nExpected: " << expected_predicate_value;
1358  return msg.GetString();
1359}
1360
1361// Helper function for implementing ASSERT_NEAR.
1362AssertionResult DoubleNearPredFormat(const char* expr1,
1363                                     const char* expr2,
1364                                     const char* abs_error_expr,
1365                                     double val1,
1366                                     double val2,
1367                                     double abs_error) {
1368  const double diff = fabs(val1 - val2);
1369  if (diff <= abs_error) return AssertionSuccess();
1370
1371  // TODO(wan): do not print the value of an expression if it's
1372  // already a literal.
1373  return AssertionFailure()
1374      << "The difference between " << expr1 << " and " << expr2
1375      << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"
1376      << expr1 << " evaluates to " << val1 << ",\n"
1377      << expr2 << " evaluates to " << val2 << ", and\n"
1378      << abs_error_expr << " evaluates to " << abs_error << ".";
1379}
1380
1381
1382// Helper template for implementing FloatLE() and DoubleLE().
1383template <typename RawType>
1384AssertionResult FloatingPointLE(const char* expr1,
1385                                const char* expr2,
1386                                RawType val1,
1387                                RawType val2) {
1388  // Returns success if val1 is less than val2,
1389  if (val1 < val2) {
1390    return AssertionSuccess();
1391  }
1392
1393  // or if val1 is almost equal to val2.
1394  const FloatingPoint<RawType> lhs(val1), rhs(val2);
1395  if (lhs.AlmostEquals(rhs)) {
1396    return AssertionSuccess();
1397  }
1398
1399  // Note that the above two checks will both fail if either val1 or
1400  // val2 is NaN, as the IEEE floating-point standard requires that
1401  // any predicate involving a NaN must return false.
1402
1403  ::std::stringstream val1_ss;
1404  val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
1405          << val1;
1406
1407  ::std::stringstream val2_ss;
1408  val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
1409          << val2;
1410
1411  return AssertionFailure()
1412      << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
1413      << "  Actual: " << StringStreamToString(&val1_ss) << " vs "
1414      << StringStreamToString(&val2_ss);
1415}
1416
1417}  // namespace internal
1418
1419// Asserts that val1 is less than, or almost equal to, val2.  Fails
1420// otherwise.  In particular, it fails if either val1 or val2 is NaN.
1421AssertionResult FloatLE(const char* expr1, const char* expr2,
1422                        float val1, float val2) {
1423  return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
1424}
1425
1426// Asserts that val1 is less than, or almost equal to, val2.  Fails
1427// otherwise.  In particular, it fails if either val1 or val2 is NaN.
1428AssertionResult DoubleLE(const char* expr1, const char* expr2,
1429                         double val1, double val2) {
1430  return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
1431}
1432
1433namespace internal {
1434
1435// The helper function for {ASSERT|EXPECT}_EQ with int or enum
1436// arguments.
1437AssertionResult CmpHelperEQ(const char* expected_expression,
1438                            const char* actual_expression,
1439                            BiggestInt expected,
1440                            BiggestInt actual) {
1441  if (expected == actual) {
1442    return AssertionSuccess();
1443  }
1444
1445  return EqFailure(expected_expression,
1446                   actual_expression,
1447                   FormatForComparisonFailureMessage(expected, actual),
1448                   FormatForComparisonFailureMessage(actual, expected),
1449                   false);
1450}
1451
1452// A macro for implementing the helper functions needed to implement
1453// ASSERT_?? and EXPECT_?? with integer or enum arguments.  It is here
1454// just to avoid copy-and-paste of similar code.
1455#define GTEST_IMPL_CMP_HELPER_(op_name, op)\
1456AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
1457                                   BiggestInt val1, BiggestInt val2) {\
1458  if (val1 op val2) {\
1459    return AssertionSuccess();\
1460  } else {\
1461    return AssertionFailure() \
1462        << "Expected: (" << expr1 << ") " #op " (" << expr2\
1463        << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
1464        << " vs " << FormatForComparisonFailureMessage(val2, val1);\
1465  }\
1466}
1467
1468// Implements the helper function for {ASSERT|EXPECT}_NE with int or
1469// enum arguments.
1470GTEST_IMPL_CMP_HELPER_(NE, !=)
1471// Implements the helper function for {ASSERT|EXPECT}_LE with int or
1472// enum arguments.
1473GTEST_IMPL_CMP_HELPER_(LE, <=)
1474// Implements the helper function for {ASSERT|EXPECT}_LT with int or
1475// enum arguments.
1476GTEST_IMPL_CMP_HELPER_(LT, < )
1477// Implements the helper function for {ASSERT|EXPECT}_GE with int or
1478// enum arguments.
1479GTEST_IMPL_CMP_HELPER_(GE, >=)
1480// Implements the helper function for {ASSERT|EXPECT}_GT with int or
1481// enum arguments.
1482GTEST_IMPL_CMP_HELPER_(GT, > )
1483
1484#undef GTEST_IMPL_CMP_HELPER_
1485
1486// The helper function for {ASSERT|EXPECT}_STREQ.
1487AssertionResult CmpHelperSTREQ(const char* expected_expression,
1488                               const char* actual_expression,
1489                               const char* expected,
1490                               const char* actual) {
1491  if (String::CStringEquals(expected, actual)) {
1492    return AssertionSuccess();
1493  }
1494
1495  return EqFailure(expected_expression,
1496                   actual_expression,
1497                   PrintToString(expected),
1498                   PrintToString(actual),
1499                   false);
1500}
1501
1502// The helper function for {ASSERT|EXPECT}_STRCASEEQ.
1503AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression,
1504                                   const char* actual_expression,
1505                                   const char* expected,
1506                                   const char* actual) {
1507  if (String::CaseInsensitiveCStringEquals(expected, actual)) {
1508    return AssertionSuccess();
1509  }
1510
1511  return EqFailure(expected_expression,
1512                   actual_expression,
1513                   PrintToString(expected),
1514                   PrintToString(actual),
1515                   true);
1516}
1517
1518// The helper function for {ASSERT|EXPECT}_STRNE.
1519AssertionResult CmpHelperSTRNE(const char* s1_expression,
1520                               const char* s2_expression,
1521                               const char* s1,
1522                               const char* s2) {
1523  if (!String::CStringEquals(s1, s2)) {
1524    return AssertionSuccess();
1525  } else {
1526    return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
1527                              << s2_expression << "), actual: \""
1528                              << s1 << "\" vs \"" << s2 << "\"";
1529  }
1530}
1531
1532// The helper function for {ASSERT|EXPECT}_STRCASENE.
1533AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
1534                                   const char* s2_expression,
1535                                   const char* s1,
1536                                   const char* s2) {
1537  if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
1538    return AssertionSuccess();
1539  } else {
1540    return AssertionFailure()
1541        << "Expected: (" << s1_expression << ") != ("
1542        << s2_expression << ") (ignoring case), actual: \""
1543        << s1 << "\" vs \"" << s2 << "\"";
1544  }
1545}
1546
1547}  // namespace internal
1548
1549namespace {
1550
1551// Helper functions for implementing IsSubString() and IsNotSubstring().
1552
1553// This group of overloaded functions return true iff needle is a
1554// substring of haystack.  NULL is considered a substring of itself
1555// only.
1556
1557bool IsSubstringPred(const char* needle, const char* haystack) {
1558  if (needle == NULL || haystack == NULL)
1559    return needle == haystack;
1560
1561  return strstr(haystack, needle) != NULL;
1562}
1563
1564bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
1565  if (needle == NULL || haystack == NULL)
1566    return needle == haystack;
1567
1568  return wcsstr(haystack, needle) != NULL;
1569}
1570
1571// StringType here can be either ::std::string or ::std::wstring.
1572template <typename StringType>
1573bool IsSubstringPred(const StringType& needle,
1574                     const StringType& haystack) {
1575  return haystack.find(needle) != StringType::npos;
1576}
1577
1578// This function implements either IsSubstring() or IsNotSubstring(),
1579// depending on the value of the expected_to_be_substring parameter.
1580// StringType here can be const char*, const wchar_t*, ::std::string,
1581// or ::std::wstring.
1582template <typename StringType>
1583AssertionResult IsSubstringImpl(
1584    bool expected_to_be_substring,
1585    const char* needle_expr, const char* haystack_expr,
1586    const StringType& needle, const StringType& haystack) {
1587  if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
1588    return AssertionSuccess();
1589
1590  const bool is_wide_string = sizeof(needle[0]) > 1;
1591  const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
1592  return AssertionFailure()
1593      << "Value of: " << needle_expr << "\n"
1594      << "  Actual: " << begin_string_quote << needle << "\"\n"
1595      << "Expected: " << (expected_to_be_substring ? "" : "not ")
1596      << "a substring of " << haystack_expr << "\n"
1597      << "Which is: " << begin_string_quote << haystack << "\"";
1598}
1599
1600}  // namespace
1601
1602// IsSubstring() and IsNotSubstring() check whether needle is a
1603// substring of haystack (NULL is considered a substring of itself
1604// only), and return an appropriate error message when they fail.
1605
1606AssertionResult IsSubstring(
1607    const char* needle_expr, const char* haystack_expr,
1608    const char* needle, const char* haystack) {
1609  return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1610}
1611
1612AssertionResult IsSubstring(
1613    const char* needle_expr, const char* haystack_expr,
1614    const wchar_t* needle, const wchar_t* haystack) {
1615  return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1616}
1617
1618AssertionResult IsNotSubstring(
1619    const char* needle_expr, const char* haystack_expr,
1620    const char* needle, const char* haystack) {
1621  return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1622}
1623
1624AssertionResult IsNotSubstring(
1625    const char* needle_expr, const char* haystack_expr,
1626    const wchar_t* needle, const wchar_t* haystack) {
1627  return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1628}
1629
1630AssertionResult IsSubstring(
1631    const char* needle_expr, const char* haystack_expr,
1632    const ::std::string& needle, const ::std::string& haystack) {
1633  return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1634}
1635
1636AssertionResult IsNotSubstring(
1637    const char* needle_expr, const char* haystack_expr,
1638    const ::std::string& needle, const ::std::string& haystack) {
1639  return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1640}
1641
1642#if GTEST_HAS_STD_WSTRING
1643AssertionResult IsSubstring(
1644    const char* needle_expr, const char* haystack_expr,
1645    const ::std::wstring& needle, const ::std::wstring& haystack) {
1646  return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1647}
1648
1649AssertionResult IsNotSubstring(
1650    const char* needle_expr, const char* haystack_expr,
1651    const ::std::wstring& needle, const ::std::wstring& haystack) {
1652  return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1653}
1654#endif  // GTEST_HAS_STD_WSTRING
1655
1656namespace internal {
1657
1658#if GTEST_OS_WINDOWS
1659
1660namespace {
1661
1662// Helper function for IsHRESULT{SuccessFailure} predicates
1663AssertionResult HRESULTFailureHelper(const char* expr,
1664                                     const char* expected,
1665                                     long hr) {  // NOLINT
1666# if GTEST_OS_WINDOWS_MOBILE
1667
1668  // Windows CE doesn't support FormatMessage.
1669  const char error_text[] = "";
1670
1671# else
1672
1673  // Looks up the human-readable system message for the HRESULT code
1674  // and since we're not passing any params to FormatMessage, we don't
1675  // want inserts expanded.
1676  const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
1677                       FORMAT_MESSAGE_IGNORE_INSERTS;
1678  const DWORD kBufSize = 4096;
1679  // Gets the system's human readable message string for this HRESULT.
1680  char error_text[kBufSize] = { '\0' };
1681  DWORD message_length = ::FormatMessageA(kFlags,
1682                                          0,  // no source, we're asking system
1683                                          hr,  // the error
1684                                          0,  // no line width restrictions
1685                                          error_text,  // output buffer
1686                                          kBufSize,  // buf size
1687                                          NULL);  // no arguments for inserts
1688  // Trims tailing white space (FormatMessage leaves a trailing CR-LF)
1689  for (; message_length && IsSpace(error_text[message_length - 1]);
1690          --message_length) {
1691    error_text[message_length - 1] = '\0';
1692  }
1693
1694# endif  // GTEST_OS_WINDOWS_MOBILE
1695
1696  const std::string error_hex("0x" + String::FormatHexInt(hr));
1697  return ::testing::AssertionFailure()
1698      << "Expected: " << expr << " " << expected << ".\n"
1699      << "  Actual: " << error_hex << " " << error_text << "\n";
1700}
1701
1702}  // namespace
1703
1704AssertionResult IsHRESULTSuccess(const char* expr, long hr) {  // NOLINT
1705  if (SUCCEEDED(hr)) {
1706    return AssertionSuccess();
1707  }
1708  return HRESULTFailureHelper(expr, "succeeds", hr);
1709}
1710
1711AssertionResult IsHRESULTFailure(const char* expr, long hr) {  // NOLINT
1712  if (FAILED(hr)) {
1713    return AssertionSuccess();
1714  }
1715  return HRESULTFailureHelper(expr, "fails", hr);
1716}
1717
1718#endif  // GTEST_OS_WINDOWS
1719
1720// Utility functions for encoding Unicode text (wide strings) in
1721// UTF-8.
1722
1723// A Unicode code-point can have upto 21 bits, and is encoded in UTF-8
1724// like this:
1725//
1726// Code-point length   Encoding
1727//   0 -  7 bits       0xxxxxxx
1728//   8 - 11 bits       110xxxxx 10xxxxxx
1729//  12 - 16 bits       1110xxxx 10xxxxxx 10xxxxxx
1730//  17 - 21 bits       11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
1731
1732// The maximum code-point a one-byte UTF-8 sequence can represent.
1733const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) <<  7) - 1;
1734
1735// The maximum code-point a two-byte UTF-8 sequence can represent.
1736const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1;
1737
1738// The maximum code-point a three-byte UTF-8 sequence can represent.
1739const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2*6)) - 1;
1740
1741// The maximum code-point a four-byte UTF-8 sequence can represent.
1742const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3*6)) - 1;
1743
1744// Chops off the n lowest bits from a bit pattern.  Returns the n
1745// lowest bits.  As a side effect, the original bit pattern will be
1746// shifted to the right by n bits.
1747inline UInt32 ChopLowBits(UInt32* bits, int n) {
1748  const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1);
1749  *bits >>= n;
1750  return low_bits;
1751}
1752
1753// Converts a Unicode code point to a narrow string in UTF-8 encoding.
1754// code_point parameter is of type UInt32 because wchar_t may not be
1755// wide enough to contain a code point.
1756// If the code_point is not a valid Unicode code point
1757// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
1758// to "(Invalid Unicode 0xXXXXXXXX)".
1759std::string CodePointToUtf8(UInt32 code_point) {
1760  if (code_point > kMaxCodePoint4) {
1761    return "(Invalid Unicode 0x" + String::FormatHexInt(code_point) + ")";
1762  }
1763
1764  char str[5];  // Big enough for the largest valid code point.
1765  if (code_point <= kMaxCodePoint1) {
1766    str[1] = '\0';
1767    str[0] = static_cast<char>(code_point);                          // 0xxxxxxx
1768  } else if (code_point <= kMaxCodePoint2) {
1769    str[2] = '\0';
1770    str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
1771    str[0] = static_cast<char>(0xC0 | code_point);                   // 110xxxxx
1772  } else if (code_point <= kMaxCodePoint3) {
1773    str[3] = '\0';
1774    str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
1775    str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
1776    str[0] = static_cast<char>(0xE0 | code_point);                   // 1110xxxx
1777  } else {  // code_point <= kMaxCodePoint4
1778    str[4] = '\0';
1779    str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
1780    str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
1781    str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
1782    str[0] = static_cast<char>(0xF0 | code_point);                   // 11110xxx
1783  }
1784  return str;
1785}
1786
1787// The following two functions only make sense if the the system
1788// uses UTF-16 for wide string encoding. All supported systems
1789// with 16 bit wchar_t (Windows, Cygwin, Symbian OS) do use UTF-16.
1790
1791// Determines if the arguments constitute UTF-16 surrogate pair
1792// and thus should be combined into a single Unicode code point
1793// using CreateCodePointFromUtf16SurrogatePair.
1794inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
1795  return sizeof(wchar_t) == 2 &&
1796      (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;
1797}
1798
1799// Creates a Unicode code point from UTF16 surrogate pair.
1800inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first,
1801                                                    wchar_t second) {
1802  const UInt32 mask = (1 << 10) - 1;
1803  return (sizeof(wchar_t) == 2) ?
1804      (((first & mask) << 10) | (second & mask)) + 0x10000 :
1805      // This function should not be called when the condition is
1806      // false, but we provide a sensible default in case it is.
1807      static_cast<UInt32>(first);
1808}
1809
1810// Converts a wide string to a narrow string in UTF-8 encoding.
1811// The wide string is assumed to have the following encoding:
1812//   UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
1813//   UTF-32 if sizeof(wchar_t) == 4 (on Linux)
1814// Parameter str points to a null-terminated wide string.
1815// Parameter num_chars may additionally limit the number
1816// of wchar_t characters processed. -1 is used when the entire string
1817// should be processed.
1818// If the string contains code points that are not valid Unicode code points
1819// (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
1820// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
1821// and contains invalid UTF-16 surrogate pairs, values in those pairs
1822// will be encoded as individual Unicode characters from Basic Normal Plane.
1823std::string WideStringToUtf8(const wchar_t* str, int num_chars) {
1824  if (num_chars == -1)
1825    num_chars = static_cast<int>(wcslen(str));
1826
1827  ::std::stringstream stream;
1828  for (int i = 0; i < num_chars; ++i) {
1829    UInt32 unicode_code_point;
1830
1831    if (str[i] == L'\0') {
1832      break;
1833    } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
1834      unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i],
1835                                                                 str[i + 1]);
1836      i++;
1837    } else {
1838      unicode_code_point = static_cast<UInt32>(str[i]);
1839    }
1840
1841    stream << CodePointToUtf8(unicode_code_point);
1842  }
1843  return StringStreamToString(&stream);
1844}
1845
1846// Converts a wide C string to an std::string using the UTF-8 encoding.
1847// NULL will be converted to "(null)".
1848std::string String::ShowWideCString(const wchar_t * wide_c_str) {
1849  if (wide_c_str == NULL)  return "(null)";
1850
1851  return internal::WideStringToUtf8(wide_c_str, -1);
1852}
1853
1854// Compares two wide C strings.  Returns true iff they have the same
1855// content.
1856//
1857// Unlike wcscmp(), this function can handle NULL argument(s).  A NULL
1858// C string is considered different to any non-NULL C string,
1859// including the empty string.
1860bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {
1861  if (lhs == NULL) return rhs == NULL;
1862
1863  if (rhs == NULL) return false;
1864
1865  return wcscmp(lhs, rhs) == 0;
1866}
1867
1868// Helper function for *_STREQ on wide strings.
1869AssertionResult CmpHelperSTREQ(const char* expected_expression,
1870                               const char* actual_expression,
1871                               const wchar_t* expected,
1872                               const wchar_t* actual) {
1873  if (String::WideCStringEquals(expected, actual)) {
1874    return AssertionSuccess();
1875  }
1876
1877  return EqFailure(expected_expression,
1878                   actual_expression,
1879                   PrintToString(expected),
1880                   PrintToString(actual),
1881                   false);
1882}
1883
1884// Helper function for *_STRNE on wide strings.
1885AssertionResult CmpHelperSTRNE(const char* s1_expression,
1886                               const char* s2_expression,
1887                               const wchar_t* s1,
1888                               const wchar_t* s2) {
1889  if (!String::WideCStringEquals(s1, s2)) {
1890    return AssertionSuccess();
1891  }
1892
1893  return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
1894                            << s2_expression << "), actual: "
1895                            << PrintToString(s1)
1896                            << " vs " << PrintToString(s2);
1897}
1898
1899// Compares two C strings, ignoring case.  Returns true iff they have
1900// the same content.
1901//
1902// Unlike strcasecmp(), this function can handle NULL argument(s).  A
1903// NULL C string is considered different to any non-NULL C string,
1904// including the empty string.
1905bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) {
1906  if (lhs == NULL)
1907    return rhs == NULL;
1908  if (rhs == NULL)
1909    return false;
1910  return posix::StrCaseCmp(lhs, rhs) == 0;
1911}
1912
1913  // Compares two wide C strings, ignoring case.  Returns true iff they
1914  // have the same content.
1915  //
1916  // Unlike wcscasecmp(), this function can handle NULL argument(s).
1917  // A NULL C string is considered different to any non-NULL wide C string,
1918  // including the empty string.
1919  // NB: The implementations on different platforms slightly differ.
1920  // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
1921  // environment variable. On GNU platform this method uses wcscasecmp
1922  // which compares according to LC_CTYPE category of the current locale.
1923  // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
1924  // current locale.
1925bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
1926                                              const wchar_t* rhs) {
1927  if (lhs == NULL) return rhs == NULL;
1928
1929  if (rhs == NULL) return false;
1930
1931#if GTEST_OS_WINDOWS
1932  return _wcsicmp(lhs, rhs) == 0;
1933#elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID
1934  return wcscasecmp(lhs, rhs) == 0;
1935#else
1936  // Android, Mac OS X and Cygwin don't define wcscasecmp.
1937  // Other unknown OSes may not define it either.
1938  wint_t left, right;
1939  do {
1940    left = towlower(*lhs++);
1941    right = towlower(*rhs++);
1942  } while (left && left == right);
1943  return left == right;
1944#endif  // OS selector
1945}
1946
1947// Returns true iff str ends with the given suffix, ignoring case.
1948// Any string is considered to end with an empty suffix.
1949bool String::EndsWithCaseInsensitive(
1950    const std::string& str, const std::string& suffix) {
1951  const size_t str_len = str.length();
1952  const size_t suffix_len = suffix.length();
1953  return (str_len >= suffix_len) &&
1954         CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len,
1955                                      suffix.c_str());
1956}
1957
1958// Formats an int value as "%02d".
1959std::string String::FormatIntWidth2(int value) {
1960  std::stringstream ss;
1961  ss << std::setfill('0') << std::setw(2) << value;
1962  return ss.str();
1963}
1964
1965// Formats an int value as "%X".
1966std::string String::FormatHexInt(int value) {
1967  std::stringstream ss;
1968  ss << std::hex << std::uppercase << value;
1969  return ss.str();
1970}
1971
1972// Formats a byte as "%02X".
1973std::string String::FormatByte(unsigned char value) {
1974  std::stringstream ss;
1975  ss << std::setfill('0') << std::setw(2) << std::hex << std::uppercase
1976     << static_cast<unsigned int>(value);
1977  return ss.str();
1978}
1979
1980// Converts the buffer in a stringstream to an std::string, converting NUL
1981// bytes to "\\0" along the way.
1982std::string StringStreamToString(::std::stringstream* ss) {
1983  const ::std::string& str = ss->str();
1984  const char* const start = str.c_str();
1985  const char* const end = start + str.length();
1986
1987  std::string result;
1988  result.reserve(2 * (end - start));
1989  for (const char* ch = start; ch != end; ++ch) {
1990    if (*ch == '\0') {
1991      result += "\\0";  // Replaces NUL with "\\0";
1992    } else {
1993      result += *ch;
1994    }
1995  }
1996
1997  return result;
1998}
1999
2000// Appends the user-supplied message to the Google-Test-generated message.
2001std::string AppendUserMessage(const std::string& gtest_msg,
2002                              const Message& user_msg) {
2003  // Appends the user message if it's non-empty.
2004  const std::string user_msg_string = user_msg.GetString();
2005  if (user_msg_string.empty()) {
2006    return gtest_msg;
2007  }
2008
2009  return gtest_msg + "\n" + user_msg_string;
2010}
2011
2012}  // namespace internal
2013
2014// class TestResult
2015
2016// Creates an empty TestResult.
2017TestResult::TestResult()
2018    : death_test_count_(0),
2019      elapsed_time_(0) {
2020}
2021
2022// D'tor.
2023TestResult::~TestResult() {
2024}
2025
2026// Returns the i-th test part result among all the results. i can
2027// range from 0 to total_part_count() - 1. If i is not in that range,
2028// aborts the program.
2029const TestPartResult& TestResult::GetTestPartResult(int i) const {
2030  if (i < 0 || i >= total_part_count())
2031    internal::posix::Abort();
2032  return test_part_results_.at(i);
2033}
2034
2035// Returns the i-th test property. i can range from 0 to
2036// test_property_count() - 1. If i is not in that range, aborts the
2037// program.
2038const TestProperty& TestResult::GetTestProperty(int i) const {
2039  if (i < 0 || i >= test_property_count())
2040    internal::posix::Abort();
2041  return test_properties_.at(i);
2042}
2043
2044// Clears the test part results.
2045void TestResult::ClearTestPartResults() {
2046  test_part_results_.clear();
2047}
2048
2049// Adds a test part result to the list.
2050void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
2051  test_part_results_.push_back(test_part_result);
2052}
2053
2054// Adds a test property to the list. If a property with the same key as the
2055// supplied property is already represented, the value of this test_property
2056// replaces the old value for that key.
2057void TestResult::RecordProperty(const std::string& xml_element,
2058                                const TestProperty& test_property) {
2059  if (!ValidateTestProperty(xml_element, test_property)) {
2060    return;
2061  }
2062  internal::MutexLock lock(&test_properites_mutex_);
2063  const std::vector<TestProperty>::iterator property_with_matching_key =
2064      std::find_if(test_properties_.begin(), test_properties_.end(),
2065                   internal::TestPropertyKeyIs(test_property.key()));
2066  if (property_with_matching_key == test_properties_.end()) {
2067    test_properties_.push_back(test_property);
2068    return;
2069  }
2070  property_with_matching_key->SetValue(test_property.value());
2071}
2072
2073// The list of reserved attributes used in the <testsuites> element of XML
2074// output.
2075static const char* const kReservedTestSuitesAttributes[] = {
2076  "disabled",
2077  "errors",
2078  "failures",
2079  "name",
2080  "random_seed",
2081  "tests",
2082  "time",
2083  "timestamp"
2084};
2085
2086// The list of reserved attributes used in the <testsuite> element of XML
2087// output.
2088static const char* const kReservedTestSuiteAttributes[] = {
2089  "disabled",
2090  "errors",
2091  "failures",
2092  "name",
2093  "tests",
2094  "time"
2095};
2096
2097// The list of reserved attributes used in the <testcase> element of XML output.
2098static const char* const kReservedTestCaseAttributes[] = {
2099  "classname",
2100  "name",
2101  "status",
2102  "time",
2103  "type_param",
2104  "value_param"
2105};
2106
2107template <int kSize>
2108std::vector<std::string> ArrayAsVector(const char* const (&array)[kSize]) {
2109  return std::vector<std::string>(array, array + kSize);
2110}
2111
2112static std::vector<std::string> GetReservedAttributesForElement(
2113    const std::string& xml_element) {
2114  if (xml_element == "testsuites") {
2115    return ArrayAsVector(kReservedTestSuitesAttributes);
2116  } else if (xml_element == "testsuite") {
2117    return ArrayAsVector(kReservedTestSuiteAttributes);
2118  } else if (xml_element == "testcase") {
2119    return ArrayAsVector(kReservedTestCaseAttributes);
2120  } else {
2121    GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element;
2122  }
2123  // This code is unreachable but some compilers may not realizes that.
2124  return std::vector<std::string>();
2125}
2126
2127static std::string FormatWordList(const std::vector<std::string>& words) {
2128  Message word_list;
2129  for (size_t i = 0; i < words.size(); ++i) {
2130    if (i > 0 && words.size() > 2) {
2131      word_list << ", ";
2132    }
2133    if (i == words.size() - 1) {
2134      word_list << "and ";
2135    }
2136    word_list << "'" << words[i] << "'";
2137  }
2138  return word_list.GetString();
2139}
2140
2141bool ValidateTestPropertyName(const std::string& property_name,
2142                              const std::vector<std::string>& reserved_names) {
2143  if (std::find(reserved_names.begin(), reserved_names.end(), property_name) !=
2144          reserved_names.end()) {
2145    ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name
2146                  << " (" << FormatWordList(reserved_names)
2147                  << " are reserved by " << GTEST_NAME_ << ")";
2148    return false;
2149  }
2150  return true;
2151}
2152
2153// Adds a failure if the key is a reserved attribute of the element named
2154// xml_element.  Returns true if the property is valid.
2155bool TestResult::ValidateTestProperty(const std::string& xml_element,
2156                                      const TestProperty& test_property) {
2157  return ValidateTestPropertyName(test_property.key(),
2158                                  GetReservedAttributesForElement(xml_element));
2159}
2160
2161// Clears the object.
2162void TestResult::Clear() {
2163  test_part_results_.clear();
2164  test_properties_.clear();
2165  death_test_count_ = 0;
2166  elapsed_time_ = 0;
2167}
2168
2169// Returns true iff the test failed.
2170bool TestResult::Failed() const {
2171  for (int i = 0; i < total_part_count(); ++i) {
2172    if (GetTestPartResult(i).failed())
2173      return true;
2174  }
2175  return false;
2176}
2177
2178// Returns true iff the test part fatally failed.
2179static bool TestPartFatallyFailed(const TestPartResult& result) {
2180  return result.fatally_failed();
2181}
2182
2183// Returns true iff the test fatally failed.
2184bool TestResult::HasFatalFailure() const {
2185  return CountIf(test_part_results_, TestPartFatallyFailed) > 0;
2186}
2187
2188// Returns true iff the test part non-fatally failed.
2189static bool TestPartNonfatallyFailed(const TestPartResult& result) {
2190  return result.nonfatally_failed();
2191}
2192
2193// Returns true iff the test has a non-fatal failure.
2194bool TestResult::HasNonfatalFailure() const {
2195  return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0;
2196}
2197
2198// Gets the number of all test parts.  This is the sum of the number
2199// of successful test parts and the number of failed test parts.
2200int TestResult::total_part_count() const {
2201  return static_cast<int>(test_part_results_.size());
2202}
2203
2204// Returns the number of the test properties.
2205int TestResult::test_property_count() const {
2206  return static_cast<int>(test_properties_.size());
2207}
2208
2209// class Test
2210
2211// Creates a Test object.
2212
2213// The c'tor saves the states of all flags.
2214Test::Test()
2215    : gtest_flag_saver_(new GTEST_FLAG_SAVER_) {
2216}
2217
2218// The d'tor restores the states of all flags.  The actual work is
2219// done by the d'tor of the gtest_flag_saver_ field, and thus not
2220// visible here.
2221Test::~Test() {
2222}
2223
2224// Sets up the test fixture.
2225//
2226// A sub-class may override this.
2227void Test::SetUp() {
2228}
2229
2230// Tears down the test fixture.
2231//
2232// A sub-class may override this.
2233void Test::TearDown() {
2234}
2235
2236// Allows user supplied key value pairs to be recorded for later output.
2237void Test::RecordProperty(const std::string& key, const std::string& value) {
2238  UnitTest::GetInstance()->RecordProperty(key, value);
2239}
2240
2241// Allows user supplied key value pairs to be recorded for later output.
2242void Test::RecordProperty(const std::string& key, int value) {
2243  Message value_message;
2244  value_message << value;
2245  RecordProperty(key, value_message.GetString().c_str());
2246}
2247
2248namespace internal {
2249
2250void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
2251                                    const std::string& message) {
2252  // This function is a friend of UnitTest and as such has access to
2253  // AddTestPartResult.
2254  UnitTest::GetInstance()->AddTestPartResult(
2255      result_type,
2256      NULL,  // No info about the source file where the exception occurred.
2257      -1,    // We have no info on which line caused the exception.
2258      message,
2259      "");   // No stack trace, either.
2260}
2261
2262}  // namespace internal
2263
2264// Google Test requires all tests in the same test case to use the same test
2265// fixture class.  This function checks if the current test has the
2266// same fixture class as the first test in the current test case.  If
2267// yes, it returns true; otherwise it generates a Google Test failure and
2268// returns false.
2269bool Test::HasSameFixtureClass() {
2270  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2271  const TestCase* const test_case = impl->current_test_case();
2272
2273  // Info about the first test in the current test case.
2274  const TestInfo* const first_test_info = test_case->test_info_list()[0];
2275  const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_;
2276  const char* const first_test_name = first_test_info->name();
2277
2278  // Info about the current test.
2279  const TestInfo* const this_test_info = impl->current_test_info();
2280  const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_;
2281  const char* const this_test_name = this_test_info->name();
2282
2283  if (this_fixture_id != first_fixture_id) {
2284    // Is the first test defined using TEST?
2285    const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();
2286    // Is this test defined using TEST?
2287    const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();
2288
2289    if (first_is_TEST || this_is_TEST) {
2290      // Both TEST and TEST_F appear in same test case, which is incorrect.
2291      // Tell the user how to fix this.
2292
2293      // Gets the name of the TEST and the name of the TEST_F.  Note
2294      // that first_is_TEST and this_is_TEST cannot both be true, as
2295      // the fixture IDs are different for the two tests.
2296      const char* const TEST_name =
2297          first_is_TEST ? first_test_name : this_test_name;
2298      const char* const TEST_F_name =
2299          first_is_TEST ? this_test_name : first_test_name;
2300
2301      ADD_FAILURE()
2302          << "All tests in the same test case must use the same test fixture\n"
2303          << "class, so mixing TEST_F and TEST in the same test case is\n"
2304          << "illegal.  In test case " << this_test_info->test_case_name()
2305          << ",\n"
2306          << "test " << TEST_F_name << " is defined using TEST_F but\n"
2307          << "test " << TEST_name << " is defined using TEST.  You probably\n"
2308          << "want to change the TEST to TEST_F or move it to another test\n"
2309          << "case.";
2310    } else {
2311      // Two fixture classes with the same name appear in two different
2312      // namespaces, which is not allowed. Tell the user how to fix this.
2313      ADD_FAILURE()
2314          << "All tests in the same test case must use the same test fixture\n"
2315          << "class.  However, in test case "
2316          << this_test_info->test_case_name() << ",\n"
2317          << "you defined test " << first_test_name
2318          << " and test " << this_test_name << "\n"
2319          << "using two different test fixture classes.  This can happen if\n"
2320          << "the two classes are from different namespaces or translation\n"
2321          << "units and have the same name.  You should probably rename one\n"
2322          << "of the classes to put the tests into different test cases.";
2323    }
2324    return false;
2325  }
2326
2327  return true;
2328}
2329
2330#if GTEST_HAS_SEH
2331
2332// Adds an "exception thrown" fatal failure to the current test.  This
2333// function returns its result via an output parameter pointer because VC++
2334// prohibits creation of objects with destructors on stack in functions
2335// using __try (see error C2712).
2336static std::string* FormatSehExceptionMessage(DWORD exception_code,
2337                                              const char* location) {
2338  Message message;
2339  message << "SEH exception with code 0x" << std::setbase(16) <<
2340    exception_code << std::setbase(10) << " thrown in " << location << ".";
2341
2342  return new std::string(message.GetString());
2343}
2344
2345#endif  // GTEST_HAS_SEH
2346
2347namespace internal {
2348
2349#if GTEST_HAS_EXCEPTIONS
2350
2351// Adds an "exception thrown" fatal failure to the current test.
2352static std::string FormatCxxExceptionMessage(const char* description,
2353                                             const char* location) {
2354  Message message;
2355  if (description != NULL) {
2356    message << "C++ exception with description \"" << description << "\"";
2357  } else {
2358    message << "Unknown C++ exception";
2359  }
2360  message << " thrown in " << location << ".";
2361
2362  return message.GetString();
2363}
2364
2365static std::string PrintTestPartResultToString(
2366    const TestPartResult& test_part_result);
2367
2368GoogleTestFailureException::GoogleTestFailureException(
2369    const TestPartResult& failure)
2370    : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
2371
2372#endif  // GTEST_HAS_EXCEPTIONS
2373
2374// We put these helper functions in the internal namespace as IBM's xlC
2375// compiler rejects the code if they were declared static.
2376
2377// Runs the given method and handles SEH exceptions it throws, when
2378// SEH is supported; returns the 0-value for type Result in case of an
2379// SEH exception.  (Microsoft compilers cannot handle SEH and C++
2380// exceptions in the same function.  Therefore, we provide a separate
2381// wrapper function for handling SEH exceptions.)
2382template <class T, typename Result>
2383Result HandleSehExceptionsInMethodIfSupported(
2384    T* object, Result (T::*method)(), const char* location) {
2385#if GTEST_HAS_SEH
2386  __try {
2387    return (object->*method)();
2388  } __except (internal::UnitTestOptions::GTestShouldProcessSEH(  // NOLINT
2389      GetExceptionCode())) {
2390    // We create the exception message on the heap because VC++ prohibits
2391    // creation of objects with destructors on stack in functions using __try
2392    // (see error C2712).
2393    std::string* exception_message = FormatSehExceptionMessage(
2394        GetExceptionCode(), location);
2395    internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
2396                                             *exception_message);
2397    delete exception_message;
2398    return static_cast<Result>(0);
2399  }
2400#else
2401  (void)location;
2402  return (object->*method)();
2403#endif  // GTEST_HAS_SEH
2404}
2405
2406// Runs the given method and catches and reports C++ and/or SEH-style
2407// exceptions, if they are supported; returns the 0-value for type
2408// Result in case of an SEH exception.
2409template <class T, typename Result>
2410Result HandleExceptionsInMethodIfSupported(
2411    T* object, Result (T::*method)(), const char* location) {
2412  // NOTE: The user code can affect the way in which Google Test handles
2413  // exceptions by setting GTEST_FLAG(catch_exceptions), but only before
2414  // RUN_ALL_TESTS() starts. It is technically possible to check the flag
2415  // after the exception is caught and either report or re-throw the
2416  // exception based on the flag's value:
2417  //
2418  // try {
2419  //   // Perform the test method.
2420  // } catch (...) {
2421  //   if (GTEST_FLAG(catch_exceptions))
2422  //     // Report the exception as failure.
2423  //   else
2424  //     throw;  // Re-throws the original exception.
2425  // }
2426  //
2427  // However, the purpose of this flag is to allow the program to drop into
2428  // the debugger when the exception is thrown. On most platforms, once the
2429  // control enters the catch block, the exception origin information is
2430  // lost and the debugger will stop the program at the point of the
2431  // re-throw in this function -- instead of at the point of the original
2432  // throw statement in the code under test.  For this reason, we perform
2433  // the check early, sacrificing the ability to affect Google Test's
2434  // exception handling in the method where the exception is thrown.
2435  if (internal::GetUnitTestImpl()->catch_exceptions()) {
2436#if GTEST_HAS_EXCEPTIONS
2437    try {
2438      return HandleSehExceptionsInMethodIfSupported(object, method, location);
2439    } catch (const internal::GoogleTestFailureException&) {  // NOLINT
2440      // This exception type can only be thrown by a failed Google
2441      // Test assertion with the intention of letting another testing
2442      // framework catch it.  Therefore we just re-throw it.
2443      throw;
2444    } catch (const std::exception& e) {  // NOLINT
2445      internal::ReportFailureInUnknownLocation(
2446          TestPartResult::kFatalFailure,
2447          FormatCxxExceptionMessage(e.what(), location));
2448    } catch (...) {  // NOLINT
2449      internal::ReportFailureInUnknownLocation(
2450          TestPartResult::kFatalFailure,
2451          FormatCxxExceptionMessage(NULL, location));
2452    }
2453    return static_cast<Result>(0);
2454#else
2455    return HandleSehExceptionsInMethodIfSupported(object, method, location);
2456#endif  // GTEST_HAS_EXCEPTIONS
2457  } else {
2458    return (object->*method)();
2459  }
2460}
2461
2462}  // namespace internal
2463
2464// Runs the test and updates the test result.
2465void Test::Run() {
2466  if (!HasSameFixtureClass()) return;
2467
2468  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2469  impl->os_stack_trace_getter()->UponLeavingGTest();
2470  internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()");
2471  // We will run the test only if SetUp() was successful.
2472  if (!HasFatalFailure()) {
2473    impl->os_stack_trace_getter()->UponLeavingGTest();
2474    internal::HandleExceptionsInMethodIfSupported(
2475        this, &Test::TestBody, "the test body");
2476  }
2477
2478  // However, we want to clean up as much as possible.  Hence we will
2479  // always call TearDown(), even if SetUp() or the test body has
2480  // failed.
2481  impl->os_stack_trace_getter()->UponLeavingGTest();
2482  internal::HandleExceptionsInMethodIfSupported(
2483      this, &Test::TearDown, "TearDown()");
2484}
2485
2486// Returns true iff the current test has a fatal failure.
2487bool Test::HasFatalFailure() {
2488  return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
2489}
2490
2491// Returns true iff the current test has a non-fatal failure.
2492bool Test::HasNonfatalFailure() {
2493  return internal::GetUnitTestImpl()->current_test_result()->
2494      HasNonfatalFailure();
2495}
2496
2497// class TestInfo
2498
2499// Constructs a TestInfo object. It assumes ownership of the test factory
2500// object.
2501TestInfo::TestInfo(const std::string& a_test_case_name,
2502                   const std::string& a_name,
2503                   const char* a_type_param,
2504                   const char* a_value_param,
2505                   internal::CodeLocation a_code_location,
2506                   internal::TypeId fixture_class_id,
2507                   internal::TestFactoryBase* factory)
2508    : test_case_name_(a_test_case_name),
2509      name_(a_name),
2510      type_param_(a_type_param ? new std::string(a_type_param) : NULL),
2511      value_param_(a_value_param ? new std::string(a_value_param) : NULL),
2512      location_(a_code_location),
2513      fixture_class_id_(fixture_class_id),
2514      should_run_(false),
2515      is_disabled_(false),
2516      matches_filter_(false),
2517      factory_(factory),
2518      result_() {}
2519
2520// Destructs a TestInfo object.
2521TestInfo::~TestInfo() { delete factory_; }
2522
2523namespace internal {
2524
2525// Creates a new TestInfo object and registers it with Google Test;
2526// returns the created object.
2527//
2528// Arguments:
2529//
2530//   test_case_name:   name of the test case
2531//   name:             name of the test
2532//   type_param:       the name of the test's type parameter, or NULL if
2533//                     this is not a typed or a type-parameterized test.
2534//   value_param:      text representation of the test's value parameter,
2535//                     or NULL if this is not a value-parameterized test.
2536//   code_location:    code location where the test is defined
2537//   fixture_class_id: ID of the test fixture class
2538//   set_up_tc:        pointer to the function that sets up the test case
2539//   tear_down_tc:     pointer to the function that tears down the test case
2540//   factory:          pointer to the factory that creates a test object.
2541//                     The newly created TestInfo instance will assume
2542//                     ownership of the factory object.
2543TestInfo* MakeAndRegisterTestInfo(
2544    const char* test_case_name,
2545    const char* name,
2546    const char* type_param,
2547    const char* value_param,
2548    CodeLocation code_location,
2549    TypeId fixture_class_id,
2550    SetUpTestCaseFunc set_up_tc,
2551    TearDownTestCaseFunc tear_down_tc,
2552    TestFactoryBase* factory) {
2553  TestInfo* const test_info =
2554      new TestInfo(test_case_name, name, type_param, value_param,
2555                   code_location, fixture_class_id, factory);
2556  GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
2557  return test_info;
2558}
2559
2560#if GTEST_HAS_PARAM_TEST
2561void ReportInvalidTestCaseType(const char* test_case_name,
2562                               CodeLocation code_location) {
2563  Message errors;
2564  errors
2565      << "Attempted redefinition of test case " << test_case_name << ".\n"
2566      << "All tests in the same test case must use the same test fixture\n"
2567      << "class.  However, in test case " << test_case_name << ", you tried\n"
2568      << "to define a test using a fixture class different from the one\n"
2569      << "used earlier. This can happen if the two fixture classes are\n"
2570      << "from different namespaces and have the same name. You should\n"
2571      << "probably rename one of the classes to put the tests into different\n"
2572      << "test cases.";
2573
2574  fprintf(stderr, "%s %s",
2575          FormatFileLocation(code_location.file.c_str(),
2576                             code_location.line).c_str(),
2577          errors.GetString().c_str());
2578}
2579#endif  // GTEST_HAS_PARAM_TEST
2580
2581}  // namespace internal
2582
2583namespace {
2584
2585// A predicate that checks the test name of a TestInfo against a known
2586// value.
2587//
2588// This is used for implementation of the TestCase class only.  We put
2589// it in the anonymous namespace to prevent polluting the outer
2590// namespace.
2591//
2592// TestNameIs is copyable.
2593class TestNameIs {
2594 public:
2595  // Constructor.
2596  //
2597  // TestNameIs has NO default constructor.
2598  explicit TestNameIs(const char* name)
2599      : name_(name) {}
2600
2601  // Returns true iff the test name of test_info matches name_.
2602  bool operator()(const TestInfo * test_info) const {
2603    return test_info && test_info->name() == name_;
2604  }
2605
2606 private:
2607  std::string name_;
2608};
2609
2610}  // namespace
2611
2612namespace internal {
2613
2614// This method expands all parameterized tests registered with macros TEST_P
2615// and INSTANTIATE_TEST_CASE_P into regular tests and registers those.
2616// This will be done just once during the program runtime.
2617void UnitTestImpl::RegisterParameterizedTests() {
2618#if GTEST_HAS_PARAM_TEST
2619  if (!parameterized_tests_registered_) {
2620    parameterized_test_registry_.RegisterTests();
2621    parameterized_tests_registered_ = true;
2622  }
2623#endif
2624}
2625
2626}  // namespace internal
2627
2628// Creates the test object, runs it, records its result, and then
2629// deletes it.
2630void TestInfo::Run() {
2631  if (!should_run_) return;
2632
2633  // Tells UnitTest where to store test result.
2634  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2635  impl->set_current_test_info(this);
2636
2637  TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
2638
2639  // Notifies the unit test event listeners that a test is about to start.
2640  repeater->OnTestStart(*this);
2641
2642  const TimeInMillis start = internal::GetTimeInMillis();
2643
2644  impl->os_stack_trace_getter()->UponLeavingGTest();
2645
2646  // Creates the test object.
2647  Test* const test = internal::HandleExceptionsInMethodIfSupported(
2648      factory_, &internal::TestFactoryBase::CreateTest,
2649      "the test fixture's constructor");
2650
2651  // Runs the test only if the test object was created and its
2652  // constructor didn't generate a fatal failure.
2653  if ((test != NULL) && !Test::HasFatalFailure()) {
2654    // This doesn't throw as all user code that can throw are wrapped into
2655    // exception handling code.
2656    test->Run();
2657  }
2658
2659  // Deletes the test object.
2660  impl->os_stack_trace_getter()->UponLeavingGTest();
2661  internal::HandleExceptionsInMethodIfSupported(
2662      test, &Test::DeleteSelf_, "the test fixture's destructor");
2663
2664  result_.set_elapsed_time(internal::GetTimeInMillis() - start);
2665
2666  // Notifies the unit test event listener that a test has just finished.
2667  repeater->OnTestEnd(*this);
2668
2669  // Tells UnitTest to stop associating assertion results to this
2670  // test.
2671  impl->set_current_test_info(NULL);
2672}
2673
2674// class TestCase
2675
2676// Gets the number of successful tests in this test case.
2677int TestCase::successful_test_count() const {
2678  return CountIf(test_info_list_, TestPassed);
2679}
2680
2681// Gets the number of failed tests in this test case.
2682int TestCase::failed_test_count() const {
2683  return CountIf(test_info_list_, TestFailed);
2684}
2685
2686// Gets the number of disabled tests that will be reported in the XML report.
2687int TestCase::reportable_disabled_test_count() const {
2688  return CountIf(test_info_list_, TestReportableDisabled);
2689}
2690
2691// Gets the number of disabled tests in this test case.
2692int TestCase::disabled_test_count() const {
2693  return CountIf(test_info_list_, TestDisabled);
2694}
2695
2696// Gets the number of tests to be printed in the XML report.
2697int TestCase::reportable_test_count() const {
2698  return CountIf(test_info_list_, TestReportable);
2699}
2700
2701// Get the number of tests in this test case that should run.
2702int TestCase::test_to_run_count() const {
2703  return CountIf(test_info_list_, ShouldRunTest);
2704}
2705
2706// Gets the number of all tests.
2707int TestCase::total_test_count() const {
2708  return static_cast<int>(test_info_list_.size());
2709}
2710
2711// Creates a TestCase with the given name.
2712//
2713// Arguments:
2714//
2715//   name:         name of the test case
2716//   a_type_param: the name of the test case's type parameter, or NULL if
2717//                 this is not a typed or a type-parameterized test case.
2718//   set_up_tc:    pointer to the function that sets up the test case
2719//   tear_down_tc: pointer to the function that tears down the test case
2720TestCase::TestCase(const char* a_name, const char* a_type_param,
2721                   Test::SetUpTestCaseFunc set_up_tc,
2722                   Test::TearDownTestCaseFunc tear_down_tc)
2723    : name_(a_name),
2724      type_param_(a_type_param ? new std::string(a_type_param) : NULL),
2725      set_up_tc_(set_up_tc),
2726      tear_down_tc_(tear_down_tc),
2727      should_run_(false),
2728      elapsed_time_(0) {
2729}
2730
2731// Destructor of TestCase.
2732TestCase::~TestCase() {
2733  // Deletes every Test in the collection.
2734  ForEach(test_info_list_, internal::Delete<TestInfo>);
2735}
2736
2737// Returns the i-th test among all the tests. i can range from 0 to
2738// total_test_count() - 1. If i is not in that range, returns NULL.
2739const TestInfo* TestCase::GetTestInfo(int i) const {
2740  const int index = GetElementOr(test_indices_, i, -1);
2741  return index < 0 ? NULL : test_info_list_[index];
2742}
2743
2744// Returns the i-th test among all the tests. i can range from 0 to
2745// total_test_count() - 1. If i is not in that range, returns NULL.
2746TestInfo* TestCase::GetMutableTestInfo(int i) {
2747  const int index = GetElementOr(test_indices_, i, -1);
2748  return index < 0 ? NULL : test_info_list_[index];
2749}
2750
2751// Adds a test to this test case.  Will delete the test upon
2752// destruction of the TestCase object.
2753void TestCase::AddTestInfo(TestInfo * test_info) {
2754  test_info_list_.push_back(test_info);
2755  test_indices_.push_back(static_cast<int>(test_indices_.size()));
2756}
2757
2758// Runs every test in this TestCase.
2759void TestCase::Run() {
2760  if (!should_run_) return;
2761
2762  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2763  impl->set_current_test_case(this);
2764
2765  TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
2766
2767  repeater->OnTestCaseStart(*this);
2768  impl->os_stack_trace_getter()->UponLeavingGTest();
2769  internal::HandleExceptionsInMethodIfSupported(
2770      this, &TestCase::RunSetUpTestCase, "SetUpTestCase()");
2771
2772  const internal::TimeInMillis start = internal::GetTimeInMillis();
2773  for (int i = 0; i < total_test_count(); i++) {
2774    GetMutableTestInfo(i)->Run();
2775  }
2776  elapsed_time_ = internal::GetTimeInMillis() - start;
2777
2778  impl->os_stack_trace_getter()->UponLeavingGTest();
2779  internal::HandleExceptionsInMethodIfSupported(
2780      this, &TestCase::RunTearDownTestCase, "TearDownTestCase()");
2781
2782  repeater->OnTestCaseEnd(*this);
2783  impl->set_current_test_case(NULL);
2784}
2785
2786// Clears the results of all tests in this test case.
2787void TestCase::ClearResult() {
2788  ad_hoc_test_result_.Clear();
2789  ForEach(test_info_list_, TestInfo::ClearTestResult);
2790}
2791
2792// Shuffles the tests in this test case.
2793void TestCase::ShuffleTests(internal::Random* random) {
2794  Shuffle(random, &test_indices_);
2795}
2796
2797// Restores the test order to before the first shuffle.
2798void TestCase::UnshuffleTests() {
2799  for (size_t i = 0; i < test_indices_.size(); i++) {
2800    test_indices_[i] = static_cast<int>(i);
2801  }
2802}
2803
2804// Formats a countable noun.  Depending on its quantity, either the
2805// singular form or the plural form is used. e.g.
2806//
2807// FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
2808// FormatCountableNoun(5, "book", "books") returns "5 books".
2809static std::string FormatCountableNoun(int count,
2810                                       const char * singular_form,
2811                                       const char * plural_form) {
2812  return internal::StreamableToString(count) + " " +
2813      (count == 1 ? singular_form : plural_form);
2814}
2815
2816// Formats the count of tests.
2817static std::string FormatTestCount(int test_count) {
2818  return FormatCountableNoun(test_count, "test", "tests");
2819}
2820
2821// Formats the count of test cases.
2822static std::string FormatTestCaseCount(int test_case_count) {
2823  return FormatCountableNoun(test_case_count, "test case", "test cases");
2824}
2825
2826// Converts a TestPartResult::Type enum to human-friendly string
2827// representation.  Both kNonFatalFailure and kFatalFailure are translated
2828// to "Failure", as the user usually doesn't care about the difference
2829// between the two when viewing the test result.
2830static const char * TestPartResultTypeToString(TestPartResult::Type type) {
2831  switch (type) {
2832    case TestPartResult::kSuccess:
2833      return "Success";
2834
2835    case TestPartResult::kNonFatalFailure:
2836    case TestPartResult::kFatalFailure:
2837#ifdef _MSC_VER
2838      return "error: ";
2839#else
2840      return "Failure\n";
2841#endif
2842    default:
2843      return "Unknown result type";
2844  }
2845}
2846
2847namespace internal {
2848
2849// Prints a TestPartResult to an std::string.
2850static std::string PrintTestPartResultToString(
2851    const TestPartResult& test_part_result) {
2852  return (Message()
2853          << internal::FormatFileLocation(test_part_result.file_name(),
2854                                          test_part_result.line_number())
2855          << " " << TestPartResultTypeToString(test_part_result.type())
2856          << test_part_result.message()).GetString();
2857}
2858
2859// Prints a TestPartResult.
2860static void PrintTestPartResult(const TestPartResult& test_part_result) {
2861  const std::string& result =
2862      PrintTestPartResultToString(test_part_result);
2863  printf("%s\n", result.c_str());
2864  fflush(stdout);
2865  // If the test program runs in Visual Studio or a debugger, the
2866  // following statements add the test part result message to the Output
2867  // window such that the user can double-click on it to jump to the
2868  // corresponding source code location; otherwise they do nothing.
2869#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
2870  // We don't call OutputDebugString*() on Windows Mobile, as printing
2871  // to stdout is done by OutputDebugString() there already - we don't
2872  // want the same message printed twice.
2873  ::OutputDebugStringA(result.c_str());
2874  ::OutputDebugStringA("\n");
2875#endif
2876}
2877
2878// class PrettyUnitTestResultPrinter
2879
2880enum GTestColor {
2881  COLOR_DEFAULT,
2882  COLOR_RED,
2883  COLOR_GREEN,
2884  COLOR_YELLOW
2885};
2886
2887#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \
2888    !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
2889
2890// Returns the character attribute for the given color.
2891WORD GetColorAttribute(GTestColor color) {
2892  switch (color) {
2893    case COLOR_RED:    return FOREGROUND_RED;
2894    case COLOR_GREEN:  return FOREGROUND_GREEN;
2895    case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
2896    default:           return 0;
2897  }
2898}
2899
2900#else
2901
2902// Returns the ANSI color code for the given color.  COLOR_DEFAULT is
2903// an invalid input.
2904const char* GetAnsiColorCode(GTestColor color) {
2905  switch (color) {
2906    case COLOR_RED:     return "1";
2907    case COLOR_GREEN:   return "2";
2908    case COLOR_YELLOW:  return "3";
2909    default:            return NULL;
2910  };
2911}
2912
2913#endif  // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
2914
2915// Returns true iff Google Test should use colors in the output.
2916bool ShouldUseColor(bool stdout_is_tty) {
2917  const char* const gtest_color = GTEST_FLAG(color).c_str();
2918
2919  if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
2920#if GTEST_OS_WINDOWS
2921    // On Windows the TERM variable is usually not set, but the
2922    // console there does support colors.
2923    return stdout_is_tty;
2924#else
2925    // On non-Windows platforms, we rely on the TERM variable.
2926    const char* const term = posix::GetEnv("TERM");
2927    const bool term_supports_color =
2928        String::CStringEquals(term, "xterm") ||
2929        String::CStringEquals(term, "xterm-color") ||
2930        String::CStringEquals(term, "xterm-256color") ||
2931        String::CStringEquals(term, "screen") ||
2932        String::CStringEquals(term, "screen-256color") ||
2933        String::CStringEquals(term, "rxvt-unicode") ||
2934        String::CStringEquals(term, "rxvt-unicode-256color") ||
2935        String::CStringEquals(term, "linux") ||
2936        String::CStringEquals(term, "cygwin");
2937    return stdout_is_tty && term_supports_color;
2938#endif  // GTEST_OS_WINDOWS
2939  }
2940
2941  return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
2942      String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
2943      String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
2944      String::CStringEquals(gtest_color, "1");
2945  // We take "yes", "true", "t", and "1" as meaning "yes".  If the
2946  // value is neither one of these nor "auto", we treat it as "no" to
2947  // be conservative.
2948}
2949
2950// Helpers for printing colored strings to stdout. Note that on Windows, we
2951// cannot simply emit special characters and have the terminal change colors.
2952// This routine must actually emit the characters rather than return a string
2953// that would be colored when printed, as can be done on Linux.
2954void ColoredPrintf(GTestColor color, const char* fmt, ...) {
2955  va_list args;
2956  va_start(args, fmt);
2957
2958#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS || \
2959    GTEST_OS_IOS || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT
2960  const bool use_color = AlwaysFalse();
2961#else
2962  static const bool in_color_mode =
2963      ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
2964  const bool use_color = in_color_mode && (color != COLOR_DEFAULT);
2965#endif  // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
2966  // The '!= 0' comparison is necessary to satisfy MSVC 7.1.
2967
2968  if (!use_color) {
2969    vprintf(fmt, args);
2970    va_end(args);
2971    return;
2972  }
2973
2974#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \
2975    !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
2976  const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
2977
2978  // Gets the current text color.
2979  CONSOLE_SCREEN_BUFFER_INFO buffer_info;
2980  GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
2981  const WORD old_color_attrs = buffer_info.wAttributes;
2982
2983  // We need to flush the stream buffers into the console before each
2984  // SetConsoleTextAttribute call lest it affect the text that is already
2985  // printed but has not yet reached the console.
2986  fflush(stdout);
2987  SetConsoleTextAttribute(stdout_handle,
2988                          GetColorAttribute(color) | FOREGROUND_INTENSITY);
2989  vprintf(fmt, args);
2990
2991  fflush(stdout);
2992  // Restores the text color.
2993  SetConsoleTextAttribute(stdout_handle, old_color_attrs);
2994#else
2995  printf("\033[0;3%sm", GetAnsiColorCode(color));
2996  vprintf(fmt, args);
2997  printf("\033[m");  // Resets the terminal to default.
2998#endif  // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
2999  va_end(args);
3000}
3001
3002// Text printed in Google Test's text output and --gunit_list_tests
3003// output to label the type parameter and value parameter for a test.
3004static const char kTypeParamLabel[] = "TypeParam";
3005static const char kValueParamLabel[] = "GetParam()";
3006
3007void PrintFullTestCommentIfPresent(const TestInfo& test_info) {
3008  const char* const type_param = test_info.type_param();
3009  const char* const value_param = test_info.value_param();
3010
3011  if (type_param != NULL || value_param != NULL) {
3012    printf(", where ");
3013    if (type_param != NULL) {
3014      printf("%s = %s", kTypeParamLabel, type_param);
3015      if (value_param != NULL)
3016        printf(" and ");
3017    }
3018    if (value_param != NULL) {
3019      printf("%s = %s", kValueParamLabel, value_param);
3020    }
3021  }
3022}
3023
3024// This class implements the TestEventListener interface.
3025//
3026// Class PrettyUnitTestResultPrinter is copyable.
3027class PrettyUnitTestResultPrinter : public TestEventListener {
3028 public:
3029  PrettyUnitTestResultPrinter() {}
3030  static void PrintTestName(const char * test_case, const char * test) {
3031    printf("%s.%s", test_case, test);
3032  }
3033
3034  // The following methods override what's in the TestEventListener class.
3035  virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {}
3036  virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
3037  virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
3038  virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {}
3039  virtual void OnTestCaseStart(const TestCase& test_case);
3040  virtual void OnTestStart(const TestInfo& test_info);
3041  virtual void OnTestPartResult(const TestPartResult& result);
3042  virtual void OnTestEnd(const TestInfo& test_info);
3043  virtual void OnTestCaseEnd(const TestCase& test_case);
3044  virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
3045  virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {}
3046  virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
3047  virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {}
3048
3049 private:
3050  static void PrintFailedTests(const UnitTest& unit_test);
3051};
3052
3053  // Fired before each iteration of tests starts.
3054void PrettyUnitTestResultPrinter::OnTestIterationStart(
3055    const UnitTest& unit_test, int iteration) {
3056  if (GTEST_FLAG(repeat) != 1)
3057    printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
3058
3059  const char* const filter = GTEST_FLAG(filter).c_str();
3060
3061  // Prints the filter if it's not *.  This reminds the user that some
3062  // tests may be skipped.
3063  if (!String::CStringEquals(filter, kUniversalFilter)) {
3064    ColoredPrintf(COLOR_YELLOW,
3065                  "Note: %s filter = %s\n", GTEST_NAME_, filter);
3066  }
3067
3068  if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
3069    const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
3070    ColoredPrintf(COLOR_YELLOW,
3071                  "Note: This is test shard %d of %s.\n",
3072                  static_cast<int>(shard_index) + 1,
3073                  internal::posix::GetEnv(kTestTotalShards));
3074  }
3075
3076  if (GTEST_FLAG(shuffle)) {
3077    ColoredPrintf(COLOR_YELLOW,
3078                  "Note: Randomizing tests' orders with a seed of %d .\n",
3079                  unit_test.random_seed());
3080  }
3081
3082  ColoredPrintf(COLOR_GREEN,  "[==========] ");
3083  printf("Running %s from %s.\n",
3084         FormatTestCount(unit_test.test_to_run_count()).c_str(),
3085         FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
3086  fflush(stdout);
3087}
3088
3089void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
3090    const UnitTest& /*unit_test*/) {
3091  ColoredPrintf(COLOR_GREEN,  "[----------] ");
3092  printf("Global test environment set-up.\n");
3093  fflush(stdout);
3094}
3095
3096void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {
3097  const std::string counts =
3098      FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
3099  ColoredPrintf(COLOR_GREEN, "[----------] ");
3100  printf("%s from %s", counts.c_str(), test_case.name());
3101  if (test_case.type_param() == NULL) {
3102    printf("\n");
3103  } else {
3104    printf(", where %s = %s\n", kTypeParamLabel, test_case.type_param());
3105  }
3106  fflush(stdout);
3107}
3108
3109void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
3110  ColoredPrintf(COLOR_GREEN,  "[ RUN      ] ");
3111  PrintTestName(test_info.test_case_name(), test_info.name());
3112  printf("\n");
3113  fflush(stdout);
3114}
3115
3116// Called after an assertion failure.
3117void PrettyUnitTestResultPrinter::OnTestPartResult(
3118    const TestPartResult& result) {
3119  // If the test part succeeded, we don't need to do anything.
3120  if (result.type() == TestPartResult::kSuccess)
3121    return;
3122
3123  // Print failure message from the assertion (e.g. expected this and got that).
3124  PrintTestPartResult(result);
3125  fflush(stdout);
3126}
3127
3128void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
3129  if (test_info.result()->Passed()) {
3130    ColoredPrintf(COLOR_GREEN, "[       OK ] ");
3131  } else {
3132    ColoredPrintf(COLOR_RED, "[  FAILED  ] ");
3133  }
3134  PrintTestName(test_info.test_case_name(), test_info.name());
3135  if (test_info.result()->Failed())
3136    PrintFullTestCommentIfPresent(test_info);
3137
3138  if (GTEST_FLAG(print_time)) {
3139    printf(" (%s ms)\n", internal::StreamableToString(
3140           test_info.result()->elapsed_time()).c_str());
3141  } else {
3142    printf("\n");
3143  }
3144  fflush(stdout);
3145}
3146
3147void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {
3148  if (!GTEST_FLAG(print_time)) return;
3149
3150  const std::string counts =
3151      FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
3152  ColoredPrintf(COLOR_GREEN, "[----------] ");
3153  printf("%s from %s (%s ms total)\n\n",
3154         counts.c_str(), test_case.name(),
3155         internal::StreamableToString(test_case.elapsed_time()).c_str());
3156  fflush(stdout);
3157}
3158
3159void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
3160    const UnitTest& /*unit_test*/) {
3161  ColoredPrintf(COLOR_GREEN,  "[----------] ");
3162  printf("Global test environment tear-down\n");
3163  fflush(stdout);
3164}
3165
3166// Internal helper for printing the list of failed tests.
3167void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
3168  const int failed_test_count = unit_test.failed_test_count();
3169  if (failed_test_count == 0) {
3170    return;
3171  }
3172
3173  for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
3174    const TestCase& test_case = *unit_test.GetTestCase(i);
3175    if (!test_case.should_run() || (test_case.failed_test_count() == 0)) {
3176      continue;
3177    }
3178    for (int j = 0; j < test_case.total_test_count(); ++j) {
3179      const TestInfo& test_info = *test_case.GetTestInfo(j);
3180      if (!test_info.should_run() || test_info.result()->Passed()) {
3181        continue;
3182      }
3183      ColoredPrintf(COLOR_RED, "[  FAILED  ] ");
3184      printf("%s.%s", test_case.name(), test_info.name());
3185      PrintFullTestCommentIfPresent(test_info);
3186      printf("\n");
3187    }
3188  }
3189}
3190
3191void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
3192                                                     int /*iteration*/) {
3193  ColoredPrintf(COLOR_GREEN,  "[==========] ");
3194  printf("%s from %s ran.",
3195         FormatTestCount(unit_test.test_to_run_count()).c_str(),
3196         FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
3197  if (GTEST_FLAG(print_time)) {
3198    printf(" (%s ms total)",
3199           internal::StreamableToString(unit_test.elapsed_time()).c_str());
3200  }
3201  printf("\n");
3202  ColoredPrintf(COLOR_GREEN,  "[  PASSED  ] ");
3203  printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
3204
3205  int num_failures = unit_test.failed_test_count();
3206  if (!unit_test.Passed()) {
3207    const int failed_test_count = unit_test.failed_test_count();
3208    ColoredPrintf(COLOR_RED,  "[  FAILED  ] ");
3209    printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
3210    PrintFailedTests(unit_test);
3211    printf("\n%2d FAILED %s\n", num_failures,
3212                        num_failures == 1 ? "TEST" : "TESTS");
3213  }
3214
3215  int num_disabled = unit_test.reportable_disabled_test_count();
3216  if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
3217    if (!num_failures) {
3218      printf("\n");  // Add a spacer if no FAILURE banner is displayed.
3219    }
3220    ColoredPrintf(COLOR_YELLOW,
3221                  "  YOU HAVE %d DISABLED %s\n\n",
3222                  num_disabled,
3223                  num_disabled == 1 ? "TEST" : "TESTS");
3224  }
3225  // Ensure that Google Test output is printed before, e.g., heapchecker output.
3226  fflush(stdout);
3227}
3228
3229// End PrettyUnitTestResultPrinter
3230
3231// class TestEventRepeater
3232//
3233// This class forwards events to other event listeners.
3234class TestEventRepeater : public TestEventListener {
3235 public:
3236  TestEventRepeater() : forwarding_enabled_(true) {}
3237  virtual ~TestEventRepeater();
3238  void Append(TestEventListener *listener);
3239  TestEventListener* Release(TestEventListener* listener);
3240
3241  // Controls whether events will be forwarded to listeners_. Set to false
3242  // in death test child processes.
3243  bool forwarding_enabled() const { return forwarding_enabled_; }
3244  void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }
3245
3246  virtual void OnTestProgramStart(const UnitTest& unit_test);
3247  virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
3248  virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
3249  virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test);
3250  virtual void OnTestCaseStart(const TestCase& test_case);
3251  virtual void OnTestStart(const TestInfo& test_info);
3252  virtual void OnTestPartResult(const TestPartResult& result);
3253  virtual void OnTestEnd(const TestInfo& test_info);
3254  virtual void OnTestCaseEnd(const TestCase& test_case);
3255  virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
3256  virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test);
3257  virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
3258  virtual void OnTestProgramEnd(const UnitTest& unit_test);
3259
3260 private:
3261  // Controls whether events will be forwarded to listeners_. Set to false
3262  // in death test child processes.
3263  bool forwarding_enabled_;
3264  // The list of listeners that receive events.
3265  std::vector<TestEventListener*> listeners_;
3266
3267  GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater);
3268};
3269
3270TestEventRepeater::~TestEventRepeater() {
3271  ForEach(listeners_, Delete<TestEventListener>);
3272}
3273
3274void TestEventRepeater::Append(TestEventListener *listener) {
3275  listeners_.push_back(listener);
3276}
3277
3278// TODO(vladl@google.com): Factor the search functionality into Vector::Find.
3279TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {
3280  for (size_t i = 0; i < listeners_.size(); ++i) {
3281    if (listeners_[i] == listener) {
3282      listeners_.erase(listeners_.begin() + i);
3283      return listener;
3284    }
3285  }
3286
3287  return NULL;
3288}
3289
3290// Since most methods are very similar, use macros to reduce boilerplate.
3291// This defines a member that forwards the call to all listeners.
3292#define GTEST_REPEATER_METHOD_(Name, Type) \
3293void TestEventRepeater::Name(const Type& parameter) { \
3294  if (forwarding_enabled_) { \
3295    for (size_t i = 0; i < listeners_.size(); i++) { \
3296      listeners_[i]->Name(parameter); \
3297    } \
3298  } \
3299}
3300// This defines a member that forwards the call to all listeners in reverse
3301// order.
3302#define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
3303void TestEventRepeater::Name(const Type& parameter) { \
3304  if (forwarding_enabled_) { \
3305    for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \
3306      listeners_[i]->Name(parameter); \
3307    } \
3308  } \
3309}
3310
3311GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)
3312GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)
3313GTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase)
3314GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
3315GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)
3316GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)
3317GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)
3318GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)
3319GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)
3320GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestCase)
3321GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)
3322
3323#undef GTEST_REPEATER_METHOD_
3324#undef GTEST_REVERSE_REPEATER_METHOD_
3325
3326void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,
3327                                             int iteration) {
3328  if (forwarding_enabled_) {
3329    for (size_t i = 0; i < listeners_.size(); i++) {
3330      listeners_[i]->OnTestIterationStart(unit_test, iteration);
3331    }
3332  }
3333}
3334
3335void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,
3336                                           int iteration) {
3337  if (forwarding_enabled_) {
3338    for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) {
3339      listeners_[i]->OnTestIterationEnd(unit_test, iteration);
3340    }
3341  }
3342}
3343
3344// End TestEventRepeater
3345
3346// This class generates an XML output file.
3347class XmlUnitTestResultPrinter : public EmptyTestEventListener {
3348 public:
3349  explicit XmlUnitTestResultPrinter(const char* output_file);
3350
3351  virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
3352
3353 private:
3354  // Is c a whitespace character that is normalized to a space character
3355  // when it appears in an XML attribute value?
3356  static bool IsNormalizableWhitespace(char c) {
3357    return c == 0x9 || c == 0xA || c == 0xD;
3358  }
3359
3360  // May c appear in a well-formed XML document?
3361  static bool IsValidXmlCharacter(char c) {
3362    return IsNormalizableWhitespace(c) || c >= 0x20;
3363  }
3364
3365  // Returns an XML-escaped copy of the input string str.  If
3366  // is_attribute is true, the text is meant to appear as an attribute
3367  // value, and normalizable whitespace is preserved by replacing it
3368  // with character references.
3369  static std::string EscapeXml(const std::string& str, bool is_attribute);
3370
3371  // Returns the given string with all characters invalid in XML removed.
3372  static std::string RemoveInvalidXmlCharacters(const std::string& str);
3373
3374  // Convenience wrapper around EscapeXml when str is an attribute value.
3375  static std::string EscapeXmlAttribute(const std::string& str) {
3376    return EscapeXml(str, true);
3377  }
3378
3379  // Convenience wrapper around EscapeXml when str is not an attribute value.
3380  static std::string EscapeXmlText(const char* str) {
3381    return EscapeXml(str, false);
3382  }
3383
3384  // Verifies that the given attribute belongs to the given element and
3385  // streams the attribute as XML.
3386  static void OutputXmlAttribute(std::ostream* stream,
3387                                 const std::string& element_name,
3388                                 const std::string& name,
3389                                 const std::string& value);
3390
3391  // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
3392  static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
3393
3394  // Streams an XML representation of a TestInfo object.
3395  static void OutputXmlTestInfo(::std::ostream* stream,
3396                                const char* test_case_name,
3397                                const TestInfo& test_info);
3398
3399  // Prints an XML representation of a TestCase object
3400  static void PrintXmlTestCase(::std::ostream* stream,
3401                               const TestCase& test_case);
3402
3403  // Prints an XML summary of unit_test to output stream out.
3404  static void PrintXmlUnitTest(::std::ostream* stream,
3405                               const UnitTest& unit_test);
3406
3407  // Produces a string representing the test properties in a result as space
3408  // delimited XML attributes based on the property key="value" pairs.
3409  // When the std::string is not empty, it includes a space at the beginning,
3410  // to delimit this attribute from prior attributes.
3411  static std::string TestPropertiesAsXmlAttributes(const TestResult& result);
3412
3413  // The output file.
3414  const std::string output_file_;
3415
3416  GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);
3417};
3418
3419// Creates a new XmlUnitTestResultPrinter.
3420XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
3421    : output_file_(output_file) {
3422  if (output_file_.c_str() == NULL || output_file_.empty()) {
3423    fprintf(stderr, "XML output file may not be null\n");
3424    fflush(stderr);
3425    exit(EXIT_FAILURE);
3426  }
3427}
3428
3429// Called after the unit test ends.
3430void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
3431                                                  int /*iteration*/) {
3432  FILE* xmlout = NULL;
3433  FilePath output_file(output_file_);
3434  FilePath output_dir(output_file.RemoveFileName());
3435
3436  if (output_dir.CreateDirectoriesRecursively()) {
3437    xmlout = posix::FOpen(output_file_.c_str(), "w");
3438  }
3439  if (xmlout == NULL) {
3440    // TODO(wan): report the reason of the failure.
3441    //
3442    // We don't do it for now as:
3443    //
3444    //   1. There is no urgent need for it.
3445    //   2. It's a bit involved to make the errno variable thread-safe on
3446    //      all three operating systems (Linux, Windows, and Mac OS).
3447    //   3. To interpret the meaning of errno in a thread-safe way,
3448    //      we need the strerror_r() function, which is not available on
3449    //      Windows.
3450    fprintf(stderr,
3451            "Unable to open file \"%s\"\n",
3452            output_file_.c_str());
3453    fflush(stderr);
3454    exit(EXIT_FAILURE);
3455  }
3456  std::stringstream stream;
3457  PrintXmlUnitTest(&stream, unit_test);
3458  fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
3459  fclose(xmlout);
3460}
3461
3462// Returns an XML-escaped copy of the input string str.  If is_attribute
3463// is true, the text is meant to appear as an attribute value, and
3464// normalizable whitespace is preserved by replacing it with character
3465// references.
3466//
3467// Invalid XML characters in str, if any, are stripped from the output.
3468// It is expected that most, if not all, of the text processed by this
3469// module will consist of ordinary English text.
3470// If this module is ever modified to produce version 1.1 XML output,
3471// most invalid characters can be retained using character references.
3472// TODO(wan): It might be nice to have a minimally invasive, human-readable
3473// escaping scheme for invalid characters, rather than dropping them.
3474std::string XmlUnitTestResultPrinter::EscapeXml(
3475    const std::string& str, bool is_attribute) {
3476  Message m;
3477
3478  for (size_t i = 0; i < str.size(); ++i) {
3479    const char ch = str[i];
3480    switch (ch) {
3481      case '<':
3482        m << "&lt;";
3483        break;
3484      case '>':
3485        m << "&gt;";
3486        break;
3487      case '&':
3488        m << "&amp;";
3489        break;
3490      case '\'':
3491        if (is_attribute)
3492          m << "&apos;";
3493        else
3494          m << '\'';
3495        break;
3496      case '"':
3497        if (is_attribute)
3498          m << "&quot;";
3499        else
3500          m << '"';
3501        break;
3502      default:
3503        if (IsValidXmlCharacter(ch)) {
3504          if (is_attribute && IsNormalizableWhitespace(ch))
3505            m << "&#x" << String::FormatByte(static_cast<unsigned char>(ch))
3506              << ";";
3507          else
3508            m << ch;
3509        }
3510        break;
3511    }
3512  }
3513
3514  return m.GetString();
3515}
3516
3517// Returns the given string with all characters invalid in XML removed.
3518// Currently invalid characters are dropped from the string. An
3519// alternative is to replace them with certain characters such as . or ?.
3520std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(
3521    const std::string& str) {
3522  std::string output;
3523  output.reserve(str.size());
3524  for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
3525    if (IsValidXmlCharacter(*it))
3526      output.push_back(*it);
3527
3528  return output;
3529}
3530
3531// The following routines generate an XML representation of a UnitTest
3532// object.
3533//
3534// This is how Google Test concepts map to the DTD:
3535//
3536// <testsuites name="AllTests">        <-- corresponds to a UnitTest object
3537//   <testsuite name="testcase-name">  <-- corresponds to a TestCase object
3538//     <testcase name="test-name">     <-- corresponds to a TestInfo object
3539//       <failure message="...">...</failure>
3540//       <failure message="...">...</failure>
3541//       <failure message="...">...</failure>
3542//                                     <-- individual assertion failures
3543//     </testcase>
3544//   </testsuite>
3545// </testsuites>
3546
3547// Formats the given time in milliseconds as seconds.
3548std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {
3549  ::std::stringstream ss;
3550  ss << (static_cast<double>(ms) * 1e-3);
3551  return ss.str();
3552}
3553
3554static bool PortableLocaltime(time_t seconds, struct tm* out) {
3555#if defined(_MSC_VER)
3556  return localtime_s(out, &seconds) == 0;
3557#elif defined(__MINGW32__) || defined(__MINGW64__)
3558  // MINGW <time.h> provides neither localtime_r nor localtime_s, but uses
3559  // Windows' localtime(), which has a thread-local tm buffer.
3560  struct tm* tm_ptr = localtime(&seconds);  // NOLINT
3561  if (tm_ptr == NULL)
3562    return false;
3563  *out = *tm_ptr;
3564  return true;
3565#else
3566  return localtime_r(&seconds, out) != NULL;
3567#endif
3568}
3569
3570// Converts the given epoch time in milliseconds to a date string in the ISO
3571// 8601 format, without the timezone information.
3572std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) {
3573  struct tm time_struct;
3574  if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))
3575    return "";
3576  // YYYY-MM-DDThh:mm:ss
3577  return StreamableToString(time_struct.tm_year + 1900) + "-" +
3578      String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +
3579      String::FormatIntWidth2(time_struct.tm_mday) + "T" +
3580      String::FormatIntWidth2(time_struct.tm_hour) + ":" +
3581      String::FormatIntWidth2(time_struct.tm_min) + ":" +
3582      String::FormatIntWidth2(time_struct.tm_sec);
3583}
3584
3585// Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
3586void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
3587                                                     const char* data) {
3588  const char* segment = data;
3589  *stream << "<![CDATA[";
3590  for (;;) {
3591    const char* const next_segment = strstr(segment, "]]>");
3592    if (next_segment != NULL) {
3593      stream->write(
3594          segment, static_cast<std::streamsize>(next_segment - segment));
3595      *stream << "]]>]]&gt;<![CDATA[";
3596      segment = next_segment + strlen("]]>");
3597    } else {
3598      *stream << segment;
3599      break;
3600    }
3601  }
3602  *stream << "]]>";
3603}
3604
3605void XmlUnitTestResultPrinter::OutputXmlAttribute(
3606    std::ostream* stream,
3607    const std::string& element_name,
3608    const std::string& name,
3609    const std::string& value) {
3610  const std::vector<std::string>& allowed_names =
3611      GetReservedAttributesForElement(element_name);
3612
3613  GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
3614                   allowed_names.end())
3615      << "Attribute " << name << " is not allowed for element <" << element_name
3616      << ">.";
3617
3618  *stream << " " << name << "=\"" << EscapeXmlAttribute(value) << "\"";
3619}
3620
3621// Prints an XML representation of a TestInfo object.
3622// TODO(wan): There is also value in printing properties with the plain printer.
3623void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
3624                                                 const char* test_case_name,
3625                                                 const TestInfo& test_info) {
3626  const TestResult& result = *test_info.result();
3627  const std::string kTestcase = "testcase";
3628
3629  *stream << "    <testcase";
3630  OutputXmlAttribute(stream, kTestcase, "name", test_info.name());
3631
3632  if (test_info.value_param() != NULL) {
3633    OutputXmlAttribute(stream, kTestcase, "value_param",
3634                       test_info.value_param());
3635  }
3636  if (test_info.type_param() != NULL) {
3637    OutputXmlAttribute(stream, kTestcase, "type_param", test_info.type_param());
3638  }
3639
3640  OutputXmlAttribute(stream, kTestcase, "status",
3641                     test_info.should_run() ? "run" : "notrun");
3642  OutputXmlAttribute(stream, kTestcase, "time",
3643                     FormatTimeInMillisAsSeconds(result.elapsed_time()));
3644  OutputXmlAttribute(stream, kTestcase, "classname", test_case_name);
3645  *stream << TestPropertiesAsXmlAttributes(result);
3646
3647  int failures = 0;
3648  for (int i = 0; i < result.total_part_count(); ++i) {
3649    const TestPartResult& part = result.GetTestPartResult(i);
3650    if (part.failed()) {
3651      if (++failures == 1) {
3652        *stream << ">\n";
3653      }
3654      const string location = internal::FormatCompilerIndependentFileLocation(
3655          part.file_name(), part.line_number());
3656      const string summary = location + "\n" + part.summary();
3657      *stream << "      <failure message=\""
3658              << EscapeXmlAttribute(summary.c_str())
3659              << "\" type=\"\">";
3660      const string detail = location + "\n" + part.message();
3661      OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
3662      *stream << "</failure>\n";
3663    }
3664  }
3665
3666  if (failures == 0)
3667    *stream << " />\n";
3668  else
3669    *stream << "    </testcase>\n";
3670}
3671
3672// Prints an XML representation of a TestCase object
3673void XmlUnitTestResultPrinter::PrintXmlTestCase(std::ostream* stream,
3674                                                const TestCase& test_case) {
3675  const std::string kTestsuite = "testsuite";
3676  *stream << "  <" << kTestsuite;
3677  OutputXmlAttribute(stream, kTestsuite, "name", test_case.name());
3678  OutputXmlAttribute(stream, kTestsuite, "tests",
3679                     StreamableToString(test_case.reportable_test_count()));
3680  OutputXmlAttribute(stream, kTestsuite, "failures",
3681                     StreamableToString(test_case.failed_test_count()));
3682  OutputXmlAttribute(
3683      stream, kTestsuite, "disabled",
3684      StreamableToString(test_case.reportable_disabled_test_count()));
3685  OutputXmlAttribute(stream, kTestsuite, "errors", "0");
3686  OutputXmlAttribute(stream, kTestsuite, "time",
3687                     FormatTimeInMillisAsSeconds(test_case.elapsed_time()));
3688  *stream << TestPropertiesAsXmlAttributes(test_case.ad_hoc_test_result())
3689          << ">\n";
3690
3691  for (int i = 0; i < test_case.total_test_count(); ++i) {
3692    if (test_case.GetTestInfo(i)->is_reportable())
3693      OutputXmlTestInfo(stream, test_case.name(), *test_case.GetTestInfo(i));
3694  }
3695  *stream << "  </" << kTestsuite << ">\n";
3696}
3697
3698// Prints an XML summary of unit_test to output stream out.
3699void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream,
3700                                                const UnitTest& unit_test) {
3701  const std::string kTestsuites = "testsuites";
3702
3703  *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
3704  *stream << "<" << kTestsuites;
3705
3706  OutputXmlAttribute(stream, kTestsuites, "tests",
3707                     StreamableToString(unit_test.reportable_test_count()));
3708  OutputXmlAttribute(stream, kTestsuites, "failures",
3709                     StreamableToString(unit_test.failed_test_count()));
3710  OutputXmlAttribute(
3711      stream, kTestsuites, "disabled",
3712      StreamableToString(unit_test.reportable_disabled_test_count()));
3713  OutputXmlAttribute(stream, kTestsuites, "errors", "0");
3714  OutputXmlAttribute(
3715      stream, kTestsuites, "timestamp",
3716      FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp()));
3717  OutputXmlAttribute(stream, kTestsuites, "time",
3718                     FormatTimeInMillisAsSeconds(unit_test.elapsed_time()));
3719
3720  if (GTEST_FLAG(shuffle)) {
3721    OutputXmlAttribute(stream, kTestsuites, "random_seed",
3722                       StreamableToString(unit_test.random_seed()));
3723  }
3724
3725  *stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result());
3726
3727  OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
3728  *stream << ">\n";
3729
3730  for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
3731    if (unit_test.GetTestCase(i)->reportable_test_count() > 0)
3732      PrintXmlTestCase(stream, *unit_test.GetTestCase(i));
3733  }
3734  *stream << "</" << kTestsuites << ">\n";
3735}
3736
3737// Produces a string representing the test properties in a result as space
3738// delimited XML attributes based on the property key="value" pairs.
3739std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
3740    const TestResult& result) {
3741  Message attributes;
3742  for (int i = 0; i < result.test_property_count(); ++i) {
3743    const TestProperty& property = result.GetTestProperty(i);
3744    attributes << " " << property.key() << "="
3745        << "\"" << EscapeXmlAttribute(property.value()) << "\"";
3746  }
3747  return attributes.GetString();
3748}
3749
3750// End XmlUnitTestResultPrinter
3751
3752#if GTEST_CAN_STREAM_RESULTS_
3753
3754// Checks if str contains '=', '&', '%' or '\n' characters. If yes,
3755// replaces them by "%xx" where xx is their hexadecimal value. For
3756// example, replaces "=" with "%3D".  This algorithm is O(strlen(str))
3757// in both time and space -- important as the input str may contain an
3758// arbitrarily long test failure message and stack trace.
3759string StreamingListener::UrlEncode(const char* str) {
3760  string result;
3761  result.reserve(strlen(str) + 1);
3762  for (char ch = *str; ch != '\0'; ch = *++str) {
3763    switch (ch) {
3764      case '%':
3765      case '=':
3766      case '&':
3767      case '\n':
3768        result.append("%" + String::FormatByte(static_cast<unsigned char>(ch)));
3769        break;
3770      default:
3771        result.push_back(ch);
3772        break;
3773    }
3774  }
3775  return result;
3776}
3777
3778void StreamingListener::SocketWriter::MakeConnection() {
3779  GTEST_CHECK_(sockfd_ == -1)
3780      << "MakeConnection() can't be called when there is already a connection.";
3781
3782  addrinfo hints;
3783  memset(&hints, 0, sizeof(hints));
3784  hints.ai_family = AF_UNSPEC;    // To allow both IPv4 and IPv6 addresses.
3785  hints.ai_socktype = SOCK_STREAM;
3786  addrinfo* servinfo = NULL;
3787
3788  // Use the getaddrinfo() to get a linked list of IP addresses for
3789  // the given host name.
3790  const int error_num = getaddrinfo(
3791      host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
3792  if (error_num != 0) {
3793    GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: "
3794                        << gai_strerror(error_num);
3795  }
3796
3797  // Loop through all the results and connect to the first we can.
3798  for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != NULL;
3799       cur_addr = cur_addr->ai_next) {
3800    sockfd_ = socket(
3801        cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol);
3802    if (sockfd_ != -1) {
3803      // Connect the client socket to the server socket.
3804      if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
3805        close(sockfd_);
3806        sockfd_ = -1;
3807      }
3808    }
3809  }
3810
3811  freeaddrinfo(servinfo);  // all done with this structure
3812
3813  if (sockfd_ == -1) {
3814    GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to "
3815                        << host_name_ << ":" << port_num_;
3816  }
3817}
3818
3819// End of class Streaming Listener
3820#endif  // GTEST_CAN_STREAM_RESULTS__
3821
3822// Class ScopedTrace
3823
3824// Pushes the given source file location and message onto a per-thread
3825// trace stack maintained by Google Test.
3826ScopedTrace::ScopedTrace(const char* file, int line, const Message& message)
3827    GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
3828  TraceInfo trace;
3829  trace.file = file;
3830  trace.line = line;
3831  trace.message = message.GetString();
3832
3833  UnitTest::GetInstance()->PushGTestTrace(trace);
3834}
3835
3836// Pops the info pushed by the c'tor.
3837ScopedTrace::~ScopedTrace()
3838    GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
3839  UnitTest::GetInstance()->PopGTestTrace();
3840}
3841
3842
3843// class OsStackTraceGetter
3844
3845const char* const OsStackTraceGetterInterface::kElidedFramesMarker =
3846    "... " GTEST_NAME_ " internal frames ...";
3847
3848string OsStackTraceGetter::CurrentStackTrace(int /*max_depth*/,
3849                                             int /*skip_count*/) {
3850  return "";
3851}
3852
3853void OsStackTraceGetter::UponLeavingGTest() {}
3854
3855// A helper class that creates the premature-exit file in its
3856// constructor and deletes the file in its destructor.
3857class ScopedPrematureExitFile {
3858 public:
3859  explicit ScopedPrematureExitFile(const char* premature_exit_filepath)
3860      : premature_exit_filepath_(premature_exit_filepath) {
3861    // If a path to the premature-exit file is specified...
3862    if (premature_exit_filepath != NULL && *premature_exit_filepath != '\0') {
3863      // create the file with a single "0" character in it.  I/O
3864      // errors are ignored as there's nothing better we can do and we
3865      // don't want to fail the test because of this.
3866      FILE* pfile = posix::FOpen(premature_exit_filepath, "w");
3867      fwrite("0", 1, 1, pfile);
3868      fclose(pfile);
3869    }
3870  }
3871
3872  ~ScopedPrematureExitFile() {
3873    if (premature_exit_filepath_ != NULL && *premature_exit_filepath_ != '\0') {
3874      remove(premature_exit_filepath_);
3875    }
3876  }
3877
3878 private:
3879  const char* const premature_exit_filepath_;
3880
3881  GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedPrematureExitFile);
3882};
3883
3884}  // namespace internal
3885
3886// class TestEventListeners
3887
3888TestEventListeners::TestEventListeners()
3889    : repeater_(new internal::TestEventRepeater()),
3890      default_result_printer_(NULL),
3891      default_xml_generator_(NULL) {
3892}
3893
3894TestEventListeners::~TestEventListeners() { delete repeater_; }
3895
3896// Returns the standard listener responsible for the default console
3897// output.  Can be removed from the listeners list to shut down default
3898// console output.  Note that removing this object from the listener list
3899// with Release transfers its ownership to the user.
3900void TestEventListeners::Append(TestEventListener* listener) {
3901  repeater_->Append(listener);
3902}
3903
3904// Removes the given event listener from the list and returns it.  It then
3905// becomes the caller's responsibility to delete the listener. Returns
3906// NULL if the listener is not found in the list.
3907TestEventListener* TestEventListeners::Release(TestEventListener* listener) {
3908  if (listener == default_result_printer_)
3909    default_result_printer_ = NULL;
3910  else if (listener == default_xml_generator_)
3911    default_xml_generator_ = NULL;
3912  return repeater_->Release(listener);
3913}
3914
3915// Returns repeater that broadcasts the TestEventListener events to all
3916// subscribers.
3917TestEventListener* TestEventListeners::repeater() { return repeater_; }
3918
3919// Sets the default_result_printer attribute to the provided listener.
3920// The listener is also added to the listener list and previous
3921// default_result_printer is removed from it and deleted. The listener can
3922// also be NULL in which case it will not be added to the list. Does
3923// nothing if the previous and the current listener objects are the same.
3924void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
3925  if (default_result_printer_ != listener) {
3926    // It is an error to pass this method a listener that is already in the
3927    // list.
3928    delete Release(default_result_printer_);
3929    default_result_printer_ = listener;
3930    if (listener != NULL)
3931      Append(listener);
3932  }
3933}
3934
3935// Sets the default_xml_generator attribute to the provided listener.  The
3936// listener is also added to the listener list and previous
3937// default_xml_generator is removed from it and deleted. The listener can
3938// also be NULL in which case it will not be added to the list. Does
3939// nothing if the previous and the current listener objects are the same.
3940void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
3941  if (default_xml_generator_ != listener) {
3942    // It is an error to pass this method a listener that is already in the
3943    // list.
3944    delete Release(default_xml_generator_);
3945    default_xml_generator_ = listener;
3946    if (listener != NULL)
3947      Append(listener);
3948  }
3949}
3950
3951// Controls whether events will be forwarded by the repeater to the
3952// listeners in the list.
3953bool TestEventListeners::EventForwardingEnabled() const {
3954  return repeater_->forwarding_enabled();
3955}
3956
3957void TestEventListeners::SuppressEventForwarding() {
3958  repeater_->set_forwarding_enabled(false);
3959}
3960
3961// class UnitTest
3962
3963// Gets the singleton UnitTest object.  The first time this method is
3964// called, a UnitTest object is constructed and returned.  Consecutive
3965// calls will return the same object.
3966//
3967// We don't protect this under mutex_ as a user is not supposed to
3968// call this before main() starts, from which point on the return
3969// value will never change.
3970UnitTest* UnitTest::GetInstance() {
3971  // When compiled with MSVC 7.1 in optimized mode, destroying the
3972  // UnitTest object upon exiting the program messes up the exit code,
3973  // causing successful tests to appear failed.  We have to use a
3974  // different implementation in this case to bypass the compiler bug.
3975  // This implementation makes the compiler happy, at the cost of
3976  // leaking the UnitTest object.
3977
3978  // CodeGear C++Builder insists on a public destructor for the
3979  // default implementation.  Use this implementation to keep good OO
3980  // design with private destructor.
3981
3982#if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
3983  static UnitTest* const instance = new UnitTest;
3984  return instance;
3985#else
3986  static UnitTest instance;
3987  return &instance;
3988#endif  // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
3989}
3990
3991// Gets the number of successful test cases.
3992int UnitTest::successful_test_case_count() const {
3993  return impl()->successful_test_case_count();
3994}
3995
3996// Gets the number of failed test cases.
3997int UnitTest::failed_test_case_count() const {
3998  return impl()->failed_test_case_count();
3999}
4000
4001// Gets the number of all test cases.
4002int UnitTest::total_test_case_count() const {
4003  return impl()->total_test_case_count();
4004}
4005
4006// Gets the number of all test cases that contain at least one test
4007// that should run.
4008int UnitTest::test_case_to_run_count() const {
4009  return impl()->test_case_to_run_count();
4010}
4011
4012// Gets the number of successful tests.
4013int UnitTest::successful_test_count() const {
4014  return impl()->successful_test_count();
4015}
4016
4017// Gets the number of failed tests.
4018int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
4019
4020// Gets the number of disabled tests that will be reported in the XML report.
4021int UnitTest::reportable_disabled_test_count() const {
4022  return impl()->reportable_disabled_test_count();
4023}
4024
4025// Gets the number of disabled tests.
4026int UnitTest::disabled_test_count() const {
4027  return impl()->disabled_test_count();
4028}
4029
4030// Gets the number of tests to be printed in the XML report.
4031int UnitTest::reportable_test_count() const {
4032  return impl()->reportable_test_count();
4033}
4034
4035// Gets the number of all tests.
4036int UnitTest::total_test_count() const { return impl()->total_test_count(); }
4037
4038// Gets the number of tests that should run.
4039int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
4040
4041// Gets the time of the test program start, in ms from the start of the
4042// UNIX epoch.
4043internal::TimeInMillis UnitTest::start_timestamp() const {
4044    return impl()->start_timestamp();
4045}
4046
4047// Gets the elapsed time, in milliseconds.
4048internal::TimeInMillis UnitTest::elapsed_time() const {
4049  return impl()->elapsed_time();
4050}
4051
4052// Returns true iff the unit test passed (i.e. all test cases passed).
4053bool UnitTest::Passed() const { return impl()->Passed(); }
4054
4055// Returns true iff the unit test failed (i.e. some test case failed
4056// or something outside of all tests failed).
4057bool UnitTest::Failed() const { return impl()->Failed(); }
4058
4059// Gets the i-th test case among all the test cases. i can range from 0 to
4060// total_test_case_count() - 1. If i is not in that range, returns NULL.
4061const TestCase* UnitTest::GetTestCase(int i) const {
4062  return impl()->GetTestCase(i);
4063}
4064
4065// Returns the TestResult containing information on test failures and
4066// properties logged outside of individual test cases.
4067const TestResult& UnitTest::ad_hoc_test_result() const {
4068  return *impl()->ad_hoc_test_result();
4069}
4070
4071// Gets the i-th test case among all the test cases. i can range from 0 to
4072// total_test_case_count() - 1. If i is not in that range, returns NULL.
4073TestCase* UnitTest::GetMutableTestCase(int i) {
4074  return impl()->GetMutableTestCase(i);
4075}
4076
4077// Returns the list of event listeners that can be used to track events
4078// inside Google Test.
4079TestEventListeners& UnitTest::listeners() {
4080  return *impl()->listeners();
4081}
4082
4083// Registers and returns a global test environment.  When a test
4084// program is run, all global test environments will be set-up in the
4085// order they were registered.  After all tests in the program have
4086// finished, all global test environments will be torn-down in the
4087// *reverse* order they were registered.
4088//
4089// The UnitTest object takes ownership of the given environment.
4090//
4091// We don't protect this under mutex_, as we only support calling it
4092// from the main thread.
4093Environment* UnitTest::AddEnvironment(Environment* env) {
4094  if (env == NULL) {
4095    return NULL;
4096  }
4097
4098  impl_->environments().push_back(env);
4099  return env;
4100}
4101
4102// Adds a TestPartResult to the current TestResult object.  All Google Test
4103// assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
4104// this to report their results.  The user code should use the
4105// assertion macros instead of calling this directly.
4106void UnitTest::AddTestPartResult(
4107    TestPartResult::Type result_type,
4108    const char* file_name,
4109    int line_number,
4110    const std::string& message,
4111    const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_) {
4112  Message msg;
4113  msg << message;
4114
4115  internal::MutexLock lock(&mutex_);
4116  if (impl_->gtest_trace_stack().size() > 0) {
4117    msg << "\n" << GTEST_NAME_ << " trace:";
4118
4119    for (int i = static_cast<int>(impl_->gtest_trace_stack().size());
4120         i > 0; --i) {
4121      const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
4122      msg << "\n" << internal::FormatFileLocation(trace.file, trace.line)
4123          << " " << trace.message;
4124    }
4125  }
4126
4127  if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) {
4128    msg << internal::kStackTraceMarker << os_stack_trace;
4129  }
4130
4131  const TestPartResult result =
4132    TestPartResult(result_type, file_name, line_number,
4133                   msg.GetString().c_str());
4134  impl_->GetTestPartResultReporterForCurrentThread()->
4135      ReportTestPartResult(result);
4136
4137  if (result_type != TestPartResult::kSuccess) {
4138    // gtest_break_on_failure takes precedence over
4139    // gtest_throw_on_failure.  This allows a user to set the latter
4140    // in the code (perhaps in order to use Google Test assertions
4141    // with another testing framework) and specify the former on the
4142    // command line for debugging.
4143    if (GTEST_FLAG(break_on_failure)) {
4144#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
4145      // Using DebugBreak on Windows allows gtest to still break into a debugger
4146      // when a failure happens and both the --gtest_break_on_failure and
4147      // the --gtest_catch_exceptions flags are specified.
4148      DebugBreak();
4149#else
4150      // Dereference NULL through a volatile pointer to prevent the compiler
4151      // from removing. We use this rather than abort() or __builtin_trap() for
4152      // portability: Symbian doesn't implement abort() well, and some debuggers
4153      // don't correctly trap abort().
4154      *static_cast<volatile int*>(NULL) = 1;
4155#endif  // GTEST_OS_WINDOWS
4156    } else if (GTEST_FLAG(throw_on_failure)) {
4157#if GTEST_HAS_EXCEPTIONS
4158      throw internal::GoogleTestFailureException(result);
4159#else
4160      // We cannot call abort() as it generates a pop-up in debug mode
4161      // that cannot be suppressed in VC 7.1 or below.
4162      exit(1);
4163#endif
4164    }
4165  }
4166}
4167
4168// Adds a TestProperty to the current TestResult object when invoked from
4169// inside a test, to current TestCase's ad_hoc_test_result_ when invoked
4170// from SetUpTestCase or TearDownTestCase, or to the global property set
4171// when invoked elsewhere.  If the result already contains a property with
4172// the same key, the value will be updated.
4173void UnitTest::RecordProperty(const std::string& key,
4174                              const std::string& value) {
4175  impl_->RecordProperty(TestProperty(key, value));
4176}
4177
4178// Runs all tests in this UnitTest object and prints the result.
4179// Returns 0 if successful, or 1 otherwise.
4180//
4181// We don't protect this under mutex_, as we only support calling it
4182// from the main thread.
4183int UnitTest::Run() {
4184  const bool in_death_test_child_process =
4185      internal::GTEST_FLAG(internal_run_death_test).length() > 0;
4186
4187  // Google Test implements this protocol for catching that a test
4188  // program exits before returning control to Google Test:
4189  //
4190  //   1. Upon start, Google Test creates a file whose absolute path
4191  //      is specified by the environment variable
4192  //      TEST_PREMATURE_EXIT_FILE.
4193  //   2. When Google Test has finished its work, it deletes the file.
4194  //
4195  // This allows a test runner to set TEST_PREMATURE_EXIT_FILE before
4196  // running a Google-Test-based test program and check the existence
4197  // of the file at the end of the test execution to see if it has
4198  // exited prematurely.
4199
4200  // If we are in the child process of a death test, don't
4201  // create/delete the premature exit file, as doing so is unnecessary
4202  // and will confuse the parent process.  Otherwise, create/delete
4203  // the file upon entering/leaving this function.  If the program
4204  // somehow exits before this function has a chance to return, the
4205  // premature-exit file will be left undeleted, causing a test runner
4206  // that understands the premature-exit-file protocol to report the
4207  // test as having failed.
4208  const internal::ScopedPrematureExitFile premature_exit_file(
4209      in_death_test_child_process ?
4210      NULL : internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE"));
4211
4212  // Captures the value of GTEST_FLAG(catch_exceptions).  This value will be
4213  // used for the duration of the program.
4214  impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions));
4215
4216#if GTEST_HAS_SEH
4217  // Either the user wants Google Test to catch exceptions thrown by the
4218  // tests or this is executing in the context of death test child
4219  // process. In either case the user does not want to see pop-up dialogs
4220  // about crashes - they are expected.
4221  if (impl()->catch_exceptions() || in_death_test_child_process) {
4222# if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
4223    // SetErrorMode doesn't exist on CE.
4224    SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
4225                 SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
4226# endif  // !GTEST_OS_WINDOWS_MOBILE
4227
4228# if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
4229    // Death test children can be terminated with _abort().  On Windows,
4230    // _abort() can show a dialog with a warning message.  This forces the
4231    // abort message to go to stderr instead.
4232    _set_error_mode(_OUT_TO_STDERR);
4233# endif
4234
4235# if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
4236    // In the debug version, Visual Studio pops up a separate dialog
4237    // offering a choice to debug the aborted program. We need to suppress
4238    // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
4239    // executed. Google Test will notify the user of any unexpected
4240    // failure via stderr.
4241    //
4242    // VC++ doesn't define _set_abort_behavior() prior to the version 8.0.
4243    // Users of prior VC versions shall suffer the agony and pain of
4244    // clicking through the countless debug dialogs.
4245    // TODO(vladl@google.com): find a way to suppress the abort dialog() in the
4246    // debug mode when compiled with VC 7.1 or lower.
4247    if (!GTEST_FLAG(break_on_failure))
4248      _set_abort_behavior(
4249          0x0,                                    // Clear the following flags:
4250          _WRITE_ABORT_MSG | _CALL_REPORTFAULT);  // pop-up window, core dump.
4251# endif
4252  }
4253#endif  // GTEST_HAS_SEH
4254
4255  return internal::HandleExceptionsInMethodIfSupported(
4256      impl(),
4257      &internal::UnitTestImpl::RunAllTests,
4258      "auxiliary test code (environments or event listeners)") ? 0 : 1;
4259}
4260
4261// Returns the working directory when the first TEST() or TEST_F() was
4262// executed.
4263const char* UnitTest::original_working_dir() const {
4264  return impl_->original_working_dir_.c_str();
4265}
4266
4267// Returns the TestCase object for the test that's currently running,
4268// or NULL if no test is running.
4269const TestCase* UnitTest::current_test_case() const
4270    GTEST_LOCK_EXCLUDED_(mutex_) {
4271  internal::MutexLock lock(&mutex_);
4272  return impl_->current_test_case();
4273}
4274
4275// Returns the TestInfo object for the test that's currently running,
4276// or NULL if no test is running.
4277const TestInfo* UnitTest::current_test_info() const
4278    GTEST_LOCK_EXCLUDED_(mutex_) {
4279  internal::MutexLock lock(&mutex_);
4280  return impl_->current_test_info();
4281}
4282
4283// Returns the random seed used at the start of the current test run.
4284int UnitTest::random_seed() const { return impl_->random_seed(); }
4285
4286#if GTEST_HAS_PARAM_TEST
4287// Returns ParameterizedTestCaseRegistry object used to keep track of
4288// value-parameterized tests and instantiate and register them.
4289internal::ParameterizedTestCaseRegistry&
4290    UnitTest::parameterized_test_registry()
4291        GTEST_LOCK_EXCLUDED_(mutex_) {
4292  return impl_->parameterized_test_registry();
4293}
4294#endif  // GTEST_HAS_PARAM_TEST
4295
4296// Creates an empty UnitTest.
4297UnitTest::UnitTest() {
4298  impl_ = new internal::UnitTestImpl(this);
4299}
4300
4301// Destructor of UnitTest.
4302UnitTest::~UnitTest() {
4303  delete impl_;
4304}
4305
4306// Pushes a trace defined by SCOPED_TRACE() on to the per-thread
4307// Google Test trace stack.
4308void UnitTest::PushGTestTrace(const internal::TraceInfo& trace)
4309    GTEST_LOCK_EXCLUDED_(mutex_) {
4310  internal::MutexLock lock(&mutex_);
4311  impl_->gtest_trace_stack().push_back(trace);
4312}
4313
4314// Pops a trace from the per-thread Google Test trace stack.
4315void UnitTest::PopGTestTrace()
4316    GTEST_LOCK_EXCLUDED_(mutex_) {
4317  internal::MutexLock lock(&mutex_);
4318  impl_->gtest_trace_stack().pop_back();
4319}
4320
4321namespace internal {
4322
4323UnitTestImpl::UnitTestImpl(UnitTest* parent)
4324    : parent_(parent),
4325      GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355 /* using this in initializer */)
4326      default_global_test_part_result_reporter_(this),
4327      default_per_thread_test_part_result_reporter_(this),
4328      GTEST_DISABLE_MSC_WARNINGS_POP_()
4329      global_test_part_result_repoter_(
4330          &default_global_test_part_result_reporter_),
4331      per_thread_test_part_result_reporter_(
4332          &default_per_thread_test_part_result_reporter_),
4333#if GTEST_HAS_PARAM_TEST
4334      parameterized_test_registry_(),
4335      parameterized_tests_registered_(false),
4336#endif  // GTEST_HAS_PARAM_TEST
4337      last_death_test_case_(-1),
4338      current_test_case_(NULL),
4339      current_test_info_(NULL),
4340      ad_hoc_test_result_(),
4341      os_stack_trace_getter_(NULL),
4342      post_flag_parse_init_performed_(false),
4343      random_seed_(0),  // Will be overridden by the flag before first use.
4344      random_(0),  // Will be reseeded before first use.
4345      start_timestamp_(0),
4346      elapsed_time_(0),
4347#if GTEST_HAS_DEATH_TEST
4348      death_test_factory_(new DefaultDeathTestFactory),
4349#endif
4350      // Will be overridden by the flag before first use.
4351      catch_exceptions_(false) {
4352  listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);
4353}
4354
4355UnitTestImpl::~UnitTestImpl() {
4356  // Deletes every TestCase.
4357  ForEach(test_cases_, internal::Delete<TestCase>);
4358
4359  // Deletes every Environment.
4360  ForEach(environments_, internal::Delete<Environment>);
4361
4362  delete os_stack_trace_getter_;
4363}
4364
4365// Adds a TestProperty to the current TestResult object when invoked in a
4366// context of a test, to current test case's ad_hoc_test_result when invoke
4367// from SetUpTestCase/TearDownTestCase, or to the global property set
4368// otherwise.  If the result already contains a property with the same key,
4369// the value will be updated.
4370void UnitTestImpl::RecordProperty(const TestProperty& test_property) {
4371  std::string xml_element;
4372  TestResult* test_result;  // TestResult appropriate for property recording.
4373
4374  if (current_test_info_ != NULL) {
4375    xml_element = "testcase";
4376    test_result = &(current_test_info_->result_);
4377  } else if (current_test_case_ != NULL) {
4378    xml_element = "testsuite";
4379    test_result = &(current_test_case_->ad_hoc_test_result_);
4380  } else {
4381    xml_element = "testsuites";
4382    test_result = &ad_hoc_test_result_;
4383  }
4384  test_result->RecordProperty(xml_element, test_property);
4385}
4386
4387#if GTEST_HAS_DEATH_TEST
4388// Disables event forwarding if the control is currently in a death test
4389// subprocess. Must not be called before InitGoogleTest.
4390void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
4391  if (internal_run_death_test_flag_.get() != NULL)
4392    listeners()->SuppressEventForwarding();
4393}
4394#endif  // GTEST_HAS_DEATH_TEST
4395
4396// Initializes event listeners performing XML output as specified by
4397// UnitTestOptions. Must not be called before InitGoogleTest.
4398void UnitTestImpl::ConfigureXmlOutput() {
4399  const std::string& output_format = UnitTestOptions::GetOutputFormat();
4400  if (output_format == "xml") {
4401    listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
4402        UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
4403  } else if (output_format != "") {
4404    printf("WARNING: unrecognized output format \"%s\" ignored.\n",
4405           output_format.c_str());
4406    fflush(stdout);
4407  }
4408}
4409
4410#if GTEST_CAN_STREAM_RESULTS_
4411// Initializes event listeners for streaming test results in string form.
4412// Must not be called before InitGoogleTest.
4413void UnitTestImpl::ConfigureStreamingOutput() {
4414  const std::string& target = GTEST_FLAG(stream_result_to);
4415  if (!target.empty()) {
4416    const size_t pos = target.find(':');
4417    if (pos != std::string::npos) {
4418      listeners()->Append(new StreamingListener(target.substr(0, pos),
4419                                                target.substr(pos+1)));
4420    } else {
4421      printf("WARNING: unrecognized streaming target \"%s\" ignored.\n",
4422             target.c_str());
4423      fflush(stdout);
4424    }
4425  }
4426}
4427#endif  // GTEST_CAN_STREAM_RESULTS_
4428
4429// Performs initialization dependent upon flag values obtained in
4430// ParseGoogleTestFlagsOnly.  Is called from InitGoogleTest after the call to
4431// ParseGoogleTestFlagsOnly.  In case a user neglects to call InitGoogleTest
4432// this function is also called from RunAllTests.  Since this function can be
4433// called more than once, it has to be idempotent.
4434void UnitTestImpl::PostFlagParsingInit() {
4435  // Ensures that this function does not execute more than once.
4436  if (!post_flag_parse_init_performed_) {
4437    post_flag_parse_init_performed_ = true;
4438
4439#if defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
4440    // Register to send notifications about key process state changes.
4441    listeners()->Append(new GTEST_CUSTOM_TEST_EVENT_LISTENER_());
4442#endif  // defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
4443
4444#if GTEST_HAS_DEATH_TEST
4445    InitDeathTestSubprocessControlInfo();
4446    SuppressTestEventsIfInSubprocess();
4447#endif  // GTEST_HAS_DEATH_TEST
4448
4449    // Registers parameterized tests. This makes parameterized tests
4450    // available to the UnitTest reflection API without running
4451    // RUN_ALL_TESTS.
4452    RegisterParameterizedTests();
4453
4454    // Configures listeners for XML output. This makes it possible for users
4455    // to shut down the default XML output before invoking RUN_ALL_TESTS.
4456    ConfigureXmlOutput();
4457
4458#if GTEST_CAN_STREAM_RESULTS_
4459    // Configures listeners for streaming test results to the specified server.
4460    ConfigureStreamingOutput();
4461#endif  // GTEST_CAN_STREAM_RESULTS_
4462  }
4463}
4464
4465// A predicate that checks the name of a TestCase against a known
4466// value.
4467//
4468// This is used for implementation of the UnitTest class only.  We put
4469// it in the anonymous namespace to prevent polluting the outer
4470// namespace.
4471//
4472// TestCaseNameIs is copyable.
4473class TestCaseNameIs {
4474 public:
4475  // Constructor.
4476  explicit TestCaseNameIs(const std::string& name)
4477      : name_(name) {}
4478
4479  // Returns true iff the name of test_case matches name_.
4480  bool operator()(const TestCase* test_case) const {
4481    return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0;
4482  }
4483
4484 private:
4485  std::string name_;
4486};
4487
4488// Finds and returns a TestCase with the given name.  If one doesn't
4489// exist, creates one and returns it.  It's the CALLER'S
4490// RESPONSIBILITY to ensure that this function is only called WHEN THE
4491// TESTS ARE NOT SHUFFLED.
4492//
4493// Arguments:
4494//
4495//   test_case_name: name of the test case
4496//   type_param:     the name of the test case's type parameter, or NULL if
4497//                   this is not a typed or a type-parameterized test case.
4498//   set_up_tc:      pointer to the function that sets up the test case
4499//   tear_down_tc:   pointer to the function that tears down the test case
4500TestCase* UnitTestImpl::GetTestCase(const char* test_case_name,
4501                                    const char* type_param,
4502                                    Test::SetUpTestCaseFunc set_up_tc,
4503                                    Test::TearDownTestCaseFunc tear_down_tc) {
4504  // Can we find a TestCase with the given name?
4505  const std::vector<TestCase*>::const_iterator test_case =
4506      std::find_if(test_cases_.begin(), test_cases_.end(),
4507                   TestCaseNameIs(test_case_name));
4508
4509  if (test_case != test_cases_.end())
4510    return *test_case;
4511
4512  // No.  Let's create one.
4513  TestCase* const new_test_case =
4514      new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc);
4515
4516  // Is this a death test case?
4517  if (internal::UnitTestOptions::MatchesFilter(test_case_name,
4518                                               kDeathTestCaseFilter)) {
4519    // Yes.  Inserts the test case after the last death test case
4520    // defined so far.  This only works when the test cases haven't
4521    // been shuffled.  Otherwise we may end up running a death test
4522    // after a non-death test.
4523    ++last_death_test_case_;
4524    test_cases_.insert(test_cases_.begin() + last_death_test_case_,
4525                       new_test_case);
4526  } else {
4527    // No.  Appends to the end of the list.
4528    test_cases_.push_back(new_test_case);
4529  }
4530
4531  test_case_indices_.push_back(static_cast<int>(test_case_indices_.size()));
4532  return new_test_case;
4533}
4534
4535// Helpers for setting up / tearing down the given environment.  They
4536// are for use in the ForEach() function.
4537static void SetUpEnvironment(Environment* env) { env->SetUp(); }
4538static void TearDownEnvironment(Environment* env) { env->TearDown(); }
4539
4540// Runs all tests in this UnitTest object, prints the result, and
4541// returns true if all tests are successful.  If any exception is
4542// thrown during a test, the test is considered to be failed, but the
4543// rest of the tests will still be run.
4544//
4545// When parameterized tests are enabled, it expands and registers
4546// parameterized tests first in RegisterParameterizedTests().
4547// All other functions called from RunAllTests() may safely assume that
4548// parameterized tests are ready to be counted and run.
4549bool UnitTestImpl::RunAllTests() {
4550  // Makes sure InitGoogleTest() was called.
4551  if (!GTestIsInitialized()) {
4552    printf("%s",
4553           "\nThis test program did NOT call ::testing::InitGoogleTest "
4554           "before calling RUN_ALL_TESTS().  Please fix it.\n");
4555    return false;
4556  }
4557
4558  // Do not run any test if the --help flag was specified.
4559  if (g_help_flag)
4560    return true;
4561
4562  // Repeats the call to the post-flag parsing initialization in case the
4563  // user didn't call InitGoogleTest.
4564  PostFlagParsingInit();
4565
4566  // Even if sharding is not on, test runners may want to use the
4567  // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
4568  // protocol.
4569  internal::WriteToShardStatusFileIfNeeded();
4570
4571  // True iff we are in a subprocess for running a thread-safe-style
4572  // death test.
4573  bool in_subprocess_for_death_test = false;
4574
4575#if GTEST_HAS_DEATH_TEST
4576  in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL);
4577# if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
4578  if (in_subprocess_for_death_test) {
4579    GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_();
4580  }
4581# endif  // defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
4582#endif  // GTEST_HAS_DEATH_TEST
4583
4584  const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
4585                                        in_subprocess_for_death_test);
4586
4587  // Compares the full test names with the filter to decide which
4588  // tests to run.
4589  const bool has_tests_to_run = FilterTests(should_shard
4590                                              ? HONOR_SHARDING_PROTOCOL
4591                                              : IGNORE_SHARDING_PROTOCOL) > 0;
4592
4593  // Lists the tests and exits if the --gtest_list_tests flag was specified.
4594  if (GTEST_FLAG(list_tests)) {
4595    // This must be called *after* FilterTests() has been called.
4596    ListTestsMatchingFilter();
4597    return true;
4598  }
4599
4600  random_seed_ = GTEST_FLAG(shuffle) ?
4601      GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;
4602
4603  // True iff at least one test has failed.
4604  bool failed = false;
4605
4606  TestEventListener* repeater = listeners()->repeater();
4607
4608  start_timestamp_ = GetTimeInMillis();
4609  repeater->OnTestProgramStart(*parent_);
4610
4611  // How many times to repeat the tests?  We don't want to repeat them
4612  // when we are inside the subprocess of a death test.
4613  const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);
4614  // Repeats forever if the repeat count is negative.
4615  const bool forever = repeat < 0;
4616  for (int i = 0; forever || i != repeat; i++) {
4617    // We want to preserve failures generated by ad-hoc test
4618    // assertions executed before RUN_ALL_TESTS().
4619    ClearNonAdHocTestResult();
4620
4621    const TimeInMillis start = GetTimeInMillis();
4622
4623    // Shuffles test cases and tests if requested.
4624    if (has_tests_to_run && GTEST_FLAG(shuffle)) {
4625      random()->Reseed(random_seed_);
4626      // This should be done before calling OnTestIterationStart(),
4627      // such that a test event listener can see the actual test order
4628      // in the event.
4629      ShuffleTests();
4630    }
4631
4632    // Tells the unit test event listeners that the tests are about to start.
4633    repeater->OnTestIterationStart(*parent_, i);
4634
4635    // Runs each test case if there is at least one test to run.
4636    if (has_tests_to_run) {
4637      // Sets up all environments beforehand.
4638      repeater->OnEnvironmentsSetUpStart(*parent_);
4639      ForEach(environments_, SetUpEnvironment);
4640      repeater->OnEnvironmentsSetUpEnd(*parent_);
4641
4642      // Runs the tests only if there was no fatal failure during global
4643      // set-up.
4644      if (!Test::HasFatalFailure()) {
4645        for (int test_index = 0; test_index < total_test_case_count();
4646             test_index++) {
4647          GetMutableTestCase(test_index)->Run();
4648        }
4649      }
4650
4651      // Tears down all environments in reverse order afterwards.
4652      repeater->OnEnvironmentsTearDownStart(*parent_);
4653      std::for_each(environments_.rbegin(), environments_.rend(),
4654                    TearDownEnvironment);
4655      repeater->OnEnvironmentsTearDownEnd(*parent_);
4656    }
4657
4658    elapsed_time_ = GetTimeInMillis() - start;
4659
4660    // Tells the unit test event listener that the tests have just finished.
4661    repeater->OnTestIterationEnd(*parent_, i);
4662
4663    // Gets the result and clears it.
4664    if (!Passed()) {
4665      failed = true;
4666    }
4667
4668    // Restores the original test order after the iteration.  This
4669    // allows the user to quickly repro a failure that happens in the
4670    // N-th iteration without repeating the first (N - 1) iterations.
4671    // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in
4672    // case the user somehow changes the value of the flag somewhere
4673    // (it's always safe to unshuffle the tests).
4674    UnshuffleTests();
4675
4676    if (GTEST_FLAG(shuffle)) {
4677      // Picks a new random seed for each iteration.
4678      random_seed_ = GetNextRandomSeed(random_seed_);
4679    }
4680  }
4681
4682  repeater->OnTestProgramEnd(*parent_);
4683
4684  return !failed;
4685}
4686
4687// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
4688// if the variable is present. If a file already exists at this location, this
4689// function will write over it. If the variable is present, but the file cannot
4690// be created, prints an error and exits.
4691void WriteToShardStatusFileIfNeeded() {
4692  const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);
4693  if (test_shard_file != NULL) {
4694    FILE* const file = posix::FOpen(test_shard_file, "w");
4695    if (file == NULL) {
4696      ColoredPrintf(COLOR_RED,
4697                    "Could not write to the test shard status file \"%s\" "
4698                    "specified by the %s environment variable.\n",
4699                    test_shard_file, kTestShardStatusFile);
4700      fflush(stdout);
4701      exit(EXIT_FAILURE);
4702    }
4703    fclose(file);
4704  }
4705}
4706
4707// Checks whether sharding is enabled by examining the relevant
4708// environment variable values. If the variables are present,
4709// but inconsistent (i.e., shard_index >= total_shards), prints
4710// an error and exits. If in_subprocess_for_death_test, sharding is
4711// disabled because it must only be applied to the original test
4712// process. Otherwise, we could filter out death tests we intended to execute.
4713bool ShouldShard(const char* total_shards_env,
4714                 const char* shard_index_env,
4715                 bool in_subprocess_for_death_test) {
4716  if (in_subprocess_for_death_test) {
4717    return false;
4718  }
4719
4720  const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1);
4721  const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1);
4722
4723  if (total_shards == -1 && shard_index == -1) {
4724    return false;
4725  } else if (total_shards == -1 && shard_index != -1) {
4726    const Message msg = Message()
4727      << "Invalid environment variables: you have "
4728      << kTestShardIndex << " = " << shard_index
4729      << ", but have left " << kTestTotalShards << " unset.\n";
4730    ColoredPrintf(COLOR_RED, msg.GetString().c_str());
4731    fflush(stdout);
4732    exit(EXIT_FAILURE);
4733  } else if (total_shards != -1 && shard_index == -1) {
4734    const Message msg = Message()
4735      << "Invalid environment variables: you have "
4736      << kTestTotalShards << " = " << total_shards
4737      << ", but have left " << kTestShardIndex << " unset.\n";
4738    ColoredPrintf(COLOR_RED, msg.GetString().c_str());
4739    fflush(stdout);
4740    exit(EXIT_FAILURE);
4741  } else if (shard_index < 0 || shard_index >= total_shards) {
4742    const Message msg = Message()
4743      << "Invalid environment variables: we require 0 <= "
4744      << kTestShardIndex << " < " << kTestTotalShards
4745      << ", but you have " << kTestShardIndex << "=" << shard_index
4746      << ", " << kTestTotalShards << "=" << total_shards << ".\n";
4747    ColoredPrintf(COLOR_RED, msg.GetString().c_str());
4748    fflush(stdout);
4749    exit(EXIT_FAILURE);
4750  }
4751
4752  return total_shards > 1;
4753}
4754
4755// Parses the environment variable var as an Int32. If it is unset,
4756// returns default_val. If it is not an Int32, prints an error
4757// and aborts.
4758Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) {
4759  const char* str_val = posix::GetEnv(var);
4760  if (str_val == NULL) {
4761    return default_val;
4762  }
4763
4764  Int32 result;
4765  if (!ParseInt32(Message() << "The value of environment variable " << var,
4766                  str_val, &result)) {
4767    exit(EXIT_FAILURE);
4768  }
4769  return result;
4770}
4771
4772// Given the total number of shards, the shard index, and the test id,
4773// returns true iff the test should be run on this shard. The test id is
4774// some arbitrary but unique non-negative integer assigned to each test
4775// method. Assumes that 0 <= shard_index < total_shards.
4776bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
4777  return (test_id % total_shards) == shard_index;
4778}
4779
4780// Compares the name of each test with the user-specified filter to
4781// decide whether the test should be run, then records the result in
4782// each TestCase and TestInfo object.
4783// If shard_tests == true, further filters tests based on sharding
4784// variables in the environment - see
4785// http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide.
4786// Returns the number of tests that should run.
4787int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
4788  const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?
4789      Int32FromEnvOrDie(kTestTotalShards, -1) : -1;
4790  const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?
4791      Int32FromEnvOrDie(kTestShardIndex, -1) : -1;
4792
4793  // num_runnable_tests are the number of tests that will
4794  // run across all shards (i.e., match filter and are not disabled).
4795  // num_selected_tests are the number of tests to be run on
4796  // this shard.
4797  int num_runnable_tests = 0;
4798  int num_selected_tests = 0;
4799  for (size_t i = 0; i < test_cases_.size(); i++) {
4800    TestCase* const test_case = test_cases_[i];
4801    const std::string &test_case_name = test_case->name();
4802    test_case->set_should_run(false);
4803
4804    for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
4805      TestInfo* const test_info = test_case->test_info_list()[j];
4806      const std::string test_name(test_info->name());
4807      // A test is disabled if test case name or test name matches
4808      // kDisableTestFilter.
4809      const bool is_disabled =
4810          internal::UnitTestOptions::MatchesFilter(test_case_name,
4811                                                   kDisableTestFilter) ||
4812          internal::UnitTestOptions::MatchesFilter(test_name,
4813                                                   kDisableTestFilter);
4814      test_info->is_disabled_ = is_disabled;
4815
4816      const bool matches_filter =
4817          internal::UnitTestOptions::FilterMatchesTest(test_case_name,
4818                                                       test_name);
4819      test_info->matches_filter_ = matches_filter;
4820
4821      const bool is_runnable =
4822          (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
4823          matches_filter;
4824
4825      const bool is_selected = is_runnable &&
4826          (shard_tests == IGNORE_SHARDING_PROTOCOL ||
4827           ShouldRunTestOnShard(total_shards, shard_index,
4828                                num_runnable_tests));
4829
4830      num_runnable_tests += is_runnable;
4831      num_selected_tests += is_selected;
4832
4833      test_info->should_run_ = is_selected;
4834      test_case->set_should_run(test_case->should_run() || is_selected);
4835    }
4836  }
4837  return num_selected_tests;
4838}
4839
4840// Prints the given C-string on a single line by replacing all '\n'
4841// characters with string "\\n".  If the output takes more than
4842// max_length characters, only prints the first max_length characters
4843// and "...".
4844static void PrintOnOneLine(const char* str, int max_length) {
4845  if (str != NULL) {
4846    for (int i = 0; *str != '\0'; ++str) {
4847      if (i >= max_length) {
4848        printf("...");
4849        break;
4850      }
4851      if (*str == '\n') {
4852        printf("\\n");
4853        i += 2;
4854      } else {
4855        printf("%c", *str);
4856        ++i;
4857      }
4858    }
4859  }
4860}
4861
4862// Prints the names of the tests matching the user-specified filter flag.
4863void UnitTestImpl::ListTestsMatchingFilter() {
4864  // Print at most this many characters for each type/value parameter.
4865  const int kMaxParamLength = 250;
4866
4867  for (size_t i = 0; i < test_cases_.size(); i++) {
4868    const TestCase* const test_case = test_cases_[i];
4869    bool printed_test_case_name = false;
4870
4871    for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
4872      const TestInfo* const test_info =
4873          test_case->test_info_list()[j];
4874      if (test_info->matches_filter_) {
4875        if (!printed_test_case_name) {
4876          printed_test_case_name = true;
4877          printf("%s.", test_case->name());
4878          if (test_case->type_param() != NULL) {
4879            printf("  # %s = ", kTypeParamLabel);
4880            // We print the type parameter on a single line to make
4881            // the output easy to parse by a program.
4882            PrintOnOneLine(test_case->type_param(), kMaxParamLength);
4883          }
4884          printf("\n");
4885        }
4886        printf("  %s", test_info->name());
4887        if (test_info->value_param() != NULL) {
4888          printf("  # %s = ", kValueParamLabel);
4889          // We print the value parameter on a single line to make the
4890          // output easy to parse by a program.
4891          PrintOnOneLine(test_info->value_param(), kMaxParamLength);
4892        }
4893        printf("\n");
4894      }
4895    }
4896  }
4897  fflush(stdout);
4898}
4899
4900// Sets the OS stack trace getter.
4901//
4902// Does nothing if the input and the current OS stack trace getter are
4903// the same; otherwise, deletes the old getter and makes the input the
4904// current getter.
4905void UnitTestImpl::set_os_stack_trace_getter(
4906    OsStackTraceGetterInterface* getter) {
4907  if (os_stack_trace_getter_ != getter) {
4908    delete os_stack_trace_getter_;
4909    os_stack_trace_getter_ = getter;
4910  }
4911}
4912
4913// Returns the current OS stack trace getter if it is not NULL;
4914// otherwise, creates an OsStackTraceGetter, makes it the current
4915// getter, and returns it.
4916OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
4917  if (os_stack_trace_getter_ == NULL) {
4918#ifdef GTEST_OS_STACK_TRACE_GETTER_
4919    os_stack_trace_getter_ = new GTEST_OS_STACK_TRACE_GETTER_;
4920#else
4921    os_stack_trace_getter_ = new OsStackTraceGetter;
4922#endif  // GTEST_OS_STACK_TRACE_GETTER_
4923  }
4924
4925  return os_stack_trace_getter_;
4926}
4927
4928// Returns the TestResult for the test that's currently running, or
4929// the TestResult for the ad hoc test if no test is running.
4930TestResult* UnitTestImpl::current_test_result() {
4931  return current_test_info_ ?
4932      &(current_test_info_->result_) : &ad_hoc_test_result_;
4933}
4934
4935// Shuffles all test cases, and the tests within each test case,
4936// making sure that death tests are still run first.
4937void UnitTestImpl::ShuffleTests() {
4938  // Shuffles the death test cases.
4939  ShuffleRange(random(), 0, last_death_test_case_ + 1, &test_case_indices_);
4940
4941  // Shuffles the non-death test cases.
4942  ShuffleRange(random(), last_death_test_case_ + 1,
4943               static_cast<int>(test_cases_.size()), &test_case_indices_);
4944
4945  // Shuffles the tests inside each test case.
4946  for (size_t i = 0; i < test_cases_.size(); i++) {
4947    test_cases_[i]->ShuffleTests(random());
4948  }
4949}
4950
4951// Restores the test cases and tests to their order before the first shuffle.
4952void UnitTestImpl::UnshuffleTests() {
4953  for (size_t i = 0; i < test_cases_.size(); i++) {
4954    // Unshuffles the tests in each test case.
4955    test_cases_[i]->UnshuffleTests();
4956    // Resets the index of each test case.
4957    test_case_indices_[i] = static_cast<int>(i);
4958  }
4959}
4960
4961// Returns the current OS stack trace as an std::string.
4962//
4963// The maximum number of stack frames to be included is specified by
4964// the gtest_stack_trace_depth flag.  The skip_count parameter
4965// specifies the number of top frames to be skipped, which doesn't
4966// count against the number of frames to be included.
4967//
4968// For example, if Foo() calls Bar(), which in turn calls
4969// GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
4970// the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
4971std::string GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/,
4972                                            int skip_count) {
4973  // We pass skip_count + 1 to skip this wrapper function in addition
4974  // to what the user really wants to skip.
4975  return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
4976}
4977
4978// Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to
4979// suppress unreachable code warnings.
4980namespace {
4981class ClassUniqueToAlwaysTrue {};
4982}
4983
4984bool IsTrue(bool condition) { return condition; }
4985
4986bool AlwaysTrue() {
4987#if GTEST_HAS_EXCEPTIONS
4988  // This condition is always false so AlwaysTrue() never actually throws,
4989  // but it makes the compiler think that it may throw.
4990  if (IsTrue(false))
4991    throw ClassUniqueToAlwaysTrue();
4992#endif  // GTEST_HAS_EXCEPTIONS
4993  return true;
4994}
4995
4996// If *pstr starts with the given prefix, modifies *pstr to be right
4997// past the prefix and returns true; otherwise leaves *pstr unchanged
4998// and returns false.  None of pstr, *pstr, and prefix can be NULL.
4999bool SkipPrefix(const char* prefix, const char** pstr) {
5000  const size_t prefix_len = strlen(prefix);
5001  if (strncmp(*pstr, prefix, prefix_len) == 0) {
5002    *pstr += prefix_len;
5003    return true;
5004  }
5005  return false;
5006}
5007
5008// Parses a string as a command line flag.  The string should have
5009// the format "--flag=value".  When def_optional is true, the "=value"
5010// part can be omitted.
5011//
5012// Returns the value of the flag, or NULL if the parsing failed.
5013const char* ParseFlagValue(const char* str,
5014                           const char* flag,
5015                           bool def_optional) {
5016  // str and flag must not be NULL.
5017  if (str == NULL || flag == NULL) return NULL;
5018
5019  // The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
5020  const std::string flag_str = std::string("--") + GTEST_FLAG_PREFIX_ + flag;
5021  const size_t flag_len = flag_str.length();
5022  if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;
5023
5024  // Skips the flag name.
5025  const char* flag_end = str + flag_len;
5026
5027  // When def_optional is true, it's OK to not have a "=value" part.
5028  if (def_optional && (flag_end[0] == '\0')) {
5029    return flag_end;
5030  }
5031
5032  // If def_optional is true and there are more characters after the
5033  // flag name, or if def_optional is false, there must be a '=' after
5034  // the flag name.
5035  if (flag_end[0] != '=') return NULL;
5036
5037  // Returns the string after "=".
5038  return flag_end + 1;
5039}
5040
5041// Parses a string for a bool flag, in the form of either
5042// "--flag=value" or "--flag".
5043//
5044// In the former case, the value is taken as true as long as it does
5045// not start with '0', 'f', or 'F'.
5046//
5047// In the latter case, the value is taken as true.
5048//
5049// On success, stores the value of the flag in *value, and returns
5050// true.  On failure, returns false without changing *value.
5051bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
5052  // Gets the value of the flag as a string.
5053  const char* const value_str = ParseFlagValue(str, flag, true);
5054
5055  // Aborts if the parsing failed.
5056  if (value_str == NULL) return false;
5057
5058  // Converts the string value to a bool.
5059  *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
5060  return true;
5061}
5062
5063// Parses a string for an Int32 flag, in the form of
5064// "--flag=value".
5065//
5066// On success, stores the value of the flag in *value, and returns
5067// true.  On failure, returns false without changing *value.
5068bool ParseInt32Flag(const char* str, const char* flag, Int32* value) {
5069  // Gets the value of the flag as a string.
5070  const char* const value_str = ParseFlagValue(str, flag, false);
5071
5072  // Aborts if the parsing failed.
5073  if (value_str == NULL) return false;
5074
5075  // Sets *value to the value of the flag.
5076  return ParseInt32(Message() << "The value of flag --" << flag,
5077                    value_str, value);
5078}
5079
5080// Parses a string for a string flag, in the form of
5081// "--flag=value".
5082//
5083// On success, stores the value of the flag in *value, and returns
5084// true.  On failure, returns false without changing *value.
5085bool ParseStringFlag(const char* str, const char* flag, std::string* value) {
5086  // Gets the value of the flag as a string.
5087  const char* const value_str = ParseFlagValue(str, flag, false);
5088
5089  // Aborts if the parsing failed.
5090  if (value_str == NULL) return false;
5091
5092  // Sets *value to the value of the flag.
5093  *value = value_str;
5094  return true;
5095}
5096
5097// Determines whether a string has a prefix that Google Test uses for its
5098// flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.
5099// If Google Test detects that a command line flag has its prefix but is not
5100// recognized, it will print its help message. Flags starting with
5101// GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
5102// internal flags and do not trigger the help message.
5103static bool HasGoogleTestFlagPrefix(const char* str) {
5104  return (SkipPrefix("--", &str) ||
5105          SkipPrefix("-", &str) ||
5106          SkipPrefix("/", &str)) &&
5107         !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
5108         (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
5109          SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str));
5110}
5111
5112// Prints a string containing code-encoded text.  The following escape
5113// sequences can be used in the string to control the text color:
5114//
5115//   @@    prints a single '@' character.
5116//   @R    changes the color to red.
5117//   @G    changes the color to green.
5118//   @Y    changes the color to yellow.
5119//   @D    changes to the default terminal text color.
5120//
5121// TODO(wan@google.com): Write tests for this once we add stdout
5122// capturing to Google Test.
5123static void PrintColorEncoded(const char* str) {
5124  GTestColor color = COLOR_DEFAULT;  // The current color.
5125
5126  // Conceptually, we split the string into segments divided by escape
5127  // sequences.  Then we print one segment at a time.  At the end of
5128  // each iteration, the str pointer advances to the beginning of the
5129  // next segment.
5130  for (;;) {
5131    const char* p = strchr(str, '@');
5132    if (p == NULL) {
5133      ColoredPrintf(color, "%s", str);
5134      return;
5135    }
5136
5137    ColoredPrintf(color, "%s", std::string(str, p).c_str());
5138
5139    const char ch = p[1];
5140    str = p + 2;
5141    if (ch == '@') {
5142      ColoredPrintf(color, "@");
5143    } else if (ch == 'D') {
5144      color = COLOR_DEFAULT;
5145    } else if (ch == 'R') {
5146      color = COLOR_RED;
5147    } else if (ch == 'G') {
5148      color = COLOR_GREEN;
5149    } else if (ch == 'Y') {
5150      color = COLOR_YELLOW;
5151    } else {
5152      --str;
5153    }
5154  }
5155}
5156
5157static const char kColorEncodedHelpMessage[] =
5158"This program contains tests written using " GTEST_NAME_ ". You can use the\n"
5159"following command line flags to control its behavior:\n"
5160"\n"
5161"Test Selection:\n"
5162"  @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n"
5163"      List the names of all tests instead of running them. The name of\n"
5164"      TEST(Foo, Bar) is \"Foo.Bar\".\n"
5165"  @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS"
5166    "[@G-@YNEGATIVE_PATTERNS]@D\n"
5167"      Run only the tests whose name matches one of the positive patterns but\n"
5168"      none of the negative patterns. '?' matches any single character; '*'\n"
5169"      matches any substring; ':' separates two patterns.\n"
5170"  @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n"
5171"      Run all disabled tests too.\n"
5172"\n"
5173"Test Execution:\n"
5174"  @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n"
5175"      Run the tests repeatedly; use a negative count to repeat forever.\n"
5176"  @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n"
5177"      Randomize tests' orders on every iteration.\n"
5178"  @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n"
5179"      Random number seed to use for shuffling test orders (between 1 and\n"
5180"      99999, or 0 to use a seed based on the current time).\n"
5181"\n"
5182"Test Output:\n"
5183"  @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
5184"      Enable/disable colored output. The default is @Gauto@D.\n"
5185"  -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n"
5186"      Don't print the elapsed time of each test.\n"
5187"  @G--" GTEST_FLAG_PREFIX_ "output=xml@Y[@G:@YDIRECTORY_PATH@G"
5188    GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n"
5189"      Generate an XML report in the given directory or with the given file\n"
5190"      name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n"
5191#if GTEST_CAN_STREAM_RESULTS_
5192"  @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n"
5193"      Stream test results to the given server.\n"
5194#endif  // GTEST_CAN_STREAM_RESULTS_
5195"\n"
5196"Assertion Behavior:\n"
5197#if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
5198"  @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
5199"      Set the default death test style.\n"
5200#endif  // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
5201"  @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n"
5202"      Turn assertion failures into debugger break-points.\n"
5203"  @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n"
5204"      Turn assertion failures into C++ exceptions.\n"
5205"  @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n"
5206"      Do not report exceptions as test failures. Instead, allow them\n"
5207"      to crash the program or throw a pop-up (on Windows).\n"
5208"\n"
5209"Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set "
5210    "the corresponding\n"
5211"environment variable of a flag (all letters in upper-case). For example, to\n"
5212"disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_
5213    "color=no@D or set\n"
5214"the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n"
5215"\n"
5216"For more information, please read the " GTEST_NAME_ " documentation at\n"
5217"@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n"
5218"(not one in your own code or tests), please report it to\n"
5219"@G<" GTEST_DEV_EMAIL_ ">@D.\n";
5220
5221bool ParseGoogleTestFlag(const char* const arg) {
5222  return ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,
5223                       &GTEST_FLAG(also_run_disabled_tests)) ||
5224      ParseBoolFlag(arg, kBreakOnFailureFlag,
5225                    &GTEST_FLAG(break_on_failure)) ||
5226      ParseBoolFlag(arg, kCatchExceptionsFlag,
5227                    &GTEST_FLAG(catch_exceptions)) ||
5228      ParseStringFlag(arg, kColorFlag, &GTEST_FLAG(color)) ||
5229      ParseStringFlag(arg, kDeathTestStyleFlag,
5230                      &GTEST_FLAG(death_test_style)) ||
5231      ParseBoolFlag(arg, kDeathTestUseFork,
5232                    &GTEST_FLAG(death_test_use_fork)) ||
5233      ParseStringFlag(arg, kFilterFlag, &GTEST_FLAG(filter)) ||
5234      ParseStringFlag(arg, kInternalRunDeathTestFlag,
5235                      &GTEST_FLAG(internal_run_death_test)) ||
5236      ParseBoolFlag(arg, kListTestsFlag, &GTEST_FLAG(list_tests)) ||
5237      ParseStringFlag(arg, kOutputFlag, &GTEST_FLAG(output)) ||
5238      ParseBoolFlag(arg, kPrintTimeFlag, &GTEST_FLAG(print_time)) ||
5239      ParseInt32Flag(arg, kRandomSeedFlag, &GTEST_FLAG(random_seed)) ||
5240      ParseInt32Flag(arg, kRepeatFlag, &GTEST_FLAG(repeat)) ||
5241      ParseBoolFlag(arg, kShuffleFlag, &GTEST_FLAG(shuffle)) ||
5242      ParseInt32Flag(arg, kStackTraceDepthFlag,
5243                     &GTEST_FLAG(stack_trace_depth)) ||
5244      ParseStringFlag(arg, kStreamResultToFlag,
5245                      &GTEST_FLAG(stream_result_to)) ||
5246      ParseBoolFlag(arg, kThrowOnFailureFlag,
5247                    &GTEST_FLAG(throw_on_failure));
5248}
5249
5250#if GTEST_USE_OWN_FLAGFILE_FLAG_
5251void LoadFlagsFromFile(const std::string& path) {
5252  FILE* flagfile = posix::FOpen(path.c_str(), "r");
5253  if (!flagfile) {
5254    fprintf(stderr,
5255            "Unable to open file \"%s\"\n",
5256            GTEST_FLAG(flagfile).c_str());
5257    fflush(stderr);
5258    exit(EXIT_FAILURE);
5259  }
5260  std::string contents(ReadEntireFile(flagfile));
5261  posix::FClose(flagfile);
5262  std::vector<std::string> lines;
5263  SplitString(contents, '\n', &lines);
5264  for (size_t i = 0; i < lines.size(); ++i) {
5265    if (lines[i].empty())
5266      continue;
5267    if (!ParseGoogleTestFlag(lines[i].c_str()))
5268      g_help_flag = true;
5269  }
5270}
5271#endif  // GTEST_USE_OWN_FLAGFILE_FLAG_
5272
5273// Parses the command line for Google Test flags, without initializing
5274// other parts of Google Test.  The type parameter CharType can be
5275// instantiated to either char or wchar_t.
5276template <typename CharType>
5277void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
5278  for (int i = 1; i < *argc; i++) {
5279    const std::string arg_string = StreamableToString(argv[i]);
5280    const char* const arg = arg_string.c_str();
5281
5282    using internal::ParseBoolFlag;
5283    using internal::ParseInt32Flag;
5284    using internal::ParseStringFlag;
5285
5286    bool remove_flag = false;
5287    if (ParseGoogleTestFlag(arg)) {
5288      remove_flag = true;
5289#if GTEST_USE_OWN_FLAGFILE_FLAG_
5290    } else if (ParseStringFlag(arg, kFlagfileFlag, &GTEST_FLAG(flagfile))) {
5291      LoadFlagsFromFile(GTEST_FLAG(flagfile));
5292      remove_flag = true;
5293#endif  // GTEST_USE_OWN_FLAGFILE_FLAG_
5294    } else if (arg_string == "--help" || arg_string == "-h" ||
5295               arg_string == "-?" || arg_string == "/?" ||
5296               HasGoogleTestFlagPrefix(arg)) {
5297      // Both help flag and unrecognized Google Test flags (excluding
5298      // internal ones) trigger help display.
5299      g_help_flag = true;
5300    }
5301
5302    if (remove_flag) {
5303      // Shift the remainder of the argv list left by one.  Note
5304      // that argv has (*argc + 1) elements, the last one always being
5305      // NULL.  The following loop moves the trailing NULL element as
5306      // well.
5307      for (int j = i; j != *argc; j++) {
5308        argv[j] = argv[j + 1];
5309      }
5310
5311      // Decrements the argument count.
5312      (*argc)--;
5313
5314      // We also need to decrement the iterator as we just removed
5315      // an element.
5316      i--;
5317    }
5318  }
5319
5320  if (g_help_flag) {
5321    // We print the help here instead of in RUN_ALL_TESTS(), as the
5322    // latter may not be called at all if the user is using Google
5323    // Test with another testing framework.
5324    PrintColorEncoded(kColorEncodedHelpMessage);
5325  }
5326}
5327
5328// Parses the command line for Google Test flags, without initializing
5329// other parts of Google Test.
5330void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
5331  ParseGoogleTestFlagsOnlyImpl(argc, argv);
5332}
5333void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {
5334  ParseGoogleTestFlagsOnlyImpl(argc, argv);
5335}
5336
5337// The internal implementation of InitGoogleTest().
5338//
5339// The type parameter CharType can be instantiated to either char or
5340// wchar_t.
5341template <typename CharType>
5342void InitGoogleTestImpl(int* argc, CharType** argv) {
5343  // We don't want to run the initialization code twice.
5344  if (GTestIsInitialized()) return;
5345
5346  if (*argc <= 0) return;
5347
5348  g_argvs.clear();
5349  for (int i = 0; i != *argc; i++) {
5350    g_argvs.push_back(StreamableToString(argv[i]));
5351  }
5352
5353  ParseGoogleTestFlagsOnly(argc, argv);
5354  GetUnitTestImpl()->PostFlagParsingInit();
5355}
5356
5357}  // namespace internal
5358
5359// Initializes Google Test.  This must be called before calling
5360// RUN_ALL_TESTS().  In particular, it parses a command line for the
5361// flags that Google Test recognizes.  Whenever a Google Test flag is
5362// seen, it is removed from argv, and *argc is decremented.
5363//
5364// No value is returned.  Instead, the Google Test flag variables are
5365// updated.
5366//
5367// Calling the function for the second time has no user-visible effect.
5368void InitGoogleTest(int* argc, char** argv) {
5369#if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
5370  GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
5371#else  // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
5372  internal::InitGoogleTestImpl(argc, argv);
5373#endif  // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
5374}
5375
5376// This overloaded version can be used in Windows programs compiled in
5377// UNICODE mode.
5378void InitGoogleTest(int* argc, wchar_t** argv) {
5379#if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
5380  GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
5381#else  // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
5382  internal::InitGoogleTestImpl(argc, argv);
5383#endif  // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
5384}
5385
5386}  // namespace testing
5387