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 <string.h>
43
44#ifdef GTEST_OS_LINUX
45
46// TODO(kenton@google.com): Use autoconf to detect availability of
47// gettimeofday().
48#define GTEST_HAS_GETTIMEOFDAY
49
50#include <fcntl.h>
51#include <limits.h>
52#include <sched.h>
53// Declares vsnprintf().  This header is not available on Windows.
54#include <strings.h>
55#include <sys/mman.h>
56#include <sys/time.h>
57#include <unistd.h>
58#include <string>
59#include <vector>
60
61#elif defined(_WIN32_WCE)  // We are on Windows CE.
62
63#include <windows.h>  // NOLINT
64
65#elif defined(_WIN32)  // We are on Windows proper.
66
67#include <io.h>  // NOLINT
68#include <sys/timeb.h>  // NOLINT
69#include <sys/types.h>  // NOLINT
70#include <sys/stat.h>  // NOLINT
71
72#if defined(__MINGW__) || defined(__MINGW32__)
73// MinGW has gettimeofday() but not _ftime64().
74// TODO(kenton@google.com): Use autoconf to detect availability of
75//   gettimeofday().
76// TODO(kenton@google.com): There are other ways to get the time on
77//   Windows, like GetTickCount() or GetSystemTimeAsFileTime().  MinGW
78//   supports these.  consider using them instead.
79#define GTEST_HAS_GETTIMEOFDAY
80#include <sys/time.h>  // NOLINT
81#endif
82
83// cpplint thinks that the header is already included, so we want to
84// silence it.
85#include <windows.h>  // NOLINT
86
87#else
88
89// Assume other platforms have gettimeofday().
90// TODO(kenton@google.com): Use autoconf to detect availability of
91//   gettimeofday().
92#define GTEST_HAS_GETTIMEOFDAY
93
94// cpplint thinks that the header is already included, so we want to
95// silence it.
96#include <sys/time.h>  // NOLINT
97#include <unistd.h>  // NOLINT
98
99#endif
100
101// Indicates that this translation unit is part of Google Test's
102// implementation.  It must come before gtest-internal-inl.h is
103// included, or there will be a compiler error.  This trick is to
104// prevent a user from accidentally including gtest-internal-inl.h in
105// his code.
106#define GTEST_IMPLEMENTATION
107#include "src/gtest-internal-inl.h"
108#undef GTEST_IMPLEMENTATION
109
110#ifdef GTEST_OS_WINDOWS
111#define fileno _fileno
112#define isatty _isatty
113#define vsnprintf _vsnprintf
114#endif  // GTEST_OS_WINDOWS
115
116namespace testing {
117
118// Constants.
119
120// A test that matches this pattern is disabled and not run.
121static const char kDisableTestPattern[] = "DISABLED_*";
122
123// A test filter that matches everything.
124static const char kUniversalFilter[] = "*";
125
126// The default output file for XML output.
127static const char kDefaultOutputFile[] = "test_detail.xml";
128
129GTEST_DEFINE_bool(
130    break_on_failure,
131    internal::BoolFromGTestEnv("break_on_failure", false),
132    "True iff a failed assertion should be a debugger break-point.");
133
134GTEST_DEFINE_bool(
135    catch_exceptions,
136    internal::BoolFromGTestEnv("catch_exceptions", false),
137    "True iff " GTEST_NAME
138    " should catch exceptions and treat them as test failures.");
139
140GTEST_DEFINE_string(
141    color,
142    internal::StringFromGTestEnv("color", "auto"),
143    "Whether to use colors in the output.  Valid values: yes, no, "
144    "and auto.  'auto' means to use colors if the output is "
145    "being sent to a terminal and the TERM environment variable "
146    "is set to xterm or xterm-color.");
147
148GTEST_DEFINE_string(
149    filter,
150    internal::StringFromGTestEnv("filter", kUniversalFilter),
151    "A colon-separated list of glob (not regex) patterns "
152    "for filtering the tests to run, optionally followed by a "
153    "'-' and a : separated list of negative patterns (tests to "
154    "exclude).  A test is run if it matches one of the positive "
155    "patterns and does not match any of the negative patterns.");
156
157GTEST_DEFINE_bool(list_tests, false,
158                  "List all tests without running them.");
159
160GTEST_DEFINE_string(
161    output,
162    internal::StringFromGTestEnv("output", ""),
163    "A format (currently must be \"xml\"), optionally followed "
164    "by a colon and an output file name or directory. A directory "
165    "is indicated by a trailing pathname separator. "
166    "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
167    "If a directory is specified, output files will be created "
168    "within that directory, with file-names based on the test "
169    "executable's name and, if necessary, made unique by adding "
170    "digits.");
171
172GTEST_DEFINE_int32(
173    repeat,
174    internal::Int32FromGTestEnv("repeat", 1),
175    "How many times to repeat each test.  Specify a negative number "
176    "for repeating forever.  Useful for shaking out flaky tests.");
177
178GTEST_DEFINE_int32(
179    stack_trace_depth,
180        internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
181    "The maximum number of stack frames to print when an "
182    "assertion fails.  The valid range is 0 through 100, inclusive.");
183
184GTEST_DEFINE_bool(
185    show_internal_stack_frames, false,
186    "True iff " GTEST_NAME " should include internal stack frames when "
187    "printing test failure stack traces.");
188
189namespace internal {
190
191// GTestIsInitialized() returns true iff the user has initialized
192// Google Test.  Useful for catching the user mistake of not initializing
193// Google Test before calling RUN_ALL_TESTS().
194
195// A user must call testing::InitGoogleTest() to initialize Google
196// Test.  g_parse_gtest_flags_called is set to true iff
197// InitGoogleTest() has been called.  We don't protect this variable
198// under a mutex as it is only accessed in the main thread.
199static bool g_parse_gtest_flags_called = false;
200static bool GTestIsInitialized() { return g_parse_gtest_flags_called; }
201
202// Iterates over a list of TestCases, keeping a running sum of the
203// results of calling a given int-returning method on each.
204// Returns the sum.
205static int SumOverTestCaseList(const internal::List<TestCase*>& case_list,
206                               int (TestCase::*method)() const) {
207  int sum = 0;
208  for (const internal::ListNode<TestCase*>* node = case_list.Head();
209       node != NULL;
210       node = node->next()) {
211    sum += (node->element()->*method)();
212  }
213  return sum;
214}
215
216// Returns true iff the test case passed.
217static bool TestCasePassed(const TestCase* test_case) {
218  return test_case->should_run() && test_case->Passed();
219}
220
221// Returns true iff the test case failed.
222static bool TestCaseFailed(const TestCase* test_case) {
223  return test_case->should_run() && test_case->Failed();
224}
225
226// Returns true iff test_case contains at least one test that should
227// run.
228static bool ShouldRunTestCase(const TestCase* test_case) {
229  return test_case->should_run();
230}
231
232#ifdef _WIN32_WCE
233// Windows CE has no C library. The abort() function is used in
234// several places in Google Test. This implementation provides a reasonable
235// imitation of standard behaviour.
236static void abort() {
237  DebugBreak();
238  TerminateProcess(GetCurrentProcess(), 1);
239}
240#endif  // _WIN32_WCE
241
242// AssertHelper constructor.
243AssertHelper::AssertHelper(TestPartResultType type, const char* file,
244                           int line, const char* message)
245    : type_(type), file_(file), line_(line), message_(message) {
246}
247
248// Message assignment, for assertion streaming support.
249void AssertHelper::operator=(const Message& message) const {
250  UnitTest::GetInstance()->
251    AddTestPartResult(type_, file_, line_,
252                      AppendUserMessage(message_, message),
253                      UnitTest::GetInstance()->impl()
254                      ->CurrentOsStackTraceExceptTop(1)
255                      // Skips the stack frame for this function itself.
256                      );  // NOLINT
257}
258
259// Application pathname gotten in InitGoogleTest.
260String g_executable_path;
261
262// Returns the current application's name, removing directory path if that
263// is present.
264FilePath GetCurrentExecutableName() {
265  FilePath result;
266
267#if defined(_WIN32_WCE) || defined(_WIN32)
268  result.Set(FilePath(g_executable_path).RemoveExtension("exe"));
269#else
270  result.Set(FilePath(g_executable_path));
271#endif  // _WIN32_WCE || _WIN32
272
273  return result.RemoveDirectoryName();
274}
275
276// Functions for processing the gtest_output flag.
277
278// Returns the output format, or "" for normal printed output.
279String UnitTestOptions::GetOutputFormat() {
280  const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
281  if (gtest_output_flag == NULL) return String("");
282
283  const char* const colon = strchr(gtest_output_flag, ':');
284  return (colon == NULL) ?
285      String(gtest_output_flag) :
286      String(gtest_output_flag, colon - gtest_output_flag);
287}
288
289// Returns the name of the requested output file, or the default if none
290// was explicitly specified.
291String UnitTestOptions::GetOutputFile() {
292  const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
293  if (gtest_output_flag == NULL)
294    return String("");
295
296  const char* const colon = strchr(gtest_output_flag, ':');
297  if (colon == NULL)
298    return String(kDefaultOutputFile);
299
300  internal::FilePath output_name(colon + 1);
301  if (!output_name.IsDirectory())
302    return output_name.ToString();
303
304  internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
305      output_name, internal::GetCurrentExecutableName(),
306      GetOutputFormat().c_str()));
307  return result.ToString();
308}
309
310// Returns true iff the wildcard pattern matches the string.  The
311// first ':' or '\0' character in pattern marks the end of it.
312//
313// This recursive algorithm isn't very efficient, but is clear and
314// works well enough for matching test names, which are short.
315bool UnitTestOptions::PatternMatchesString(const char *pattern,
316                                           const char *str) {
317  switch (*pattern) {
318    case '\0':
319    case ':':  // Either ':' or '\0' marks the end of the pattern.
320      return *str == '\0';
321    case '?':  // Matches any single character.
322      return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);
323    case '*':  // Matches any string (possibly empty) of characters.
324      return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||
325          PatternMatchesString(pattern + 1, str);
326    default:  // Non-special character.  Matches itself.
327      return *pattern == *str &&
328          PatternMatchesString(pattern + 1, str + 1);
329  }
330}
331
332bool UnitTestOptions::MatchesFilter(const String& name, const char* filter) {
333  const char *cur_pattern = filter;
334  while (true) {
335    if (PatternMatchesString(cur_pattern, name.c_str())) {
336      return true;
337    }
338
339    // Finds the next pattern in the filter.
340    cur_pattern = strchr(cur_pattern, ':');
341
342    // Returns if no more pattern can be found.
343    if (cur_pattern == NULL) {
344      return false;
345    }
346
347    // Skips the pattern separater (the ':' character).
348    cur_pattern++;
349  }
350}
351
352// TODO(keithray): move String function implementations to gtest-string.cc.
353
354// Returns true iff the user-specified filter matches the test case
355// name and the test name.
356bool UnitTestOptions::FilterMatchesTest(const String &test_case_name,
357                                        const String &test_name) {
358  const String& full_name = String::Format("%s.%s",
359                                           test_case_name.c_str(),
360                                           test_name.c_str());
361
362  // Split --gtest_filter at '-', if there is one, to separate into
363  // positive filter and negative filter portions
364  const char* const p = GTEST_FLAG(filter).c_str();
365  const char* const dash = strchr(p, '-');
366  String positive;
367  String negative;
368  if (dash == NULL) {
369    positive = GTEST_FLAG(filter).c_str();  // Whole string is a positive filter
370    negative = String("");
371  } else {
372    positive.Set(p, dash - p);       // Everything up to the dash
373    negative = String(dash+1);       // Everything after the dash
374    if (positive.empty()) {
375      // Treat '-test1' as the same as '*-test1'
376      positive = kUniversalFilter;
377    }
378  }
379
380  // A filter is a colon-separated list of patterns.  It matches a
381  // test if any pattern in it matches the test.
382  return (MatchesFilter(full_name, positive.c_str()) &&
383          !MatchesFilter(full_name, negative.c_str()));
384}
385
386#ifdef GTEST_OS_WINDOWS
387// Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
388// given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
389// This function is useful as an __except condition.
390int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
391  // Google Test should handle an exception if:
392  //   1. the user wants it to, AND
393  //   2. this is not a breakpoint exception.
394  return (GTEST_FLAG(catch_exceptions) &&
395          exception_code != EXCEPTION_BREAKPOINT) ?
396      EXCEPTION_EXECUTE_HANDLER :
397      EXCEPTION_CONTINUE_SEARCH;
398}
399#endif  // GTEST_OS_WINDOWS
400
401}  // namespace internal
402
403// The interface for printing the result of a UnitTest
404class UnitTestEventListenerInterface {
405 public:
406  // The d'tor is pure virtual as this is an abstract class.
407  virtual ~UnitTestEventListenerInterface() = 0;
408
409  // Called before the unit test starts.
410  virtual void OnUnitTestStart(const UnitTest*) {}
411
412  // Called after the unit test ends.
413  virtual void OnUnitTestEnd(const UnitTest*) {}
414
415  // Called before the test case starts.
416  virtual void OnTestCaseStart(const TestCase*) {}
417
418  // Called after the test case ends.
419  virtual void OnTestCaseEnd(const TestCase*) {}
420
421  // Called before the global set-up starts.
422  virtual void OnGlobalSetUpStart(const UnitTest*) {}
423
424  // Called after the global set-up ends.
425  virtual void OnGlobalSetUpEnd(const UnitTest*) {}
426
427  // Called before the global tear-down starts.
428  virtual void OnGlobalTearDownStart(const UnitTest*) {}
429
430  // Called after the global tear-down ends.
431  virtual void OnGlobalTearDownEnd(const UnitTest*) {}
432
433  // Called before the test starts.
434  virtual void OnTestStart(const TestInfo*) {}
435
436  // Called after the test ends.
437  virtual void OnTestEnd(const TestInfo*) {}
438
439  // Called after an assertion.
440  virtual void OnNewTestPartResult(const TestPartResult*) {}
441};
442
443// Constructs an empty TestPartResultArray.
444TestPartResultArray::TestPartResultArray()
445    : list_(new internal::List<TestPartResult>) {
446}
447
448// Destructs a TestPartResultArray.
449TestPartResultArray::~TestPartResultArray() {
450  delete list_;
451}
452
453// Appends a TestPartResult to the array.
454void TestPartResultArray::Append(const TestPartResult& result) {
455  list_->PushBack(result);
456}
457
458// Returns the TestPartResult at the given index (0-based).
459const TestPartResult& TestPartResultArray::GetTestPartResult(int index) const {
460  if (index < 0 || index >= size()) {
461    printf("\nInvalid index (%d) into TestPartResultArray.\n", index);
462    abort();
463  }
464
465  const internal::ListNode<TestPartResult>* p = list_->Head();
466  for (int i = 0; i < index; i++) {
467    p = p->next();
468  }
469
470  return p->element();
471}
472
473// Returns the number of TestPartResult objects in the array.
474int TestPartResultArray::size() const {
475  return list_->size();
476}
477
478// The c'tor sets this object as the test part result reporter used by
479// Google Test.  The 'result' parameter specifies where to report the
480// results.
481ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
482    TestPartResultArray* result)
483    : old_reporter_(UnitTest::GetInstance()->impl()->
484                    test_part_result_reporter()),
485      result_(result) {
486  internal::UnitTestImpl* const impl = UnitTest::GetInstance()->impl();
487  impl->set_test_part_result_reporter(this);
488}
489
490// The d'tor restores the test part result reporter used by Google Test
491// before.
492ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
493  UnitTest::GetInstance()->impl()->
494      set_test_part_result_reporter(old_reporter_);
495}
496
497// Increments the test part result count and remembers the result.
498// This method is from the TestPartResultReporterInterface interface.
499void ScopedFakeTestPartResultReporter::ReportTestPartResult(
500    const TestPartResult& result) {
501  result_->Append(result);
502}
503
504namespace internal {
505
506// This predicate-formatter checks that 'results' contains a test part
507// failure of the given type and that the failure message contains the
508// given substring.
509AssertionResult HasOneFailure(const char* /* results_expr */,
510                              const char* /* type_expr */,
511                              const char* /* substr_expr */,
512                              const TestPartResultArray& results,
513                              TestPartResultType type,
514                              const char* substr) {
515  const String expected(
516      type == TPRT_FATAL_FAILURE ? "1 fatal failure" :
517      "1 non-fatal failure");
518  Message msg;
519  if (results.size() != 1) {
520    msg << "Expected: " << expected << "\n"
521        << "  Actual: " << results.size() << " failures";
522    for (int i = 0; i < results.size(); i++) {
523      msg << "\n" << results.GetTestPartResult(i);
524    }
525    return AssertionFailure(msg);
526  }
527
528  const TestPartResult& r = results.GetTestPartResult(0);
529  if (r.type() != type) {
530    msg << "Expected: " << expected << "\n"
531        << "  Actual:\n"
532        << r;
533    return AssertionFailure(msg);
534  }
535
536  if (strstr(r.message(), substr) == NULL) {
537    msg << "Expected: " << expected << " containing \""
538        << substr << "\"\n"
539        << "  Actual:\n"
540        << r;
541    return AssertionFailure(msg);
542  }
543
544  return AssertionSuccess();
545}
546
547// The constructor of SingleFailureChecker remembers where to look up
548// test part results, what type of failure we expect, and what
549// substring the failure message should contain.
550SingleFailureChecker:: SingleFailureChecker(
551    const TestPartResultArray* results,
552    TestPartResultType type,
553    const char* substr)
554    : results_(results),
555      type_(type),
556      substr_(substr) {}
557
558// The destructor of SingleFailureChecker verifies that the given
559// TestPartResultArray contains exactly one failure that has the given
560// type and contains the given substring.  If that's not the case, a
561// non-fatal failure will be generated.
562SingleFailureChecker::~SingleFailureChecker() {
563  EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_.c_str());
564}
565
566// Reports a test part result.
567void UnitTestImpl::ReportTestPartResult(const TestPartResult& result) {
568  current_test_result()->AddTestPartResult(result);
569  result_printer()->OnNewTestPartResult(&result);
570}
571
572// Returns the current test part result reporter.
573TestPartResultReporterInterface* UnitTestImpl::test_part_result_reporter() {
574  return test_part_result_reporter_;
575}
576
577// Sets the current test part result reporter.
578void UnitTestImpl::set_test_part_result_reporter(
579    TestPartResultReporterInterface* reporter) {
580  test_part_result_reporter_ = reporter;
581}
582
583// Gets the number of successful test cases.
584int UnitTestImpl::successful_test_case_count() const {
585  return test_cases_.CountIf(TestCasePassed);
586}
587
588// Gets the number of failed test cases.
589int UnitTestImpl::failed_test_case_count() const {
590  return test_cases_.CountIf(TestCaseFailed);
591}
592
593// Gets the number of all test cases.
594int UnitTestImpl::total_test_case_count() const {
595  return test_cases_.size();
596}
597
598// Gets the number of all test cases that contain at least one test
599// that should run.
600int UnitTestImpl::test_case_to_run_count() const {
601  return test_cases_.CountIf(ShouldRunTestCase);
602}
603
604// Gets the number of successful tests.
605int UnitTestImpl::successful_test_count() const {
606  return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count);
607}
608
609// Gets the number of failed tests.
610int UnitTestImpl::failed_test_count() const {
611  return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count);
612}
613
614// Gets the number of disabled tests.
615int UnitTestImpl::disabled_test_count() const {
616  return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count);
617}
618
619// Gets the number of all tests.
620int UnitTestImpl::total_test_count() const {
621  return SumOverTestCaseList(test_cases_, &TestCase::total_test_count);
622}
623
624// Gets the number of tests that should run.
625int UnitTestImpl::test_to_run_count() const {
626  return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count);
627}
628
629// Returns the current OS stack trace as a String.
630//
631// The maximum number of stack frames to be included is specified by
632// the gtest_stack_trace_depth flag.  The skip_count parameter
633// specifies the number of top frames to be skipped, which doesn't
634// count against the number of frames to be included.
635//
636// For example, if Foo() calls Bar(), which in turn calls
637// CurrentOsStackTraceExceptTop(1), Foo() will be included in the
638// trace but Bar() and CurrentOsStackTraceExceptTop() won't.
639String UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
640  (void)skip_count;
641  return String("");
642}
643
644static TimeInMillis GetTimeInMillis() {
645#ifdef _WIN32_WCE  // We are on Windows CE
646  // Difference between 1970-01-01 and 1601-01-01 in miliseconds.
647  // http://analogous.blogspot.com/2005/04/epoch.html
648  const TimeInMillis kJavaEpochToWinFileTimeDelta = 11644473600000UL;
649  const DWORD kTenthMicrosInMilliSecond = 10000;
650
651  SYSTEMTIME now_systime;
652  FILETIME now_filetime;
653  ULARGE_INTEGER now_int64;
654  // TODO(kenton@google.com): Shouldn't this just use
655  //   GetSystemTimeAsFileTime()?
656  GetSystemTime(&now_systime);
657  if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
658    now_int64.LowPart = now_filetime.dwLowDateTime;
659    now_int64.HighPart = now_filetime.dwHighDateTime;
660    now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
661      kJavaEpochToWinFileTimeDelta;
662    return now_int64.QuadPart;
663  }
664  return 0;
665#elif defined(_WIN32) && !defined(GTEST_HAS_GETTIMEOFDAY)
666  __timeb64 now;
667#ifdef _MSC_VER
668  // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996
669  // (deprecated function) there.
670  // TODO(kenton@google.com): Use GetTickCount()?  Or use
671  //   SystemTimeToFileTime()
672#pragma warning(push)          // Saves the current warning state.
673#pragma warning(disable:4996)  // Temporarily disables warning 4996.
674  _ftime64(&now);
675#pragma warning(pop)           // Restores the warning state.
676#else
677  _ftime64(&now);
678#endif  // _MSC_VER
679  return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
680#elif defined(GTEST_HAS_GETTIMEOFDAY)
681  struct timeval now;
682  gettimeofday(&now, NULL);
683  return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
684#else
685#error "Don't know how to get the current time on your system."
686#endif
687}
688
689// Utilities
690
691// class String
692
693// Returns the input enclosed in double quotes if it's not NULL;
694// otherwise returns "(null)".  For example, "\"Hello\"" is returned
695// for input "Hello".
696//
697// This is useful for printing a C string in the syntax of a literal.
698//
699// Known issue: escape sequences are not handled yet.
700String String::ShowCStringQuoted(const char* c_str) {
701  return c_str ? String::Format("\"%s\"", c_str) : String("(null)");
702}
703
704// Copies at most length characters from str into a newly-allocated
705// piece of memory of size length+1.  The memory is allocated with new[].
706// A terminating null byte is written to the memory, and a pointer to it
707// is returned.  If str is NULL, NULL is returned.
708static char* CloneString(const char* str, size_t length) {
709  if (str == NULL) {
710    return NULL;
711  } else {
712    char* const clone = new char[length + 1];
713    // MSVC 8 deprecates strncpy(), so we want to suppress warning
714    // 4996 (deprecated function) there.
715#ifdef GTEST_OS_WINDOWS  // We are on Windows.
716#pragma warning(push)          // Saves the current warning state.
717#pragma warning(disable:4996)  // Temporarily disables warning 4996.
718    strncpy(clone, str, length);
719#pragma warning(pop)           // Restores the warning state.
720#else  // We are on Linux or Mac OS.
721    strncpy(clone, str, length);
722#endif  // GTEST_OS_WINDOWS
723    clone[length] = '\0';
724    return clone;
725  }
726}
727
728// Clones a 0-terminated C string, allocating memory using new.  The
729// caller is responsible for deleting[] the return value.  Returns the
730// cloned string, or NULL if the input is NULL.
731const char * String::CloneCString(const char* c_str) {
732  return (c_str == NULL) ?
733                    NULL : CloneString(c_str, strlen(c_str));
734}
735
736// Compares two C strings.  Returns true iff they have the same content.
737//
738// Unlike strcmp(), this function can handle NULL argument(s).  A NULL
739// C string is considered different to any non-NULL C string,
740// including the empty string.
741bool String::CStringEquals(const char * lhs, const char * rhs) {
742  if ( lhs == NULL ) return rhs == NULL;
743
744  if ( rhs == NULL ) return false;
745
746  return strcmp(lhs, rhs) == 0;
747}
748
749#if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
750
751// Converts an array of wide chars to a narrow string using the UTF-8
752// encoding, and streams the result to the given Message object.
753static void StreamWideCharsToMessage(const wchar_t* wstr, size_t len,
754                                     Message* msg) {
755  for (size_t i = 0; i != len; i++) {
756    // TODO(wan): consider allowing a testing::String object to
757    // contain '\0'.  This will make it behave more like std::string,
758    // and will allow ToUtf8String() to return the correct encoding
759    // for '\0' s.t. we can get rid of the conditional here (and in
760    // several other places).
761    if (wstr[i]) {
762      *msg << internal::ToUtf8String(wstr[i]);
763    } else {
764      *msg << '\0';
765    }
766  }
767}
768
769#endif  // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
770
771}  // namespace internal
772
773#if GTEST_HAS_STD_WSTRING
774// Converts the given wide string to a narrow string using the UTF-8
775// encoding, and streams the result to this Message object.
776Message& Message::operator <<(const ::std::wstring& wstr) {
777  internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
778  return *this;
779}
780#endif  // GTEST_HAS_STD_WSTRING
781
782#if GTEST_HAS_GLOBAL_WSTRING
783// Converts the given wide string to a narrow string using the UTF-8
784// encoding, and streams the result to this Message object.
785Message& Message::operator <<(const ::wstring& wstr) {
786  internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
787  return *this;
788}
789#endif  // GTEST_HAS_GLOBAL_WSTRING
790
791namespace internal {
792
793// Formats a value to be used in a failure message.
794
795// For a char value, we print it as a C++ char literal and as an
796// unsigned integer (both in decimal and in hexadecimal).
797String FormatForFailureMessage(char ch) {
798  const unsigned int ch_as_uint = ch;
799  // A String object cannot contain '\0', so we print "\\0" when ch is
800  // '\0'.
801  return String::Format("'%s' (%u, 0x%X)",
802                        ch ? String::Format("%c", ch).c_str() : "\\0",
803                        ch_as_uint, ch_as_uint);
804}
805
806// For a wchar_t value, we print it as a C++ wchar_t literal and as an
807// unsigned integer (both in decimal and in hexidecimal).
808String FormatForFailureMessage(wchar_t wchar) {
809  // The C++ standard doesn't specify the exact size of the wchar_t
810  // type.  It just says that it shall have the same size as another
811  // integral type, called its underlying type.
812  //
813  // Therefore, in order to print a wchar_t value in the numeric form,
814  // we first convert it to the largest integral type (UInt64) and
815  // then print the converted value.
816  //
817  // We use streaming to print the value as "%llu" doesn't work
818  // correctly with MSVC 7.1.
819  const UInt64 wchar_as_uint64 = wchar;
820  Message msg;
821  // A String object cannot contain '\0', so we print "\\0" when wchar is
822  // L'\0'.
823  msg << "L'" << (wchar ? ToUtf8String(wchar).c_str() : "\\0") << "' ("
824      << wchar_as_uint64 << ", 0x" << ::std::setbase(16)
825      << wchar_as_uint64 << ")";
826  return msg.GetString();
827}
828
829}  // namespace internal
830
831// AssertionResult constructor.
832AssertionResult::AssertionResult(const internal::String& failure_message)
833    : failure_message_(failure_message) {
834}
835
836
837// Makes a successful assertion result.
838AssertionResult AssertionSuccess() {
839  return AssertionResult();
840}
841
842
843// Makes a failed assertion result with the given failure message.
844AssertionResult AssertionFailure(const Message& message) {
845  return AssertionResult(message.GetString());
846}
847
848namespace internal {
849
850// Constructs and returns the message for an equality assertion
851// (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
852//
853// The first four parameters are the expressions used in the assertion
854// and their values, as strings.  For example, for ASSERT_EQ(foo, bar)
855// where foo is 5 and bar is 6, we have:
856//
857//   expected_expression: "foo"
858//   actual_expression:   "bar"
859//   expected_value:      "5"
860//   actual_value:        "6"
861//
862// The ignoring_case parameter is true iff the assertion is a
863// *_STRCASEEQ*.  When it's true, the string " (ignoring case)" will
864// be inserted into the message.
865AssertionResult EqFailure(const char* expected_expression,
866                          const char* actual_expression,
867                          const String& expected_value,
868                          const String& actual_value,
869                          bool ignoring_case) {
870  Message msg;
871  msg << "Value of: " << actual_expression;
872  if (actual_value != actual_expression) {
873    msg << "\n  Actual: " << actual_value;
874  }
875
876  msg << "\nExpected: " << expected_expression;
877  if (ignoring_case) {
878    msg << " (ignoring case)";
879  }
880  if (expected_value != expected_expression) {
881    msg << "\nWhich is: " << expected_value;
882  }
883
884  return AssertionFailure(msg);
885}
886
887
888// Helper function for implementing ASSERT_NEAR.
889AssertionResult DoubleNearPredFormat(const char* expr1,
890                                     const char* expr2,
891                                     const char* abs_error_expr,
892                                     double val1,
893                                     double val2,
894                                     double abs_error) {
895  const double diff = fabs(val1 - val2);
896  if (diff <= abs_error) return AssertionSuccess();
897
898  // TODO(wan): do not print the value of an expression if it's
899  // already a literal.
900  Message msg;
901  msg << "The difference between " << expr1 << " and " << expr2
902      << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"
903      << expr1 << " evaluates to " << val1 << ",\n"
904      << expr2 << " evaluates to " << val2 << ", and\n"
905      << abs_error_expr << " evaluates to " << abs_error << ".";
906  return AssertionFailure(msg);
907}
908
909
910// Helper template for implementing FloatLE() and DoubleLE().
911template <typename RawType>
912AssertionResult FloatingPointLE(const char* expr1,
913                                const char* expr2,
914                                RawType val1,
915                                RawType val2) {
916  // Returns success if val1 is less than val2,
917  if (val1 < val2) {
918    return AssertionSuccess();
919  }
920
921  // or if val1 is almost equal to val2.
922  const FloatingPoint<RawType> lhs(val1), rhs(val2);
923  if (lhs.AlmostEquals(rhs)) {
924    return AssertionSuccess();
925  }
926
927  // Note that the above two checks will both fail if either val1 or
928  // val2 is NaN, as the IEEE floating-point standard requires that
929  // any predicate involving a NaN must return false.
930
931  StrStream val1_ss;
932  val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
933          << val1;
934
935  StrStream val2_ss;
936  val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
937          << val2;
938
939  Message msg;
940  msg << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
941      << "  Actual: " << StrStreamToString(&val1_ss) << " vs "
942      << StrStreamToString(&val2_ss);
943
944  return AssertionFailure(msg);
945}
946
947}  // namespace internal
948
949// Asserts that val1 is less than, or almost equal to, val2.  Fails
950// otherwise.  In particular, it fails if either val1 or val2 is NaN.
951AssertionResult FloatLE(const char* expr1, const char* expr2,
952                        float val1, float val2) {
953  return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
954}
955
956// Asserts that val1 is less than, or almost equal to, val2.  Fails
957// otherwise.  In particular, it fails if either val1 or val2 is NaN.
958AssertionResult DoubleLE(const char* expr1, const char* expr2,
959                         double val1, double val2) {
960  return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
961}
962
963namespace internal {
964
965// The helper function for {ASSERT|EXPECT}_EQ with int or enum
966// arguments.
967AssertionResult CmpHelperEQ(const char* expected_expression,
968                            const char* actual_expression,
969                            BiggestInt expected,
970                            BiggestInt actual) {
971  if (expected == actual) {
972    return AssertionSuccess();
973  }
974
975  return EqFailure(expected_expression,
976                   actual_expression,
977                   FormatForComparisonFailureMessage(expected, actual),
978                   FormatForComparisonFailureMessage(actual, expected),
979                   false);
980}
981
982// A macro for implementing the helper functions needed to implement
983// ASSERT_?? and EXPECT_?? with integer or enum arguments.  It is here
984// just to avoid copy-and-paste of similar code.
985#define GTEST_IMPL_CMP_HELPER(op_name, op)\
986AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
987                                   BiggestInt val1, BiggestInt val2) {\
988  if (val1 op val2) {\
989    return AssertionSuccess();\
990  } else {\
991    Message msg;\
992    msg << "Expected: (" << expr1 << ") " #op " (" << expr2\
993        << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
994        << " vs " << FormatForComparisonFailureMessage(val2, val1);\
995    return AssertionFailure(msg);\
996  }\
997}
998
999// Implements the helper function for {ASSERT|EXPECT}_NE with int or
1000// enum arguments.
1001GTEST_IMPL_CMP_HELPER(NE, !=)
1002// Implements the helper function for {ASSERT|EXPECT}_LE with int or
1003// enum arguments.
1004GTEST_IMPL_CMP_HELPER(LE, <=)
1005// Implements the helper function for {ASSERT|EXPECT}_LT with int or
1006// enum arguments.
1007GTEST_IMPL_CMP_HELPER(LT, < )
1008// Implements the helper function for {ASSERT|EXPECT}_GE with int or
1009// enum arguments.
1010GTEST_IMPL_CMP_HELPER(GE, >=)
1011// Implements the helper function for {ASSERT|EXPECT}_GT with int or
1012// enum arguments.
1013GTEST_IMPL_CMP_HELPER(GT, > )
1014
1015#undef GTEST_IMPL_CMP_HELPER
1016
1017// The helper function for {ASSERT|EXPECT}_STREQ.
1018AssertionResult CmpHelperSTREQ(const char* expected_expression,
1019                               const char* actual_expression,
1020                               const char* expected,
1021                               const char* actual) {
1022  if (String::CStringEquals(expected, actual)) {
1023    return AssertionSuccess();
1024  }
1025
1026  return EqFailure(expected_expression,
1027                   actual_expression,
1028                   String::ShowCStringQuoted(expected),
1029                   String::ShowCStringQuoted(actual),
1030                   false);
1031}
1032
1033// The helper function for {ASSERT|EXPECT}_STRCASEEQ.
1034AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression,
1035                                   const char* actual_expression,
1036                                   const char* expected,
1037                                   const char* actual) {
1038  if (String::CaseInsensitiveCStringEquals(expected, actual)) {
1039    return AssertionSuccess();
1040  }
1041
1042  return EqFailure(expected_expression,
1043                   actual_expression,
1044                   String::ShowCStringQuoted(expected),
1045                   String::ShowCStringQuoted(actual),
1046                   true);
1047}
1048
1049// The helper function for {ASSERT|EXPECT}_STRNE.
1050AssertionResult CmpHelperSTRNE(const char* s1_expression,
1051                               const char* s2_expression,
1052                               const char* s1,
1053                               const char* s2) {
1054  if (!String::CStringEquals(s1, s2)) {
1055    return AssertionSuccess();
1056  } else {
1057    Message msg;
1058    msg << "Expected: (" << s1_expression << ") != ("
1059        << s2_expression << "), actual: \""
1060        << s1 << "\" vs \"" << s2 << "\"";
1061    return AssertionFailure(msg);
1062  }
1063}
1064
1065// The helper function for {ASSERT|EXPECT}_STRCASENE.
1066AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
1067                                   const char* s2_expression,
1068                                   const char* s1,
1069                                   const char* s2) {
1070  if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
1071    return AssertionSuccess();
1072  } else {
1073    Message msg;
1074    msg << "Expected: (" << s1_expression << ") != ("
1075        << s2_expression << ") (ignoring case), actual: \""
1076        << s1 << "\" vs \"" << s2 << "\"";
1077    return AssertionFailure(msg);
1078  }
1079}
1080
1081}  // namespace internal
1082
1083namespace {
1084
1085// Helper functions for implementing IsSubString() and IsNotSubstring().
1086
1087// This group of overloaded functions return true iff needle is a
1088// substring of haystack.  NULL is considered a substring of itself
1089// only.
1090
1091bool IsSubstringPred(const char* needle, const char* haystack) {
1092  if (needle == NULL || haystack == NULL)
1093    return needle == haystack;
1094
1095  return strstr(haystack, needle) != NULL;
1096}
1097
1098bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
1099  if (needle == NULL || haystack == NULL)
1100    return needle == haystack;
1101
1102  return wcsstr(haystack, needle) != NULL;
1103}
1104
1105// StringType here can be either ::std::string or ::std::wstring.
1106template <typename StringType>
1107bool IsSubstringPred(const StringType& needle,
1108                     const StringType& haystack) {
1109  return haystack.find(needle) != StringType::npos;
1110}
1111
1112// This function implements either IsSubstring() or IsNotSubstring(),
1113// depending on the value of the expected_to_be_substring parameter.
1114// StringType here can be const char*, const wchar_t*, ::std::string,
1115// or ::std::wstring.
1116template <typename StringType>
1117AssertionResult IsSubstringImpl(
1118    bool expected_to_be_substring,
1119    const char* needle_expr, const char* haystack_expr,
1120    const StringType& needle, const StringType& haystack) {
1121  if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
1122    return AssertionSuccess();
1123
1124  const bool is_wide_string = sizeof(needle[0]) > 1;
1125  const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
1126  return AssertionFailure(
1127      Message()
1128      << "Value of: " << needle_expr << "\n"
1129      << "  Actual: " << begin_string_quote << needle << "\"\n"
1130      << "Expected: " << (expected_to_be_substring ? "" : "not ")
1131      << "a substring of " << haystack_expr << "\n"
1132      << "Which is: " << begin_string_quote << haystack << "\"");
1133}
1134
1135}  // namespace
1136
1137// IsSubstring() and IsNotSubstring() check whether needle is a
1138// substring of haystack (NULL is considered a substring of itself
1139// only), and return an appropriate error message when they fail.
1140
1141AssertionResult IsSubstring(
1142    const char* needle_expr, const char* haystack_expr,
1143    const char* needle, const char* haystack) {
1144  return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1145}
1146
1147AssertionResult IsSubstring(
1148    const char* needle_expr, const char* haystack_expr,
1149    const wchar_t* needle, const wchar_t* haystack) {
1150  return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1151}
1152
1153AssertionResult IsNotSubstring(
1154    const char* needle_expr, const char* haystack_expr,
1155    const char* needle, const char* haystack) {
1156  return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1157}
1158
1159AssertionResult IsNotSubstring(
1160    const char* needle_expr, const char* haystack_expr,
1161    const wchar_t* needle, const wchar_t* haystack) {
1162  return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1163}
1164
1165#if GTEST_HAS_STD_STRING
1166AssertionResult IsSubstring(
1167    const char* needle_expr, const char* haystack_expr,
1168    const ::std::string& needle, const ::std::string& haystack) {
1169  return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1170}
1171
1172AssertionResult IsNotSubstring(
1173    const char* needle_expr, const char* haystack_expr,
1174    const ::std::string& needle, const ::std::string& haystack) {
1175  return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1176}
1177#endif  // GTEST_HAS_STD_STRING
1178
1179#if GTEST_HAS_STD_WSTRING
1180AssertionResult IsSubstring(
1181    const char* needle_expr, const char* haystack_expr,
1182    const ::std::wstring& needle, const ::std::wstring& haystack) {
1183  return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1184}
1185
1186AssertionResult IsNotSubstring(
1187    const char* needle_expr, const char* haystack_expr,
1188    const ::std::wstring& needle, const ::std::wstring& haystack) {
1189  return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1190}
1191#endif  // GTEST_HAS_STD_WSTRING
1192
1193namespace internal {
1194
1195#ifdef GTEST_OS_WINDOWS
1196
1197namespace {
1198
1199// Helper function for IsHRESULT{SuccessFailure} predicates
1200AssertionResult HRESULTFailureHelper(const char* expr,
1201                                     const char* expected,
1202                                     long hr) {  // NOLINT
1203#ifdef _WIN32_WCE
1204  // Windows CE doesn't support FormatMessage.
1205  const char error_text[] = "";
1206#else
1207  // Looks up the human-readable system message for the HRESULT code
1208  // and since we're not passing any params to FormatMessage, we don't
1209  // want inserts expanded.
1210  const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
1211                       FORMAT_MESSAGE_IGNORE_INSERTS;
1212  const DWORD kBufSize = 4096;  // String::Format can't exceed this length.
1213  // Gets the system's human readable message string for this HRESULT.
1214  char error_text[kBufSize] = { '\0' };
1215  DWORD message_length = ::FormatMessageA(kFlags,
1216                                          0,  // no source, we're asking system
1217                                          hr,  // the error
1218                                          0,  // no line width restrictions
1219                                          error_text,  // output buffer
1220                                          kBufSize,  // buf size
1221                                          NULL);  // no arguments for inserts
1222  // Trims tailing white space (FormatMessage leaves a trailing cr-lf)
1223  for (; message_length && isspace(error_text[message_length - 1]);
1224          --message_length) {
1225    error_text[message_length - 1] = '\0';
1226  }
1227#endif  // _WIN32_WCE
1228
1229  const String error_hex(String::Format("0x%08X ", hr));
1230  Message msg;
1231  msg << "Expected: " << expr << " " << expected << ".\n"
1232      << "  Actual: " << error_hex << error_text << "\n";
1233
1234  return ::testing::AssertionFailure(msg);
1235}
1236
1237}  // namespace
1238
1239AssertionResult IsHRESULTSuccess(const char* expr, long hr) {  // NOLINT
1240  if (SUCCEEDED(hr)) {
1241    return AssertionSuccess();
1242  }
1243  return HRESULTFailureHelper(expr, "succeeds", hr);
1244}
1245
1246AssertionResult IsHRESULTFailure(const char* expr, long hr) {  // NOLINT
1247  if (FAILED(hr)) {
1248    return AssertionSuccess();
1249  }
1250  return HRESULTFailureHelper(expr, "fails", hr);
1251}
1252
1253#endif  // GTEST_OS_WINDOWS
1254
1255// Utility functions for encoding Unicode text (wide strings) in
1256// UTF-8.
1257
1258// A Unicode code-point can have upto 21 bits, and is encoded in UTF-8
1259// like this:
1260//
1261// Code-point length   Encoding
1262//   0 -  7 bits       0xxxxxxx
1263//   8 - 11 bits       110xxxxx 10xxxxxx
1264//  12 - 16 bits       1110xxxx 10xxxxxx 10xxxxxx
1265//  17 - 21 bits       11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
1266
1267// The maximum code-point a one-byte UTF-8 sequence can represent.
1268const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) <<  7) - 1;
1269
1270// The maximum code-point a two-byte UTF-8 sequence can represent.
1271const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1;
1272
1273// The maximum code-point a three-byte UTF-8 sequence can represent.
1274const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2*6)) - 1;
1275
1276// The maximum code-point a four-byte UTF-8 sequence can represent.
1277const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3*6)) - 1;
1278
1279// Chops off the n lowest bits from a bit pattern.  Returns the n
1280// lowest bits.  As a side effect, the original bit pattern will be
1281// shifted to the right by n bits.
1282inline UInt32 ChopLowBits(UInt32* bits, int n) {
1283  const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1);
1284  *bits >>= n;
1285  return low_bits;
1286}
1287
1288// Converts a Unicode code-point to its UTF-8 encoding.
1289String ToUtf8String(wchar_t wchar) {
1290  char str[5] = {};  // Initializes str to all '\0' characters.
1291
1292  UInt32 code = static_cast<UInt32>(wchar);
1293  if (code <= kMaxCodePoint1) {
1294    str[0] = static_cast<char>(code);                          // 0xxxxxxx
1295  } else if (code <= kMaxCodePoint2) {
1296    str[1] = static_cast<char>(0x80 | ChopLowBits(&code, 6));  // 10xxxxxx
1297    str[0] = static_cast<char>(0xC0 | code);                   // 110xxxxx
1298  } else if (code <= kMaxCodePoint3) {
1299    str[2] = static_cast<char>(0x80 | ChopLowBits(&code, 6));  // 10xxxxxx
1300    str[1] = static_cast<char>(0x80 | ChopLowBits(&code, 6));  // 10xxxxxx
1301    str[0] = static_cast<char>(0xE0 | code);                   // 1110xxxx
1302  } else if (code <= kMaxCodePoint4) {
1303    str[3] = static_cast<char>(0x80 | ChopLowBits(&code, 6));  // 10xxxxxx
1304    str[2] = static_cast<char>(0x80 | ChopLowBits(&code, 6));  // 10xxxxxx
1305    str[1] = static_cast<char>(0x80 | ChopLowBits(&code, 6));  // 10xxxxxx
1306    str[0] = static_cast<char>(0xF0 | code);                   // 11110xxx
1307  } else {
1308    return String::Format("(Invalid Unicode 0x%llX)",
1309                          static_cast<UInt64>(wchar));
1310  }
1311
1312  return String(str);
1313}
1314
1315// Converts a wide C string to a String using the UTF-8 encoding.
1316// NULL will be converted to "(null)".
1317String String::ShowWideCString(const wchar_t * wide_c_str) {
1318  if (wide_c_str == NULL) return String("(null)");
1319
1320  StrStream ss;
1321  while (*wide_c_str) {
1322    ss << internal::ToUtf8String(*wide_c_str++);
1323  }
1324
1325  return internal::StrStreamToString(&ss);
1326}
1327
1328// Similar to ShowWideCString(), except that this function encloses
1329// the converted string in double quotes.
1330String String::ShowWideCStringQuoted(const wchar_t* wide_c_str) {
1331  if (wide_c_str == NULL) return String("(null)");
1332
1333  return String::Format("L\"%s\"",
1334                        String::ShowWideCString(wide_c_str).c_str());
1335}
1336
1337// Compares two wide C strings.  Returns true iff they have the same
1338// content.
1339//
1340// Unlike wcscmp(), this function can handle NULL argument(s).  A NULL
1341// C string is considered different to any non-NULL C string,
1342// including the empty string.
1343bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {
1344  if (lhs == NULL) return rhs == NULL;
1345
1346  if (rhs == NULL) return false;
1347
1348  return wcscmp(lhs, rhs) == 0;
1349}
1350
1351// Helper function for *_STREQ on wide strings.
1352AssertionResult CmpHelperSTREQ(const char* expected_expression,
1353                               const char* actual_expression,
1354                               const wchar_t* expected,
1355                               const wchar_t* actual) {
1356  if (String::WideCStringEquals(expected, actual)) {
1357    return AssertionSuccess();
1358  }
1359
1360  return EqFailure(expected_expression,
1361                   actual_expression,
1362                   String::ShowWideCStringQuoted(expected),
1363                   String::ShowWideCStringQuoted(actual),
1364                   false);
1365}
1366
1367// Helper function for *_STRNE on wide strings.
1368AssertionResult CmpHelperSTRNE(const char* s1_expression,
1369                               const char* s2_expression,
1370                               const wchar_t* s1,
1371                               const wchar_t* s2) {
1372  if (!String::WideCStringEquals(s1, s2)) {
1373    return AssertionSuccess();
1374  }
1375
1376  Message msg;
1377  msg << "Expected: (" << s1_expression << ") != ("
1378      << s2_expression << "), actual: "
1379      << String::ShowWideCStringQuoted(s1)
1380      << " vs " << String::ShowWideCStringQuoted(s2);
1381  return AssertionFailure(msg);
1382}
1383
1384// Compares two C strings, ignoring case.  Returns true iff they have
1385// the same content.
1386//
1387// Unlike strcasecmp(), this function can handle NULL argument(s).  A
1388// NULL C string is considered different to any non-NULL C string,
1389// including the empty string.
1390bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) {
1391  if ( lhs == NULL ) return rhs == NULL;
1392
1393  if ( rhs == NULL ) return false;
1394
1395#ifdef GTEST_OS_WINDOWS
1396  return _stricmp(lhs, rhs) == 0;
1397#else  // GTEST_OS_WINDOWS
1398  return strcasecmp(lhs, rhs) == 0;
1399#endif  // GTEST_OS_WINDOWS
1400}
1401
1402// Constructs a String by copying a given number of chars from a
1403// buffer.  E.g. String("hello", 3) will create the string "hel".
1404String::String(const char * buffer, size_t len) {
1405  char * const temp = new char[ len + 1 ];
1406  memcpy(temp, buffer, len);
1407  temp[ len ] = '\0';
1408  c_str_ = temp;
1409}
1410
1411// Compares this with another String.
1412// Returns < 0 if this is less than rhs, 0 if this is equal to rhs, or > 0
1413// if this is greater than rhs.
1414int String::Compare(const String & rhs) const {
1415  if ( c_str_ == NULL ) {
1416    return rhs.c_str_ == NULL ? 0 : -1;  // NULL < anything except NULL
1417  }
1418
1419  return rhs.c_str_ == NULL ? 1 : strcmp(c_str_, rhs.c_str_);
1420}
1421
1422// Returns true iff this String ends with the given suffix.  *Any*
1423// String is considered to end with a NULL or empty suffix.
1424bool String::EndsWith(const char* suffix) const {
1425  if (suffix == NULL || CStringEquals(suffix, "")) return true;
1426
1427  if (c_str_ == NULL) return false;
1428
1429  const size_t this_len = strlen(c_str_);
1430  const size_t suffix_len = strlen(suffix);
1431  return (this_len >= suffix_len) &&
1432         CStringEquals(c_str_ + this_len - suffix_len, suffix);
1433}
1434
1435// Returns true iff this String ends with the given suffix, ignoring case.
1436// Any String is considered to end with a NULL or empty suffix.
1437bool String::EndsWithCaseInsensitive(const char* suffix) const {
1438  if (suffix == NULL || CStringEquals(suffix, "")) return true;
1439
1440  if (c_str_ == NULL) return false;
1441
1442  const size_t this_len = strlen(c_str_);
1443  const size_t suffix_len = strlen(suffix);
1444  return (this_len >= suffix_len) &&
1445         CaseInsensitiveCStringEquals(c_str_ + this_len - suffix_len, suffix);
1446}
1447
1448// Sets the 0-terminated C string this String object represents.  The
1449// old string in this object is deleted, and this object will own a
1450// clone of the input string.  This function copies only up to length
1451// bytes (plus a terminating null byte), or until the first null byte,
1452// whichever comes first.
1453//
1454// This function works even when the c_str parameter has the same
1455// value as that of the c_str_ field.
1456void String::Set(const char * c_str, size_t length) {
1457  // Makes sure this works when c_str == c_str_
1458  const char* const temp = CloneString(c_str, length);
1459  delete[] c_str_;
1460  c_str_ = temp;
1461}
1462
1463// Assigns a C string to this object.  Self-assignment works.
1464const String& String::operator=(const char* c_str) {
1465  // Makes sure this works when c_str == c_str_
1466  if (c_str != c_str_) {
1467    delete[] c_str_;
1468    c_str_ = CloneCString(c_str);
1469  }
1470  return *this;
1471}
1472
1473// Formats a list of arguments to a String, using the same format
1474// spec string as for printf.
1475//
1476// We do not use the StringPrintf class as it is not universally
1477// available.
1478//
1479// The result is limited to 4096 characters (including the tailing 0).
1480// If 4096 characters are not enough to format the input,
1481// "<buffer exceeded>" is returned.
1482String String::Format(const char * format, ...) {
1483  va_list args;
1484  va_start(args, format);
1485
1486  char buffer[4096];
1487  // MSVC 8 deprecates vsnprintf(), so we want to suppress warning
1488  // 4996 (deprecated function) there.
1489#ifdef GTEST_OS_WINDOWS  // We are on Windows.
1490#pragma warning(push)          // Saves the current warning state.
1491#pragma warning(disable:4996)  // Temporarily disables warning 4996.
1492  const int size =
1493    vsnprintf(buffer, sizeof(buffer)/sizeof(buffer[0]) - 1, format, args);
1494#pragma warning(pop)           // Restores the warning state.
1495#else  // We are on Linux or Mac OS.
1496  const int size =
1497    vsnprintf(buffer, sizeof(buffer)/sizeof(buffer[0]) - 1, format, args);
1498#endif  // GTEST_OS_WINDOWS
1499  va_end(args);
1500
1501  return String(size >= 0 ? buffer : "<buffer exceeded>");
1502}
1503
1504// Converts the buffer in a StrStream to a String, converting NUL
1505// bytes to "\\0" along the way.
1506String StrStreamToString(StrStream* ss) {
1507#if GTEST_HAS_STD_STRING
1508  const ::std::string& str = ss->str();
1509  const char* const start = str.c_str();
1510  const char* const end = start + str.length();
1511#else
1512  const char* const start = ss->str();
1513  const char* const end = start + ss->pcount();
1514#endif  // GTEST_HAS_STD_STRING
1515
1516  // We need to use a helper StrStream to do this transformation
1517  // because String doesn't support push_back().
1518  StrStream helper;
1519  for (const char* ch = start; ch != end; ++ch) {
1520    if (*ch == '\0') {
1521      helper << "\\0";  // Replaces NUL with "\\0";
1522    } else {
1523      helper.put(*ch);
1524    }
1525  }
1526
1527#if GTEST_HAS_STD_STRING
1528  return String(helper.str().c_str());
1529#else
1530  const String str(helper.str(), helper.pcount());
1531  helper.freeze(false);
1532  ss->freeze(false);
1533  return str;
1534#endif  // GTEST_HAS_STD_STRING
1535}
1536
1537// Appends the user-supplied message to the Google-Test-generated message.
1538String AppendUserMessage(const String& gtest_msg,
1539                         const Message& user_msg) {
1540  // Appends the user message if it's non-empty.
1541  const String user_msg_string = user_msg.GetString();
1542  if (user_msg_string.empty()) {
1543    return gtest_msg;
1544  }
1545
1546  Message msg;
1547  msg << gtest_msg << "\n" << user_msg_string;
1548
1549  return msg.GetString();
1550}
1551
1552}  // namespace internal
1553
1554// Prints a TestPartResult object.
1555std::ostream& operator<<(std::ostream& os, const TestPartResult& result) {
1556  return os << result.file_name() << ":"
1557            << result.line_number() << ": "
1558            << (result.type() == TPRT_SUCCESS ? "Success" :
1559                result.type() == TPRT_FATAL_FAILURE ? "Fatal failure" :
1560                "Non-fatal failure") << ":\n"
1561            << result.message() << std::endl;
1562}
1563
1564namespace internal {
1565// class TestResult
1566
1567// Creates an empty TestResult.
1568TestResult::TestResult()
1569    : death_test_count_(0),
1570      elapsed_time_(0) {
1571}
1572
1573// D'tor.
1574TestResult::~TestResult() {
1575}
1576
1577// Adds a test part result to the list.
1578void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
1579  test_part_results_.PushBack(test_part_result);
1580}
1581
1582// Adds a test property to the list. If a property with the same key as the
1583// supplied property is already represented, the value of this test_property
1584// replaces the old value for that key.
1585void TestResult::RecordProperty(const TestProperty& test_property) {
1586  if (!ValidateTestProperty(test_property)) {
1587    return;
1588  }
1589  MutexLock lock(&test_properites_mutex_);
1590  ListNode<TestProperty>* const node_with_matching_key =
1591      test_properties_.FindIf(TestPropertyKeyIs(test_property.key()));
1592  if (node_with_matching_key == NULL) {
1593    test_properties_.PushBack(test_property);
1594    return;
1595  }
1596  TestProperty& property_with_matching_key = node_with_matching_key->element();
1597  property_with_matching_key.SetValue(test_property.value());
1598}
1599
1600// Adds a failure if the key is a reserved attribute of Google Test testcase tags.
1601// Returns true if the property is valid.
1602bool TestResult::ValidateTestProperty(const TestProperty& test_property) {
1603  String key(test_property.key());
1604  if (key == "name" || key == "status" || key == "time" || key == "classname") {
1605    ADD_FAILURE()
1606        << "Reserved key used in RecordProperty(): "
1607        << key
1608        << " ('name', 'status', 'time', and 'classname' are reserved by "
1609        << GTEST_NAME << ")";
1610    return false;
1611  }
1612  return true;
1613}
1614
1615// Clears the object.
1616void TestResult::Clear() {
1617  test_part_results_.Clear();
1618  test_properties_.Clear();
1619  death_test_count_ = 0;
1620  elapsed_time_ = 0;
1621}
1622
1623// Returns true iff the test part passed.
1624static bool TestPartPassed(const TestPartResult & result) {
1625  return result.passed();
1626}
1627
1628// Gets the number of successful test parts.
1629int TestResult::successful_part_count() const {
1630  return test_part_results_.CountIf(TestPartPassed);
1631}
1632
1633// Returns true iff the test part failed.
1634static bool TestPartFailed(const TestPartResult & result) {
1635  return result.failed();
1636}
1637
1638// Gets the number of failed test parts.
1639int TestResult::failed_part_count() const {
1640  return test_part_results_.CountIf(TestPartFailed);
1641}
1642
1643// Returns true iff the test part fatally failed.
1644static bool TestPartFatallyFailed(const TestPartResult & result) {
1645  return result.fatally_failed();
1646}
1647
1648// Returns true iff the test fatally failed.
1649bool TestResult::HasFatalFailure() const {
1650  return test_part_results_.CountIf(TestPartFatallyFailed) > 0;
1651}
1652
1653// Gets the number of all test parts.  This is the sum of the number
1654// of successful test parts and the number of failed test parts.
1655int TestResult::total_part_count() const {
1656  return test_part_results_.size();
1657}
1658
1659}  // namespace internal
1660
1661// class Test
1662
1663// Creates a Test object.
1664
1665// The c'tor saves the values of all Google Test flags.
1666Test::Test()
1667    : gtest_flag_saver_(new internal::GTestFlagSaver) {
1668}
1669
1670// The d'tor restores the values of all Google Test flags.
1671Test::~Test() {
1672  delete gtest_flag_saver_;
1673}
1674
1675// Sets up the test fixture.
1676//
1677// A sub-class may override this.
1678void Test::SetUp() {
1679}
1680
1681// Tears down the test fixture.
1682//
1683// A sub-class may override this.
1684void Test::TearDown() {
1685}
1686
1687// Allows user supplied key value pairs to be recorded for later output.
1688void Test::RecordProperty(const char* key, const char* value) {
1689  UnitTest::GetInstance()->RecordPropertyForCurrentTest(key, value);
1690}
1691
1692// Allows user supplied key value pairs to be recorded for later output.
1693void Test::RecordProperty(const char* key, int value) {
1694  Message value_message;
1695  value_message << value;
1696  RecordProperty(key, value_message.GetString().c_str());
1697}
1698
1699#ifdef GTEST_OS_WINDOWS
1700// We are on Windows.
1701
1702// Adds an "exception thrown" fatal failure to the current test.
1703static void AddExceptionThrownFailure(DWORD exception_code,
1704                                      const char* location) {
1705  Message message;
1706  message << "Exception thrown with code 0x" << std::setbase(16) <<
1707    exception_code << std::setbase(10) << " in " << location << ".";
1708
1709  UnitTest* const unit_test = UnitTest::GetInstance();
1710  unit_test->AddTestPartResult(
1711      TPRT_FATAL_FAILURE,
1712      static_cast<const char *>(NULL),
1713           // We have no info about the source file where the exception
1714           // occurred.
1715      -1,  // We have no info on which line caused the exception.
1716      message.GetString(),
1717      internal::String(""));
1718}
1719
1720#endif  // GTEST_OS_WINDOWS
1721
1722// Google Test requires all tests in the same test case to use the same test
1723// fixture class.  This function checks if the current test has the
1724// same fixture class as the first test in the current test case.  If
1725// yes, it returns true; otherwise it generates a Google Test failure and
1726// returns false.
1727bool Test::HasSameFixtureClass() {
1728  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
1729  const TestCase* const test_case = impl->current_test_case();
1730
1731  // Info about the first test in the current test case.
1732  const internal::TestInfoImpl* const first_test_info =
1733      test_case->test_info_list().Head()->element()->impl();
1734  const internal::TypeId first_fixture_id = first_test_info->fixture_class_id();
1735  const char* const first_test_name = first_test_info->name();
1736
1737  // Info about the current test.
1738  const internal::TestInfoImpl* const this_test_info =
1739      impl->current_test_info()->impl();
1740  const internal::TypeId this_fixture_id = this_test_info->fixture_class_id();
1741  const char* const this_test_name = this_test_info->name();
1742
1743  if (this_fixture_id != first_fixture_id) {
1744    // Is the first test defined using TEST?
1745    const bool first_is_TEST = first_fixture_id == internal::GetTypeId<Test>();
1746    // Is this test defined using TEST?
1747    const bool this_is_TEST = this_fixture_id == internal::GetTypeId<Test>();
1748
1749    if (first_is_TEST || this_is_TEST) {
1750      // The user mixed TEST and TEST_F in this test case - we'll tell
1751      // him/her how to fix it.
1752
1753      // Gets the name of the TEST and the name of the TEST_F.  Note
1754      // that first_is_TEST and this_is_TEST cannot both be true, as
1755      // the fixture IDs are different for the two tests.
1756      const char* const TEST_name =
1757          first_is_TEST ? first_test_name : this_test_name;
1758      const char* const TEST_F_name =
1759          first_is_TEST ? this_test_name : first_test_name;
1760
1761      ADD_FAILURE()
1762          << "All tests in the same test case must use the same test fixture\n"
1763          << "class, so mixing TEST_F and TEST in the same test case is\n"
1764          << "illegal.  In test case " << this_test_info->test_case_name()
1765          << ",\n"
1766          << "test " << TEST_F_name << " is defined using TEST_F but\n"
1767          << "test " << TEST_name << " is defined using TEST.  You probably\n"
1768          << "want to change the TEST to TEST_F or move it to another test\n"
1769          << "case.";
1770    } else {
1771      // The user defined two fixture classes with the same name in
1772      // two namespaces - we'll tell him/her how to fix it.
1773      ADD_FAILURE()
1774          << "All tests in the same test case must use the same test fixture\n"
1775          << "class.  However, in test case "
1776          << this_test_info->test_case_name() << ",\n"
1777          << "you defined test " << first_test_name
1778          << " and test " << this_test_name << "\n"
1779          << "using two different test fixture classes.  This can happen if\n"
1780          << "the two classes are from different namespaces or translation\n"
1781          << "units and have the same name.  You should probably rename one\n"
1782          << "of the classes to put the tests into different test cases.";
1783    }
1784    return false;
1785  }
1786
1787  return true;
1788}
1789
1790// Runs the test and updates the test result.
1791void Test::Run() {
1792  if (!HasSameFixtureClass()) return;
1793
1794  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
1795#ifdef GTEST_OS_WINDOWS
1796  // We are on Windows.
1797  impl->os_stack_trace_getter()->UponLeavingGTest();
1798  __try {
1799    SetUp();
1800  } __except(internal::UnitTestOptions::GTestShouldProcessSEH(
1801      GetExceptionCode())) {
1802    AddExceptionThrownFailure(GetExceptionCode(), "SetUp()");
1803  }
1804
1805  // We will run the test only if SetUp() had no fatal failure.
1806  if (!HasFatalFailure()) {
1807    impl->os_stack_trace_getter()->UponLeavingGTest();
1808    __try {
1809      TestBody();
1810    } __except(internal::UnitTestOptions::GTestShouldProcessSEH(
1811        GetExceptionCode())) {
1812      AddExceptionThrownFailure(GetExceptionCode(), "the test body");
1813    }
1814  }
1815
1816  // However, we want to clean up as much as possible.  Hence we will
1817  // always call TearDown(), even if SetUp() or the test body has
1818  // failed.
1819  impl->os_stack_trace_getter()->UponLeavingGTest();
1820  __try {
1821    TearDown();
1822  } __except(internal::UnitTestOptions::GTestShouldProcessSEH(
1823      GetExceptionCode())) {
1824    AddExceptionThrownFailure(GetExceptionCode(), "TearDown()");
1825  }
1826
1827#else  // We are on Linux or Mac - exceptions are disabled.
1828  impl->os_stack_trace_getter()->UponLeavingGTest();
1829  SetUp();
1830
1831  // We will run the test only if SetUp() was successful.
1832  if (!HasFatalFailure()) {
1833    impl->os_stack_trace_getter()->UponLeavingGTest();
1834    TestBody();
1835  }
1836
1837  // However, we want to clean up as much as possible.  Hence we will
1838  // always call TearDown(), even if SetUp() or the test body has
1839  // failed.
1840  impl->os_stack_trace_getter()->UponLeavingGTest();
1841  TearDown();
1842#endif  // GTEST_OS_WINDOWS
1843}
1844
1845
1846// Returns true iff the current test has a fatal failure.
1847bool Test::HasFatalFailure() {
1848  return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
1849}
1850
1851// class TestInfo
1852
1853// Constructs a TestInfo object.
1854TestInfo::TestInfo(const char* test_case_name,
1855                   const char* name,
1856                   internal::TypeId fixture_class_id,
1857                   TestMaker maker) {
1858  impl_ = new internal::TestInfoImpl(this, test_case_name, name,
1859                                     fixture_class_id, maker);
1860}
1861
1862// Destructs a TestInfo object.
1863TestInfo::~TestInfo() {
1864  delete impl_;
1865}
1866
1867// Creates a TestInfo object and registers it with the UnitTest
1868// singleton; returns the created object.
1869//
1870// Arguments:
1871//
1872//   test_case_name: name of the test case
1873//   name:           name of the test
1874//   set_up_tc:      pointer to the function that sets up the test case
1875//   tear_down_tc:   pointer to the function that tears down the test case
1876//   maker:          pointer to the function that creates a test object
1877TestInfo* TestInfo::MakeAndRegisterInstance(
1878    const char* test_case_name,
1879    const char* name,
1880    internal::TypeId fixture_class_id,
1881    Test::SetUpTestCaseFunc set_up_tc,
1882    Test::TearDownTestCaseFunc tear_down_tc,
1883    TestMaker maker) {
1884  TestInfo* const test_info =
1885      new TestInfo(test_case_name, name, fixture_class_id, maker);
1886  internal::GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
1887  return test_info;
1888}
1889
1890// Returns the test case name.
1891const char* TestInfo::test_case_name() const {
1892  return impl_->test_case_name();
1893}
1894
1895// Returns the test name.
1896const char* TestInfo::name() const {
1897  return impl_->name();
1898}
1899
1900// Returns true if this test should run.
1901bool TestInfo::should_run() const { return impl_->should_run(); }
1902
1903// Returns the result of the test.
1904const internal::TestResult* TestInfo::result() const { return impl_->result(); }
1905
1906// Increments the number of death tests encountered in this test so
1907// far.
1908int TestInfo::increment_death_test_count() {
1909  return impl_->result()->increment_death_test_count();
1910}
1911
1912namespace {
1913
1914// A predicate that checks the test name of a TestInfo against a known
1915// value.
1916//
1917// This is used for implementation of the TestCase class only.  We put
1918// it in the anonymous namespace to prevent polluting the outer
1919// namespace.
1920//
1921// TestNameIs is copyable.
1922class TestNameIs {
1923 public:
1924  // Constructor.
1925  //
1926  // TestNameIs has NO default constructor.
1927  explicit TestNameIs(const char* name)
1928      : name_(name) {}
1929
1930  // Returns true iff the test name of test_info matches name_.
1931  bool operator()(const TestInfo * test_info) const {
1932    return test_info && internal::String(test_info->name()).Compare(name_) == 0;
1933  }
1934
1935 private:
1936  internal::String name_;
1937};
1938
1939}  // namespace
1940
1941// Finds and returns a TestInfo with the given name.  If one doesn't
1942// exist, returns NULL.
1943TestInfo * TestCase::GetTestInfo(const char* test_name) {
1944  // Can we find a TestInfo with the given name?
1945  internal::ListNode<TestInfo *> * const node = test_info_list_->FindIf(
1946      TestNameIs(test_name));
1947
1948  // Returns the TestInfo found.
1949  return node ? node->element() : NULL;
1950}
1951
1952namespace internal {
1953
1954// Creates the test object, runs it, records its result, and then
1955// deletes it.
1956void TestInfoImpl::Run() {
1957  if (!should_run_) return;
1958
1959  // Tells UnitTest where to store test result.
1960  UnitTestImpl* const impl = internal::GetUnitTestImpl();
1961  impl->set_current_test_info(parent_);
1962
1963  // Notifies the unit test event listener that a test is about to
1964  // start.
1965  UnitTestEventListenerInterface* const result_printer =
1966    impl->result_printer();
1967  result_printer->OnTestStart(parent_);
1968
1969  const TimeInMillis start = GetTimeInMillis();
1970
1971  impl->os_stack_trace_getter()->UponLeavingGTest();
1972#ifdef GTEST_OS_WINDOWS
1973  // We are on Windows.
1974  Test* test = NULL;
1975
1976  __try {
1977    // Creates the test object.
1978    test = (*maker_)();
1979  } __except(internal::UnitTestOptions::GTestShouldProcessSEH(
1980      GetExceptionCode())) {
1981    AddExceptionThrownFailure(GetExceptionCode(),
1982                              "the test fixture's constructor");
1983    return;
1984  }
1985#else  // We are on Linux or Mac OS - exceptions are disabled.
1986
1987  // TODO(wan): If test->Run() throws, test won't be deleted.  This is
1988  // not a problem now as we don't use exceptions.  If we were to
1989  // enable exceptions, we should revise the following to be
1990  // exception-safe.
1991
1992  // Creates the test object.
1993  Test* test = (*maker_)();
1994#endif  // GTEST_OS_WINDOWS
1995
1996  // Runs the test only if the constructor of the test fixture didn't
1997  // generate a fatal failure.
1998  if (!Test::HasFatalFailure()) {
1999    test->Run();
2000  }
2001
2002  // Deletes the test object.
2003  impl->os_stack_trace_getter()->UponLeavingGTest();
2004  delete test;
2005  test = NULL;
2006
2007  result_.set_elapsed_time(GetTimeInMillis() - start);
2008
2009  // Notifies the unit test event listener that a test has just finished.
2010  result_printer->OnTestEnd(parent_);
2011
2012  // Tells UnitTest to stop associating assertion results to this
2013  // test.
2014  impl->set_current_test_info(NULL);
2015}
2016
2017}  // namespace internal
2018
2019// class TestCase
2020
2021// Gets the number of successful tests in this test case.
2022int TestCase::successful_test_count() const {
2023  return test_info_list_->CountIf(TestPassed);
2024}
2025
2026// Gets the number of failed tests in this test case.
2027int TestCase::failed_test_count() const {
2028  return test_info_list_->CountIf(TestFailed);
2029}
2030
2031int TestCase::disabled_test_count() const {
2032  return test_info_list_->CountIf(TestDisabled);
2033}
2034
2035// Get the number of tests in this test case that should run.
2036int TestCase::test_to_run_count() const {
2037  return test_info_list_->CountIf(ShouldRunTest);
2038}
2039
2040// Gets the number of all tests.
2041int TestCase::total_test_count() const {
2042  return test_info_list_->size();
2043}
2044
2045// Creates a TestCase with the given name.
2046//
2047// Arguments:
2048//
2049//   name:         name of the test case
2050//   set_up_tc:    pointer to the function that sets up the test case
2051//   tear_down_tc: pointer to the function that tears down the test case
2052TestCase::TestCase(const char* name,
2053                   Test::SetUpTestCaseFunc set_up_tc,
2054                   Test::TearDownTestCaseFunc tear_down_tc)
2055    : name_(name),
2056      set_up_tc_(set_up_tc),
2057      tear_down_tc_(tear_down_tc),
2058      should_run_(false),
2059      elapsed_time_(0) {
2060  test_info_list_ = new internal::List<TestInfo *>;
2061}
2062
2063// Destructor of TestCase.
2064TestCase::~TestCase() {
2065  // Deletes every Test in the collection.
2066  test_info_list_->ForEach(internal::Delete<TestInfo>);
2067
2068  // Then deletes the Test collection.
2069  delete test_info_list_;
2070  test_info_list_ = NULL;
2071}
2072
2073// Adds a test to this test case.  Will delete the test upon
2074// destruction of the TestCase object.
2075void TestCase::AddTestInfo(TestInfo * test_info) {
2076  test_info_list_->PushBack(test_info);
2077}
2078
2079// Runs every test in this TestCase.
2080void TestCase::Run() {
2081  if (!should_run_) return;
2082
2083  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2084  impl->set_current_test_case(this);
2085
2086  UnitTestEventListenerInterface * const result_printer =
2087      impl->result_printer();
2088
2089  result_printer->OnTestCaseStart(this);
2090  impl->os_stack_trace_getter()->UponLeavingGTest();
2091  set_up_tc_();
2092
2093  const internal::TimeInMillis start = internal::GetTimeInMillis();
2094  test_info_list_->ForEach(internal::TestInfoImpl::RunTest);
2095  elapsed_time_ = internal::GetTimeInMillis() - start;
2096
2097  impl->os_stack_trace_getter()->UponLeavingGTest();
2098  tear_down_tc_();
2099  result_printer->OnTestCaseEnd(this);
2100  impl->set_current_test_case(NULL);
2101}
2102
2103// Clears the results of all tests in this test case.
2104void TestCase::ClearResult() {
2105  test_info_list_->ForEach(internal::TestInfoImpl::ClearTestResult);
2106}
2107
2108
2109// class UnitTestEventListenerInterface
2110
2111// The virtual d'tor.
2112UnitTestEventListenerInterface::~UnitTestEventListenerInterface() {
2113}
2114
2115// A result printer that never prints anything.  Used in the child process
2116// of an exec-style death test to avoid needless output clutter.
2117class NullUnitTestResultPrinter : public UnitTestEventListenerInterface {};
2118
2119// Formats a countable noun.  Depending on its quantity, either the
2120// singular form or the plural form is used. e.g.
2121//
2122// FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
2123// FormatCountableNoun(5, "book", "books") returns "5 books".
2124static internal::String FormatCountableNoun(int count,
2125                                            const char * singular_form,
2126                                            const char * plural_form) {
2127  return internal::String::Format("%d %s", count,
2128                                  count == 1 ? singular_form : plural_form);
2129}
2130
2131// Formats the count of tests.
2132static internal::String FormatTestCount(int test_count) {
2133  return FormatCountableNoun(test_count, "test", "tests");
2134}
2135
2136// Formats the count of test cases.
2137static internal::String FormatTestCaseCount(int test_case_count) {
2138  return FormatCountableNoun(test_case_count, "test case", "test cases");
2139}
2140
2141// Converts a TestPartResultType enum to human-friendly string
2142// representation.  Both TPRT_NONFATAL_FAILURE and TPRT_FATAL_FAILURE
2143// are translated to "Failure", as the user usually doesn't care about
2144// the difference between the two when viewing the test result.
2145static const char * TestPartResultTypeToString(TestPartResultType type) {
2146  switch (type) {
2147    case TPRT_SUCCESS:
2148      return "Success";
2149
2150    case TPRT_NONFATAL_FAILURE:
2151    case TPRT_FATAL_FAILURE:
2152      return "Failure";
2153  }
2154
2155  return "Unknown result type";
2156}
2157
2158// Prints a TestPartResult.
2159static void PrintTestPartResult(
2160    const TestPartResult & test_part_result) {
2161  const char * const file_name = test_part_result.file_name();
2162
2163  printf("%s", file_name == NULL ? "unknown file" : file_name);
2164  if (test_part_result.line_number() >= 0) {
2165    printf(":%d", test_part_result.line_number());
2166  }
2167  printf(": %s\n", TestPartResultTypeToString(test_part_result.type()));
2168  printf("%s\n", test_part_result.message());
2169  fflush(stdout);
2170}
2171
2172// class PrettyUnitTestResultPrinter
2173
2174namespace internal {
2175
2176enum GTestColor {
2177  COLOR_RED,
2178  COLOR_GREEN,
2179  COLOR_YELLOW
2180};
2181
2182#ifdef _WIN32
2183
2184// Returns the character attribute for the given color.
2185WORD GetColorAttribute(GTestColor color) {
2186  switch (color) {
2187    case COLOR_RED:    return FOREGROUND_RED;
2188    case COLOR_GREEN:  return FOREGROUND_GREEN;
2189    case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
2190  }
2191  return 0;
2192}
2193
2194#else
2195
2196// Returns the ANSI color code for the given color.
2197const char* GetAnsiColorCode(GTestColor color) {
2198  switch (color) {
2199    case COLOR_RED:     return "1";
2200    case COLOR_GREEN:   return "2";
2201    case COLOR_YELLOW:  return "3";
2202  };
2203  return NULL;
2204}
2205
2206#endif  // _WIN32
2207
2208// Returns true iff Google Test should use colors in the output.
2209bool ShouldUseColor(bool stdout_is_tty) {
2210  const char* const gtest_color = GTEST_FLAG(color).c_str();
2211
2212  if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
2213#ifdef _WIN32
2214    // On Windows the TERM variable is usually not set, but the
2215    // console there does support colors.
2216    return stdout_is_tty;
2217#else
2218    // On non-Windows platforms, we rely on the TERM variable.
2219    const char* const term = GetEnv("TERM");
2220    const bool term_supports_color =
2221        String::CStringEquals(term, "xterm") ||
2222        String::CStringEquals(term, "xterm-color") ||
2223        String::CStringEquals(term, "cygwin");
2224    return stdout_is_tty && term_supports_color;
2225#endif  // _WIN32
2226  }
2227
2228  return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
2229      String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
2230      String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
2231      String::CStringEquals(gtest_color, "1");
2232  // We take "yes", "true", "t", and "1" as meaning "yes".  If the
2233  // value is neither one of these nor "auto", we treat it as "no" to
2234  // be conservative.
2235}
2236
2237// Helpers for printing colored strings to stdout. Note that on Windows, we
2238// cannot simply emit special characters and have the terminal change colors.
2239// This routine must actually emit the characters rather than return a string
2240// that would be colored when printed, as can be done on Linux.
2241void ColoredPrintf(GTestColor color, const char* fmt, ...) {
2242  va_list args;
2243  va_start(args, fmt);
2244
2245  static const bool use_color = ShouldUseColor(isatty(fileno(stdout)) != 0);
2246  // The '!= 0' comparison is necessary to satisfy MSVC 7.1.
2247
2248  if (!use_color) {
2249    vprintf(fmt, args);
2250    va_end(args);
2251    return;
2252  }
2253
2254#ifdef _WIN32
2255  const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
2256
2257  // Gets the current text color.
2258  CONSOLE_SCREEN_BUFFER_INFO buffer_info;
2259  GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
2260  const WORD old_color_attrs = buffer_info.wAttributes;
2261
2262  SetConsoleTextAttribute(stdout_handle,
2263                          GetColorAttribute(color) | FOREGROUND_INTENSITY);
2264  vprintf(fmt, args);
2265
2266  // Restores the text color.
2267  SetConsoleTextAttribute(stdout_handle, old_color_attrs);
2268#else
2269  printf("\033[0;3%sm", GetAnsiColorCode(color));
2270  vprintf(fmt, args);
2271  printf("\033[m");  // Resets the terminal to default.
2272#endif  // _WIN32
2273  va_end(args);
2274}
2275
2276}  // namespace internal
2277
2278using internal::ColoredPrintf;
2279using internal::COLOR_RED;
2280using internal::COLOR_GREEN;
2281using internal::COLOR_YELLOW;
2282
2283// This class implements the UnitTestEventListenerInterface interface.
2284//
2285// Class PrettyUnitTestResultPrinter is copyable.
2286class PrettyUnitTestResultPrinter : public UnitTestEventListenerInterface {
2287 public:
2288  PrettyUnitTestResultPrinter() {}
2289  static void PrintTestName(const char * test_case, const char * test) {
2290    printf("%s.%s", test_case, test);
2291  }
2292
2293  // The following methods override what's in the
2294  // UnitTestEventListenerInterface class.
2295  virtual void OnUnitTestStart(const UnitTest * unit_test);
2296  virtual void OnGlobalSetUpStart(const UnitTest*);
2297  virtual void OnTestCaseStart(const TestCase * test_case);
2298  virtual void OnTestStart(const TestInfo * test_info);
2299  virtual void OnNewTestPartResult(const TestPartResult * result);
2300  virtual void OnTestEnd(const TestInfo * test_info);
2301  virtual void OnGlobalTearDownStart(const UnitTest*);
2302  virtual void OnUnitTestEnd(const UnitTest * unit_test);
2303
2304 private:
2305  internal::String test_case_name_;
2306};
2307
2308// Called before the unit test starts.
2309void PrettyUnitTestResultPrinter::OnUnitTestStart(
2310    const UnitTest * unit_test) {
2311  const char * const filter = GTEST_FLAG(filter).c_str();
2312
2313  // Prints the filter if it's not *.  This reminds the user that some
2314  // tests may be skipped.
2315  if (!internal::String::CStringEquals(filter, kUniversalFilter)) {
2316    ColoredPrintf(COLOR_YELLOW,
2317                  "Note: %s filter = %s\n", GTEST_NAME, filter);
2318  }
2319
2320  const internal::UnitTestImpl* const impl = unit_test->impl();
2321  ColoredPrintf(COLOR_GREEN,  "[==========] ");
2322  printf("Running %s from %s.\n",
2323         FormatTestCount(impl->test_to_run_count()).c_str(),
2324         FormatTestCaseCount(impl->test_case_to_run_count()).c_str());
2325  fflush(stdout);
2326}
2327
2328void PrettyUnitTestResultPrinter::OnGlobalSetUpStart(const UnitTest*) {
2329  ColoredPrintf(COLOR_GREEN,  "[----------] ");
2330  printf("Global test environment set-up.\n");
2331  fflush(stdout);
2332}
2333
2334void PrettyUnitTestResultPrinter::OnTestCaseStart(
2335    const TestCase * test_case) {
2336  test_case_name_ = test_case->name();
2337  const internal::String counts =
2338      FormatCountableNoun(test_case->test_to_run_count(), "test", "tests");
2339  ColoredPrintf(COLOR_GREEN, "[----------] ");
2340  printf("%s from %s\n", counts.c_str(), test_case_name_.c_str());
2341  fflush(stdout);
2342}
2343
2344void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo * test_info) {
2345  ColoredPrintf(COLOR_GREEN,  "[ RUN      ] ");
2346  PrintTestName(test_case_name_.c_str(), test_info->name());
2347  printf("\n");
2348  fflush(stdout);
2349}
2350
2351void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo * test_info) {
2352  if (test_info->result()->Passed()) {
2353    ColoredPrintf(COLOR_GREEN, "[       OK ] ");
2354  } else {
2355    ColoredPrintf(COLOR_RED, "[  FAILED  ] ");
2356  }
2357  PrintTestName(test_case_name_.c_str(), test_info->name());
2358  printf("\n");
2359  fflush(stdout);
2360}
2361
2362// Called after an assertion failure.
2363void PrettyUnitTestResultPrinter::OnNewTestPartResult(
2364    const TestPartResult * result) {
2365  // If the test part succeeded, we don't need to do anything.
2366  if (result->type() == TPRT_SUCCESS)
2367    return;
2368
2369  // Print failure message from the assertion (e.g. expected this and got that).
2370  PrintTestPartResult(*result);
2371  fflush(stdout);
2372}
2373
2374void PrettyUnitTestResultPrinter::OnGlobalTearDownStart(const UnitTest*) {
2375  ColoredPrintf(COLOR_GREEN,  "[----------] ");
2376  printf("Global test environment tear-down\n");
2377  fflush(stdout);
2378}
2379
2380namespace internal {
2381
2382// Internal helper for printing the list of failed tests.
2383static void PrintFailedTestsPretty(const UnitTestImpl* impl) {
2384  const int failed_test_count = impl->failed_test_count();
2385  if (failed_test_count == 0) {
2386    return;
2387  }
2388
2389  for (const internal::ListNode<TestCase*>* node = impl->test_cases()->Head();
2390       node != NULL; node = node->next()) {
2391    const TestCase* const tc = node->element();
2392    if (!tc->should_run() || (tc->failed_test_count() == 0)) {
2393      continue;
2394    }
2395    for (const internal::ListNode<TestInfo*>* tinode =
2396         tc->test_info_list().Head();
2397         tinode != NULL; tinode = tinode->next()) {
2398      const TestInfo* const ti = tinode->element();
2399      if (!tc->ShouldRunTest(ti) || tc->TestPassed(ti)) {
2400        continue;
2401      }
2402      ColoredPrintf(COLOR_RED, "[  FAILED  ] ");
2403      printf("%s.%s\n", ti->test_case_name(), ti->name());
2404    }
2405  }
2406}
2407
2408}  // namespace internal
2409
2410void PrettyUnitTestResultPrinter::OnUnitTestEnd(
2411    const UnitTest * unit_test) {
2412  const internal::UnitTestImpl* const impl = unit_test->impl();
2413
2414  ColoredPrintf(COLOR_GREEN,  "[==========] ");
2415  printf("%s from %s ran.\n",
2416         FormatTestCount(impl->test_to_run_count()).c_str(),
2417         FormatTestCaseCount(impl->test_case_to_run_count()).c_str());
2418  ColoredPrintf(COLOR_GREEN,  "[  PASSED  ] ");
2419  printf("%s.\n", FormatTestCount(impl->successful_test_count()).c_str());
2420
2421  int num_failures = impl->failed_test_count();
2422  if (!impl->Passed()) {
2423    const int failed_test_count = impl->failed_test_count();
2424    ColoredPrintf(COLOR_RED,  "[  FAILED  ] ");
2425    printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
2426    internal::PrintFailedTestsPretty(impl);
2427    printf("\n%2d FAILED %s\n", num_failures,
2428                        num_failures == 1 ? "TEST" : "TESTS");
2429  }
2430
2431  int num_disabled = impl->disabled_test_count();
2432  if (num_disabled) {
2433    if (!num_failures) {
2434      printf("\n");  // Add a spacer if no FAILURE banner is displayed.
2435    }
2436    ColoredPrintf(COLOR_YELLOW,
2437                  "  YOU HAVE %d DISABLED %s\n\n",
2438                  num_disabled,
2439                  num_disabled == 1 ? "TEST" : "TESTS");
2440  }
2441  // Ensure that Google Test output is printed before, e.g., heapchecker output.
2442  fflush(stdout);
2443}
2444
2445// End PrettyUnitTestResultPrinter
2446
2447// class UnitTestEventsRepeater
2448//
2449// This class forwards events to other event listeners.
2450class UnitTestEventsRepeater : public UnitTestEventListenerInterface {
2451 public:
2452  typedef internal::List<UnitTestEventListenerInterface *> Listeners;
2453  typedef internal::ListNode<UnitTestEventListenerInterface *> ListenersNode;
2454  UnitTestEventsRepeater() {}
2455  virtual ~UnitTestEventsRepeater();
2456  void AddListener(UnitTestEventListenerInterface *listener);
2457
2458  virtual void OnUnitTestStart(const UnitTest* unit_test);
2459  virtual void OnUnitTestEnd(const UnitTest* unit_test);
2460  virtual void OnGlobalSetUpStart(const UnitTest* unit_test);
2461  virtual void OnGlobalSetUpEnd(const UnitTest* unit_test);
2462  virtual void OnGlobalTearDownStart(const UnitTest* unit_test);
2463  virtual void OnGlobalTearDownEnd(const UnitTest* unit_test);
2464  virtual void OnTestCaseStart(const TestCase* test_case);
2465  virtual void OnTestCaseEnd(const TestCase* test_case);
2466  virtual void OnTestStart(const TestInfo* test_info);
2467  virtual void OnTestEnd(const TestInfo* test_info);
2468  virtual void OnNewTestPartResult(const TestPartResult* result);
2469
2470 private:
2471  Listeners listeners_;
2472
2473  GTEST_DISALLOW_COPY_AND_ASSIGN(UnitTestEventsRepeater);
2474};
2475
2476UnitTestEventsRepeater::~UnitTestEventsRepeater() {
2477  for (ListenersNode* listener = listeners_.Head();
2478       listener != NULL;
2479       listener = listener->next()) {
2480    delete listener->element();
2481  }
2482}
2483
2484void UnitTestEventsRepeater::AddListener(
2485    UnitTestEventListenerInterface *listener) {
2486  listeners_.PushBack(listener);
2487}
2488
2489// Since the methods are identical, use a macro to reduce boilerplate.
2490// This defines a member that repeats the call to all listeners.
2491#define GTEST_REPEATER_METHOD(Name, Type) \
2492void UnitTestEventsRepeater::Name(const Type* parameter) { \
2493  for (ListenersNode* listener = listeners_.Head(); \
2494       listener != NULL; \
2495       listener = listener->next()) { \
2496    listener->element()->Name(parameter); \
2497  } \
2498}
2499
2500GTEST_REPEATER_METHOD(OnUnitTestStart, UnitTest)
2501GTEST_REPEATER_METHOD(OnUnitTestEnd, UnitTest)
2502GTEST_REPEATER_METHOD(OnGlobalSetUpStart, UnitTest)
2503GTEST_REPEATER_METHOD(OnGlobalSetUpEnd, UnitTest)
2504GTEST_REPEATER_METHOD(OnGlobalTearDownStart, UnitTest)
2505GTEST_REPEATER_METHOD(OnGlobalTearDownEnd, UnitTest)
2506GTEST_REPEATER_METHOD(OnTestCaseStart, TestCase)
2507GTEST_REPEATER_METHOD(OnTestCaseEnd, TestCase)
2508GTEST_REPEATER_METHOD(OnTestStart, TestInfo)
2509GTEST_REPEATER_METHOD(OnTestEnd, TestInfo)
2510GTEST_REPEATER_METHOD(OnNewTestPartResult, TestPartResult)
2511
2512#undef GTEST_REPEATER_METHOD
2513
2514// End PrettyUnitTestResultPrinter
2515
2516// This class generates an XML output file.
2517class XmlUnitTestResultPrinter : public UnitTestEventListenerInterface {
2518 public:
2519  explicit XmlUnitTestResultPrinter(const char* output_file);
2520
2521  virtual void OnUnitTestEnd(const UnitTest* unit_test);
2522
2523 private:
2524  // Is c a whitespace character that is normalized to a space character
2525  // when it appears in an XML attribute value?
2526  static bool IsNormalizableWhitespace(char c) {
2527    return c == 0x9 || c == 0xA || c == 0xD;
2528  }
2529
2530  // May c appear in a well-formed XML document?
2531  static bool IsValidXmlCharacter(char c) {
2532    return IsNormalizableWhitespace(c) || c >= 0x20;
2533  }
2534
2535  // Returns an XML-escaped copy of the input string str.  If
2536  // is_attribute is true, the text is meant to appear as an attribute
2537  // value, and normalizable whitespace is preserved by replacing it
2538  // with character references.
2539  static internal::String EscapeXml(const char* str,
2540                                    bool is_attribute);
2541
2542  // Convenience wrapper around EscapeXml when str is an attribute value.
2543  static internal::String EscapeXmlAttribute(const char* str) {
2544    return EscapeXml(str, true);
2545  }
2546
2547  // Convenience wrapper around EscapeXml when str is not an attribute value.
2548  static internal::String EscapeXmlText(const char* str) {
2549    return EscapeXml(str, false);
2550  }
2551
2552  // Prints an XML representation of a TestInfo object.
2553  static void PrintXmlTestInfo(FILE* out,
2554                               const char* test_case_name,
2555                               const TestInfo* test_info);
2556
2557  // Prints an XML representation of a TestCase object
2558  static void PrintXmlTestCase(FILE* out, const TestCase* test_case);
2559
2560  // Prints an XML summary of unit_test to output stream out.
2561  static void PrintXmlUnitTest(FILE* out, const UnitTest* unit_test);
2562
2563  // Produces a string representing the test properties in a result as space
2564  // delimited XML attributes based on the property key="value" pairs.
2565  // When the String is not empty, it includes a space at the beginning,
2566  // to delimit this attribute from prior attributes.
2567  static internal::String TestPropertiesAsXmlAttributes(
2568      const internal::TestResult* result);
2569
2570  // The output file.
2571  const internal::String output_file_;
2572
2573  GTEST_DISALLOW_COPY_AND_ASSIGN(XmlUnitTestResultPrinter);
2574};
2575
2576// Creates a new XmlUnitTestResultPrinter.
2577XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
2578    : output_file_(output_file) {
2579  if (output_file_.c_str() == NULL || output_file_.empty()) {
2580    fprintf(stderr, "XML output file may not be null\n");
2581    fflush(stderr);
2582    exit(EXIT_FAILURE);
2583  }
2584}
2585
2586// Called after the unit test ends.
2587void XmlUnitTestResultPrinter::OnUnitTestEnd(const UnitTest* unit_test) {
2588  FILE* xmlout = NULL;
2589  internal::FilePath output_file(output_file_);
2590  internal::FilePath output_dir(output_file.RemoveFileName());
2591
2592  if (output_dir.CreateDirectoriesRecursively()) {
2593  // MSVC 8 deprecates fopen(), so we want to suppress warning 4996
2594  // (deprecated function) there.
2595#ifdef GTEST_OS_WINDOWS
2596  // We are on Windows.
2597#pragma warning(push)          // Saves the current warning state.
2598#pragma warning(disable:4996)  // Temporarily disables warning 4996.
2599    xmlout = fopen(output_file_.c_str(), "w");
2600#pragma warning(pop)           // Restores the warning state.
2601#else  // We are on Linux or Mac OS.
2602    xmlout = fopen(output_file_.c_str(), "w");
2603#endif  // GTEST_OS_WINDOWS
2604  }
2605  if (xmlout == NULL) {
2606    // TODO(wan): report the reason of the failure.
2607    //
2608    // We don't do it for now as:
2609    //
2610    //   1. There is no urgent need for it.
2611    //   2. It's a bit involved to make the errno variable thread-safe on
2612    //      all three operating systems (Linux, Windows, and Mac OS).
2613    //   3. To interpret the meaning of errno in a thread-safe way,
2614    //      we need the strerror_r() function, which is not available on
2615    //      Windows.
2616    fprintf(stderr,
2617            "Unable to open file \"%s\"\n",
2618            output_file_.c_str());
2619    fflush(stderr);
2620    exit(EXIT_FAILURE);
2621  }
2622  PrintXmlUnitTest(xmlout, unit_test);
2623  fclose(xmlout);
2624}
2625
2626// Returns an XML-escaped copy of the input string str.  If is_attribute
2627// is true, the text is meant to appear as an attribute value, and
2628// normalizable whitespace is preserved by replacing it with character
2629// references.
2630//
2631// Invalid XML characters in str, if any, are stripped from the output.
2632// It is expected that most, if not all, of the text processed by this
2633// module will consist of ordinary English text.
2634// If this module is ever modified to produce version 1.1 XML output,
2635// most invalid characters can be retained using character references.
2636// TODO(wan): It might be nice to have a minimally invasive, human-readable
2637// escaping scheme for invalid characters, rather than dropping them.
2638internal::String XmlUnitTestResultPrinter::EscapeXml(const char* str,
2639                                                     bool is_attribute) {
2640  Message m;
2641
2642  if (str != NULL) {
2643    for (const char* src = str; *src; ++src) {
2644      switch (*src) {
2645        case '<':
2646          m << "&lt;";
2647          break;
2648        case '>':
2649          m << "&gt;";
2650          break;
2651        case '&':
2652          m << "&amp;";
2653          break;
2654        case '\'':
2655          if (is_attribute)
2656            m << "&apos;";
2657          else
2658            m << '\'';
2659          break;
2660        case '"':
2661          if (is_attribute)
2662            m << "&quot;";
2663          else
2664            m << '"';
2665          break;
2666        default:
2667          if (IsValidXmlCharacter(*src)) {
2668            if (is_attribute && IsNormalizableWhitespace(*src))
2669              m << internal::String::Format("&#x%02X;", unsigned(*src));
2670            else
2671              m << *src;
2672          }
2673          break;
2674      }
2675    }
2676  }
2677
2678  return m.GetString();
2679}
2680
2681
2682// The following routines generate an XML representation of a UnitTest
2683// object.
2684//
2685// This is how Google Test concepts map to the DTD:
2686//
2687// <testsuite name="AllTests">         <-- corresponds to a UnitTest object
2688//   <testsuite name="testcase-name">  <-- corresponds to a TestCase object
2689//     <testcase name="test-name">     <-- corresponds to a TestInfo object
2690//       <failure message="..." />
2691//       <failure message="..." />     <-- individual assertion failures
2692//       <failure message="..." />
2693//     </testcase>
2694//   </testsuite>
2695// </testsuite>
2696
2697// Prints an XML representation of a TestInfo object.
2698// TODO(wan): There is also value in printing properties with the plain printer.
2699void XmlUnitTestResultPrinter::PrintXmlTestInfo(FILE* out,
2700                                                const char* test_case_name,
2701                                                const TestInfo* test_info) {
2702  const internal::TestResult * const result = test_info->result();
2703  const internal::List<TestPartResult> &results = result->test_part_results();
2704  fprintf(out,
2705          "    <testcase name=\"%s\" status=\"%s\" time=\"%s\" "
2706          "classname=\"%s\"%s",
2707          EscapeXmlAttribute(test_info->name()).c_str(),
2708          test_info->should_run() ? "run" : "notrun",
2709          internal::StreamableToString(result->elapsed_time()).c_str(),
2710          EscapeXmlAttribute(test_case_name).c_str(),
2711          TestPropertiesAsXmlAttributes(result).c_str());
2712
2713  int failures = 0;
2714  for (const internal::ListNode<TestPartResult>* part_node = results.Head();
2715       part_node != NULL;
2716       part_node = part_node->next()) {
2717    const TestPartResult& part = part_node->element();
2718    if (part.failed()) {
2719      const internal::String message =
2720          internal::String::Format("%s:%d\n%s", part.file_name(),
2721                                   part.line_number(), part.message());
2722      if (++failures == 1)
2723        fprintf(out, ">\n");
2724      fprintf(out,
2725              "      <failure message=\"%s\" type=\"\"/>\n",
2726              EscapeXmlAttribute(message.c_str()).c_str());
2727    }
2728  }
2729
2730  if (failures == 0)
2731    fprintf(out, " />\n");
2732  else
2733    fprintf(out, "    </testcase>\n");
2734}
2735
2736// Prints an XML representation of a TestCase object
2737void XmlUnitTestResultPrinter::PrintXmlTestCase(FILE* out,
2738                                                const TestCase* test_case) {
2739  fprintf(out,
2740          "  <testsuite name=\"%s\" tests=\"%d\" failures=\"%d\" "
2741          "disabled=\"%d\" ",
2742          EscapeXmlAttribute(test_case->name()).c_str(),
2743          test_case->total_test_count(),
2744          test_case->failed_test_count(),
2745          test_case->disabled_test_count());
2746  fprintf(out,
2747          "errors=\"0\" time=\"%s\">\n",
2748          internal::StreamableToString(test_case->elapsed_time()).c_str());
2749  for (const internal::ListNode<TestInfo*>* info_node =
2750         test_case->test_info_list().Head();
2751       info_node != NULL;
2752       info_node = info_node->next()) {
2753    PrintXmlTestInfo(out, test_case->name(), info_node->element());
2754  }
2755  fprintf(out, "  </testsuite>\n");
2756}
2757
2758// Prints an XML summary of unit_test to output stream out.
2759void XmlUnitTestResultPrinter::PrintXmlUnitTest(FILE* out,
2760                                                const UnitTest* unit_test) {
2761  const internal::UnitTestImpl* const impl = unit_test->impl();
2762  fprintf(out, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
2763  fprintf(out,
2764          "<testsuite tests=\"%d\" failures=\"%d\" disabled=\"%d\" "
2765          "errors=\"0\" time=\"%s\" ",
2766          impl->total_test_count(),
2767          impl->failed_test_count(),
2768          impl->disabled_test_count(),
2769          internal::StreamableToString(impl->elapsed_time()).c_str());
2770  fprintf(out, "name=\"AllTests\">\n");
2771  for (const internal::ListNode<TestCase*>* case_node =
2772       impl->test_cases()->Head();
2773       case_node != NULL;
2774       case_node = case_node->next()) {
2775    PrintXmlTestCase(out, case_node->element());
2776  }
2777  fprintf(out, "</testsuite>\n");
2778}
2779
2780// Produces a string representing the test properties in a result as space
2781// delimited XML attributes based on the property key="value" pairs.
2782internal::String XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
2783    const internal::TestResult* result) {
2784  using internal::TestProperty;
2785  Message attributes;
2786  const internal::List<TestProperty>& properties = result->test_properties();
2787  for (const internal::ListNode<TestProperty>* property_node =
2788       properties.Head();
2789       property_node != NULL;
2790       property_node = property_node->next()) {
2791    const TestProperty& property = property_node->element();
2792    attributes << " " << property.key() << "="
2793        << "\"" << EscapeXmlAttribute(property.value()) << "\"";
2794  }
2795  return attributes.GetString();
2796}
2797
2798// End XmlUnitTestResultPrinter
2799
2800namespace internal {
2801
2802// Class ScopedTrace
2803
2804// Pushes the given source file location and message onto a per-thread
2805// trace stack maintained by Google Test.
2806// L < UnitTest::mutex_
2807ScopedTrace::ScopedTrace(const char* file, int line, const Message& message) {
2808  TraceInfo trace;
2809  trace.file = file;
2810  trace.line = line;
2811  trace.message = message.GetString();
2812
2813  UnitTest::GetInstance()->PushGTestTrace(trace);
2814}
2815
2816// Pops the info pushed by the c'tor.
2817// L < UnitTest::mutex_
2818ScopedTrace::~ScopedTrace() {
2819  UnitTest::GetInstance()->PopGTestTrace();
2820}
2821
2822
2823// class OsStackTraceGetter
2824
2825// Returns the current OS stack trace as a String.  Parameters:
2826//
2827//   max_depth  - the maximum number of stack frames to be included
2828//                in the trace.
2829//   skip_count - the number of top frames to be skipped; doesn't count
2830//                against max_depth.
2831//
2832// L < mutex_
2833// We use "L < mutex_" to denote that the function may acquire mutex_.
2834String OsStackTraceGetter::CurrentStackTrace(int, int) {
2835  return String("");
2836}
2837
2838// L < mutex_
2839void OsStackTraceGetter::UponLeavingGTest() {
2840}
2841
2842const char* const
2843OsStackTraceGetter::kElidedFramesMarker =
2844    "... " GTEST_NAME " internal frames ...";
2845
2846}  // namespace internal
2847
2848// class UnitTest
2849
2850// Gets the singleton UnitTest object.  The first time this method is
2851// called, a UnitTest object is constructed and returned.  Consecutive
2852// calls will return the same object.
2853//
2854// We don't protect this under mutex_ as a user is not supposed to
2855// call this before main() starts, from which point on the return
2856// value will never change.
2857UnitTest * UnitTest::GetInstance() {
2858  // When compiled with MSVC 7.1 in optimized mode, destroying the
2859  // UnitTest object upon exiting the program messes up the exit code,
2860  // causing successful tests to appear failed.  We have to use a
2861  // different implementation in this case to bypass the compiler bug.
2862  // This implementation makes the compiler happy, at the cost of
2863  // leaking the UnitTest object.
2864#if _MSC_VER == 1310 && !defined(_DEBUG)  // MSVC 7.1 and optimized build.
2865  static UnitTest* const instance = new UnitTest;
2866  return instance;
2867#else
2868  static UnitTest instance;
2869  return &instance;
2870#endif  // _MSC_VER==1310 && !defined(_DEBUG)
2871}
2872
2873// Registers and returns a global test environment.  When a test
2874// program is run, all global test environments will be set-up in the
2875// order they were registered.  After all tests in the program have
2876// finished, all global test environments will be torn-down in the
2877// *reverse* order they were registered.
2878//
2879// The UnitTest object takes ownership of the given environment.
2880//
2881// We don't protect this under mutex_, as we only support calling it
2882// from the main thread.
2883Environment* UnitTest::AddEnvironment(Environment* env) {
2884  if (env == NULL) {
2885    return NULL;
2886  }
2887
2888  impl_->environments()->PushBack(env);
2889  impl_->environments_in_reverse_order()->PushFront(env);
2890  return env;
2891}
2892
2893// Adds a TestPartResult to the current TestResult object.  All Google Test
2894// assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
2895// this to report their results.  The user code should use the
2896// assertion macros instead of calling this directly.
2897// L < mutex_
2898void UnitTest::AddTestPartResult(TestPartResultType result_type,
2899                                 const char* file_name,
2900                                 int line_number,
2901                                 const internal::String& message,
2902                                 const internal::String& os_stack_trace) {
2903  Message msg;
2904  msg << message;
2905
2906  internal::MutexLock lock(&mutex_);
2907  if (impl_->gtest_trace_stack()->size() > 0) {
2908    msg << "\n" << GTEST_NAME << " trace:";
2909
2910    for (internal::ListNode<internal::TraceInfo>* node =
2911         impl_->gtest_trace_stack()->Head();
2912         node != NULL;
2913         node = node->next()) {
2914      const internal::TraceInfo& trace = node->element();
2915      msg << "\n" << trace.file << ":" << trace.line << ": " << trace.message;
2916    }
2917  }
2918
2919  if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) {
2920    msg << "\nStack trace:\n" << os_stack_trace;
2921  }
2922
2923  const TestPartResult result =
2924    TestPartResult(result_type, file_name, line_number,
2925                   msg.GetString().c_str());
2926  impl_->test_part_result_reporter()->ReportTestPartResult(result);
2927
2928  // If this is a failure and the user wants the debugger to break on
2929  // failures ...
2930  if (result_type != TPRT_SUCCESS && GTEST_FLAG(break_on_failure)) {
2931    // ... then we generate a seg fault.
2932    *static_cast<int*>(NULL) = 1;
2933  }
2934}
2935
2936// Creates and adds a property to the current TestResult. If a property matching
2937// the supplied value already exists, updates its value instead.
2938void UnitTest::RecordPropertyForCurrentTest(const char* key,
2939                                            const char* value) {
2940  const internal::TestProperty test_property(key, value);
2941  impl_->current_test_result()->RecordProperty(test_property);
2942}
2943
2944// Runs all tests in this UnitTest object and prints the result.
2945// Returns 0 if successful, or 1 otherwise.
2946//
2947// We don't protect this under mutex_, as we only support calling it
2948// from the main thread.
2949int UnitTest::Run() {
2950#ifdef GTEST_OS_WINDOWS
2951
2952#if !defined(_WIN32_WCE)
2953  // SetErrorMode doesn't exist on CE.
2954  if (GTEST_FLAG(catch_exceptions)) {
2955    // The user wants Google Test to catch exceptions thrown by the tests.
2956
2957    // This lets fatal errors be handled by us, instead of causing pop-ups.
2958    SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
2959                 SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
2960  }
2961#endif  // _WIN32_WCE
2962
2963  __try {
2964    return impl_->RunAllTests();
2965  } __except(internal::UnitTestOptions::GTestShouldProcessSEH(
2966      GetExceptionCode())) {
2967    printf("Exception thrown with code 0x%x.\nFAIL\n", GetExceptionCode());
2968    fflush(stdout);
2969    return 1;
2970  }
2971
2972#else
2973  // We are on Linux or Mac OS.  There is no exception of any kind.
2974
2975  return impl_->RunAllTests();
2976#endif  // GTEST_OS_WINDOWS
2977}
2978
2979// Returns the TestCase object for the test that's currently running,
2980// or NULL if no test is running.
2981// L < mutex_
2982const TestCase* UnitTest::current_test_case() const {
2983  internal::MutexLock lock(&mutex_);
2984  return impl_->current_test_case();
2985}
2986
2987// Returns the TestInfo object for the test that's currently running,
2988// or NULL if no test is running.
2989// L < mutex_
2990const TestInfo* UnitTest::current_test_info() const {
2991  internal::MutexLock lock(&mutex_);
2992  return impl_->current_test_info();
2993}
2994
2995// Creates an empty UnitTest.
2996UnitTest::UnitTest() {
2997  impl_ = new internal::UnitTestImpl(this);
2998}
2999
3000// Destructor of UnitTest.
3001UnitTest::~UnitTest() {
3002  delete impl_;
3003}
3004
3005// Pushes a trace defined by SCOPED_TRACE() on to the per-thread
3006// Google Test trace stack.
3007// L < mutex_
3008void UnitTest::PushGTestTrace(const internal::TraceInfo& trace) {
3009  internal::MutexLock lock(&mutex_);
3010  impl_->gtest_trace_stack()->PushFront(trace);
3011}
3012
3013// Pops a trace from the per-thread Google Test trace stack.
3014// L < mutex_
3015void UnitTest::PopGTestTrace() {
3016  internal::MutexLock lock(&mutex_);
3017  impl_->gtest_trace_stack()->PopFront(NULL);
3018}
3019
3020namespace internal {
3021
3022UnitTestImpl::UnitTestImpl(UnitTest* parent)
3023    : parent_(parent),
3024      test_cases_(),
3025      last_death_test_case_(NULL),
3026      current_test_case_(NULL),
3027      current_test_info_(NULL),
3028      ad_hoc_test_result_(),
3029      result_printer_(NULL),
3030      os_stack_trace_getter_(NULL),
3031#ifdef GTEST_HAS_DEATH_TEST
3032      elapsed_time_(0),
3033      internal_run_death_test_flag_(NULL),
3034      death_test_factory_(new DefaultDeathTestFactory) {
3035#else
3036      elapsed_time_(0) {
3037#endif  // GTEST_HAS_DEATH_TEST
3038  // We do the assignment here instead of in the initializer list, as
3039  // doing that latter causes MSVC to issue a warning about using
3040  // 'this' in initializers.
3041  test_part_result_reporter_ = this;
3042}
3043
3044UnitTestImpl::~UnitTestImpl() {
3045  // Deletes every TestCase.
3046  test_cases_.ForEach(internal::Delete<TestCase>);
3047
3048  // Deletes every Environment.
3049  environments_.ForEach(internal::Delete<Environment>);
3050
3051  // Deletes the current test result printer.
3052  delete result_printer_;
3053
3054  delete os_stack_trace_getter_;
3055}
3056
3057// A predicate that checks the name of a TestCase against a known
3058// value.
3059//
3060// This is used for implementation of the UnitTest class only.  We put
3061// it in the anonymous namespace to prevent polluting the outer
3062// namespace.
3063//
3064// TestCaseNameIs is copyable.
3065class TestCaseNameIs {
3066 public:
3067  // Constructor.
3068  explicit TestCaseNameIs(const String& name)
3069      : name_(name) {}
3070
3071  // Returns true iff the name of test_case matches name_.
3072  bool operator()(const TestCase* test_case) const {
3073    return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0;
3074  }
3075
3076 private:
3077  String name_;
3078};
3079
3080// Finds and returns a TestCase with the given name.  If one doesn't
3081// exist, creates one and returns it.
3082//
3083// Arguments:
3084//
3085//   test_case_name: name of the test case
3086//   set_up_tc:      pointer to the function that sets up the test case
3087//   tear_down_tc:   pointer to the function that tears down the test case
3088TestCase* UnitTestImpl::GetTestCase(const char* test_case_name,
3089                                    Test::SetUpTestCaseFunc set_up_tc,
3090                                    Test::TearDownTestCaseFunc tear_down_tc) {
3091  // Can we find a TestCase with the given name?
3092  internal::ListNode<TestCase*>* node = test_cases_.FindIf(
3093      TestCaseNameIs(test_case_name));
3094
3095  if (node == NULL) {
3096    // No.  Let's create one.
3097    TestCase* const test_case =
3098      new TestCase(test_case_name, set_up_tc, tear_down_tc);
3099
3100    // Is this a death test case?
3101    if (String(test_case_name).EndsWith("DeathTest")) {
3102      // Yes.  Inserts the test case after the last death test case
3103      // defined so far.
3104      node = test_cases_.InsertAfter(last_death_test_case_, test_case);
3105      last_death_test_case_ = node;
3106    } else {
3107      // No.  Appends to the end of the list.
3108      test_cases_.PushBack(test_case);
3109      node = test_cases_.Last();
3110    }
3111  }
3112
3113  // Returns the TestCase found.
3114  return node->element();
3115}
3116
3117// Helpers for setting up / tearing down the given environment.  They
3118// are for use in the List::ForEach() method.
3119static void SetUpEnvironment(Environment* env) { env->SetUp(); }
3120static void TearDownEnvironment(Environment* env) { env->TearDown(); }
3121
3122// Runs all tests in this UnitTest object, prints the result, and
3123// returns 0 if all tests are successful, or 1 otherwise.  If any
3124// exception is thrown during a test on Windows, this test is
3125// considered to be failed, but the rest of the tests will still be
3126// run.  (We disable exceptions on Linux and Mac OS X, so the issue
3127// doesn't apply there.)
3128int UnitTestImpl::RunAllTests() {
3129  // Makes sure InitGoogleTest() was called.
3130  if (!GTestIsInitialized()) {
3131    printf("%s",
3132           "\nThis test program did NOT call ::testing::InitGoogleTest "
3133           "before calling RUN_ALL_TESTS().  Please fix it.\n");
3134    return 1;
3135  }
3136
3137  // Lists all the tests and exits if the --gtest_list_tests
3138  // flag was specified.
3139  if (GTEST_FLAG(list_tests)) {
3140    ListAllTests();
3141    return 0;
3142  }
3143
3144  // True iff we are in a subprocess for running a thread-safe-style
3145  // death test.
3146  bool in_subprocess_for_death_test = false;
3147
3148#ifdef GTEST_HAS_DEATH_TEST
3149  internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());
3150  in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL);
3151#endif  // GTEST_HAS_DEATH_TEST
3152
3153  UnitTestEventListenerInterface * const printer = result_printer();
3154
3155  // Compares the full test names with the filter to decide which
3156  // tests to run.
3157  const bool has_tests_to_run = FilterTests() > 0;
3158  // True iff at least one test has failed.
3159  bool failed = false;
3160
3161  // How many times to repeat the tests?  We don't want to repeat them
3162  // when we are inside the subprocess of a death test.
3163  const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);
3164  // Repeats forever if the repeat count is negative.
3165  const bool forever = repeat < 0;
3166  for (int i = 0; forever || i != repeat; i++) {
3167    if (repeat != 1) {
3168      printf("\nRepeating all tests (iteration %d) . . .\n\n", i + 1);
3169    }
3170
3171    // Tells the unit test event listener that the tests are about to
3172    // start.
3173    printer->OnUnitTestStart(parent_);
3174
3175    const TimeInMillis start = GetTimeInMillis();
3176
3177    // Runs each test case if there is at least one test to run.
3178    if (has_tests_to_run) {
3179      // Sets up all environments beforehand.
3180      printer->OnGlobalSetUpStart(parent_);
3181      environments_.ForEach(SetUpEnvironment);
3182      printer->OnGlobalSetUpEnd(parent_);
3183
3184      // Runs the tests only if there was no fatal failure during global
3185      // set-up.
3186      if (!Test::HasFatalFailure()) {
3187        test_cases_.ForEach(TestCase::RunTestCase);
3188      }
3189
3190      // Tears down all environments in reverse order afterwards.
3191      printer->OnGlobalTearDownStart(parent_);
3192      environments_in_reverse_order_.ForEach(TearDownEnvironment);
3193      printer->OnGlobalTearDownEnd(parent_);
3194    }
3195
3196    elapsed_time_ = GetTimeInMillis() - start;
3197
3198    // Tells the unit test event listener that the tests have just
3199    // finished.
3200    printer->OnUnitTestEnd(parent_);
3201
3202    // Gets the result and clears it.
3203    if (!Passed()) {
3204      failed = true;
3205    }
3206    ClearResult();
3207  }
3208
3209  // Returns 0 if all tests passed, or 1 other wise.
3210  return failed ? 1 : 0;
3211}
3212
3213// Compares the name of each test with the user-specified filter to
3214// decide whether the test should be run, then records the result in
3215// each TestCase and TestInfo object.
3216// Returns the number of tests that should run.
3217int UnitTestImpl::FilterTests() {
3218  int num_runnable_tests = 0;
3219  for (const internal::ListNode<TestCase *> *test_case_node =
3220       test_cases_.Head();
3221       test_case_node != NULL;
3222       test_case_node = test_case_node->next()) {
3223    TestCase * const test_case = test_case_node->element();
3224    const String &test_case_name = test_case->name();
3225    test_case->set_should_run(false);
3226
3227    for (const internal::ListNode<TestInfo *> *test_info_node =
3228           test_case->test_info_list().Head();
3229         test_info_node != NULL;
3230         test_info_node = test_info_node->next()) {
3231      TestInfo * const test_info = test_info_node->element();
3232      const String test_name(test_info->name());
3233      // A test is disabled if test case name or test name matches
3234      // kDisableTestPattern.
3235      const bool is_disabled =
3236        internal::UnitTestOptions::PatternMatchesString(kDisableTestPattern,
3237            test_case_name.c_str()) ||
3238        internal::UnitTestOptions::PatternMatchesString(kDisableTestPattern,
3239            test_name.c_str());
3240      test_info->impl()->set_is_disabled(is_disabled);
3241
3242      const bool should_run = !is_disabled &&
3243          internal::UnitTestOptions::FilterMatchesTest(test_case_name,
3244                                                       test_name);
3245      test_info->impl()->set_should_run(should_run);
3246      test_case->set_should_run(test_case->should_run() || should_run);
3247      if (should_run) {
3248        num_runnable_tests++;
3249      }
3250    }
3251  }
3252  return num_runnable_tests;
3253}
3254
3255// Lists all tests by name.
3256void UnitTestImpl::ListAllTests() {
3257  for (const internal::ListNode<TestCase*>* test_case_node = test_cases_.Head();
3258       test_case_node != NULL;
3259       test_case_node = test_case_node->next()) {
3260    const TestCase* const test_case = test_case_node->element();
3261
3262    // Prints the test case name following by an indented list of test nodes.
3263    printf("%s.\n", test_case->name());
3264
3265    for (const internal::ListNode<TestInfo*>* test_info_node =
3266         test_case->test_info_list().Head();
3267         test_info_node != NULL;
3268         test_info_node = test_info_node->next()) {
3269      const TestInfo* const test_info = test_info_node->element();
3270
3271      printf("  %s\n", test_info->name());
3272    }
3273  }
3274  fflush(stdout);
3275}
3276
3277// Sets the unit test result printer.
3278//
3279// Does nothing if the input and the current printer object are the
3280// same; otherwise, deletes the old printer object and makes the
3281// input the current printer.
3282void UnitTestImpl::set_result_printer(
3283    UnitTestEventListenerInterface* result_printer) {
3284  if (result_printer_ != result_printer) {
3285    delete result_printer_;
3286    result_printer_ = result_printer;
3287  }
3288}
3289
3290// Returns the current unit test result printer if it is not NULL;
3291// otherwise, creates an appropriate result printer, makes it the
3292// current printer, and returns it.
3293UnitTestEventListenerInterface* UnitTestImpl::result_printer() {
3294  if (result_printer_ != NULL) {
3295    return result_printer_;
3296  }
3297
3298#ifdef GTEST_HAS_DEATH_TEST
3299  if (internal_run_death_test_flag_.get() != NULL) {
3300    result_printer_ = new NullUnitTestResultPrinter;
3301    return result_printer_;
3302  }
3303#endif  // GTEST_HAS_DEATH_TEST
3304
3305  UnitTestEventsRepeater *repeater = new UnitTestEventsRepeater;
3306  const String& output_format = internal::UnitTestOptions::GetOutputFormat();
3307  if (output_format == "xml") {
3308    repeater->AddListener(new XmlUnitTestResultPrinter(
3309        internal::UnitTestOptions::GetOutputFile().c_str()));
3310  } else if (output_format != "") {
3311      printf("WARNING: unrecognized output format \"%s\" ignored.\n",
3312             output_format.c_str());
3313      fflush(stdout);
3314  }
3315  repeater->AddListener(new PrettyUnitTestResultPrinter);
3316  result_printer_ = repeater;
3317  return result_printer_;
3318}
3319
3320// Sets the OS stack trace getter.
3321//
3322// Does nothing if the input and the current OS stack trace getter are
3323// the same; otherwise, deletes the old getter and makes the input the
3324// current getter.
3325void UnitTestImpl::set_os_stack_trace_getter(
3326    OsStackTraceGetterInterface* getter) {
3327  if (os_stack_trace_getter_ != getter) {
3328    delete os_stack_trace_getter_;
3329    os_stack_trace_getter_ = getter;
3330  }
3331}
3332
3333// Returns the current OS stack trace getter if it is not NULL;
3334// otherwise, creates an OsStackTraceGetter, makes it the current
3335// getter, and returns it.
3336OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
3337  if (os_stack_trace_getter_ == NULL) {
3338    os_stack_trace_getter_ = new OsStackTraceGetter;
3339  }
3340
3341  return os_stack_trace_getter_;
3342}
3343
3344// Returns the TestResult for the test that's currently running, or
3345// the TestResult for the ad hoc test if no test is running.
3346internal::TestResult* UnitTestImpl::current_test_result() {
3347  return current_test_info_ ?
3348    current_test_info_->impl()->result() : &ad_hoc_test_result_;
3349}
3350
3351// TestInfoImpl constructor.
3352TestInfoImpl::TestInfoImpl(TestInfo* parent,
3353                           const char* test_case_name,
3354                           const char* name,
3355                           TypeId fixture_class_id,
3356                           TestMaker maker) :
3357    parent_(parent),
3358    test_case_name_(String(test_case_name)),
3359    name_(String(name)),
3360    fixture_class_id_(fixture_class_id),
3361    should_run_(false),
3362    is_disabled_(false),
3363    maker_(maker) {
3364}
3365
3366// TestInfoImpl destructor.
3367TestInfoImpl::~TestInfoImpl() {
3368}
3369
3370}  // namespace internal
3371
3372namespace internal {
3373
3374// Parses a string as a command line flag.  The string should have
3375// the format "--flag=value".  When def_optional is true, the "=value"
3376// part can be omitted.
3377//
3378// Returns the value of the flag, or NULL if the parsing failed.
3379const char* ParseFlagValue(const char* str,
3380                           const char* flag,
3381                           bool def_optional) {
3382  // str and flag must not be NULL.
3383  if (str == NULL || flag == NULL) return NULL;
3384
3385  // The flag must start with "--" followed by GTEST_FLAG_PREFIX.
3386  const String flag_str = String::Format("--%s%s", GTEST_FLAG_PREFIX, flag);
3387  const size_t flag_len = flag_str.GetLength();
3388  if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;
3389
3390  // Skips the flag name.
3391  const char* flag_end = str + flag_len;
3392
3393  // When def_optional is true, it's OK to not have a "=value" part.
3394  if (def_optional && (flag_end[0] == '\0')) {
3395    return flag_end;
3396  }
3397
3398  // If def_optional is true and there are more characters after the
3399  // flag name, or if def_optional is false, there must be a '=' after
3400  // the flag name.
3401  if (flag_end[0] != '=') return NULL;
3402
3403  // Returns the string after "=".
3404  return flag_end + 1;
3405}
3406
3407// Parses a string for a bool flag, in the form of either
3408// "--flag=value" or "--flag".
3409//
3410// In the former case, the value is taken as true as long as it does
3411// not start with '0', 'f', or 'F'.
3412//
3413// In the latter case, the value is taken as true.
3414//
3415// On success, stores the value of the flag in *value, and returns
3416// true.  On failure, returns false without changing *value.
3417bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
3418  // Gets the value of the flag as a string.
3419  const char* const value_str = ParseFlagValue(str, flag, true);
3420
3421  // Aborts if the parsing failed.
3422  if (value_str == NULL) return false;
3423
3424  // Converts the string value to a bool.
3425  *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
3426  return true;
3427}
3428
3429// Parses a string for an Int32 flag, in the form of
3430// "--flag=value".
3431//
3432// On success, stores the value of the flag in *value, and returns
3433// true.  On failure, returns false without changing *value.
3434bool ParseInt32Flag(const char* str, const char* flag, Int32* value) {
3435  // Gets the value of the flag as a string.
3436  const char* const value_str = ParseFlagValue(str, flag, false);
3437
3438  // Aborts if the parsing failed.
3439  if (value_str == NULL) return false;
3440
3441  // Sets *value to the value of the flag.
3442  return ParseInt32(Message() << "The value of flag --" << flag,
3443                    value_str, value);
3444}
3445
3446// Parses a string for a string flag, in the form of
3447// "--flag=value".
3448//
3449// On success, stores the value of the flag in *value, and returns
3450// true.  On failure, returns false without changing *value.
3451bool ParseStringFlag(const char* str, const char* flag, String* value) {
3452  // Gets the value of the flag as a string.
3453  const char* const value_str = ParseFlagValue(str, flag, false);
3454
3455  // Aborts if the parsing failed.
3456  if (value_str == NULL) return false;
3457
3458  // Sets *value to the value of the flag.
3459  *value = value_str;
3460  return true;
3461}
3462
3463// The internal implementation of InitGoogleTest().
3464//
3465// The type parameter CharType can be instantiated to either char or
3466// wchar_t.
3467template <typename CharType>
3468void InitGoogleTestImpl(int* argc, CharType** argv) {
3469  g_parse_gtest_flags_called = true;
3470  if (*argc <= 0) return;
3471
3472#ifdef GTEST_HAS_DEATH_TEST
3473  g_argvs.clear();
3474  for (int i = 0; i != *argc; i++) {
3475    g_argvs.push_back(StreamableToString(argv[i]));
3476  }
3477#endif  // GTEST_HAS_DEATH_TEST
3478
3479  for (int i = 1; i != *argc; i++) {
3480    const String arg_string = StreamableToString(argv[i]);
3481    const char* const arg = arg_string.c_str();
3482
3483    using internal::ParseBoolFlag;
3484    using internal::ParseInt32Flag;
3485    using internal::ParseStringFlag;
3486
3487    // Do we see a Google Test flag?
3488    if (ParseBoolFlag(arg, kBreakOnFailureFlag,
3489                      &GTEST_FLAG(break_on_failure)) ||
3490        ParseBoolFlag(arg, kCatchExceptionsFlag,
3491                      &GTEST_FLAG(catch_exceptions)) ||
3492        ParseStringFlag(arg, kColorFlag, &GTEST_FLAG(color)) ||
3493        ParseStringFlag(arg, kDeathTestStyleFlag,
3494                        &GTEST_FLAG(death_test_style)) ||
3495        ParseStringFlag(arg, kFilterFlag, &GTEST_FLAG(filter)) ||
3496        ParseStringFlag(arg, kInternalRunDeathTestFlag,
3497                        &GTEST_FLAG(internal_run_death_test)) ||
3498        ParseBoolFlag(arg, kListTestsFlag, &GTEST_FLAG(list_tests)) ||
3499        ParseStringFlag(arg, kOutputFlag, &GTEST_FLAG(output)) ||
3500        ParseInt32Flag(arg, kRepeatFlag, &GTEST_FLAG(repeat))
3501        ) {
3502      // Yes.  Shift the remainder of the argv list left by one.  Note
3503      // that argv has (*argc + 1) elements, the last one always being
3504      // NULL.  The following loop moves the trailing NULL element as
3505      // well.
3506      for (int j = i; j != *argc; j++) {
3507        argv[j] = argv[j + 1];
3508      }
3509
3510      // Decrements the argument count.
3511      (*argc)--;
3512
3513      // We also need to decrement the iterator as we just removed
3514      // an element.
3515      i--;
3516    }
3517  }
3518}
3519
3520}  // namespace internal
3521
3522// Initializes Google Test.  This must be called before calling
3523// RUN_ALL_TESTS().  In particular, it parses a command line for the
3524// flags that Google Test recognizes.  Whenever a Google Test flag is
3525// seen, it is removed from argv, and *argc is decremented.
3526//
3527// No value is returned.  Instead, the Google Test flag variables are
3528// updated.
3529void InitGoogleTest(int* argc, char** argv) {
3530  internal::g_executable_path = argv[0];
3531  internal::InitGoogleTestImpl(argc, argv);
3532}
3533
3534// This overloaded version can be used in Windows programs compiled in
3535// UNICODE mode.
3536#ifdef GTEST_OS_WINDOWS
3537void InitGoogleTest(int* argc, wchar_t** argv) {
3538  // g_executable_path uses normal characters rather than wide chars, so call
3539  // StreamableToString to convert argv[0] to normal characters (utf8 encoding).
3540  internal::g_executable_path = internal::StreamableToString(argv[0]);
3541  internal::InitGoogleTestImpl(argc, argv);
3542}
3543#endif  // GTEST_OS_WINDOWS
3544
3545}  // namespace testing
3546