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