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