~ubuntu-branches/debian/experimental/protobuf/experimental

« back to all changes in this revision

Viewing changes to gtest/src/gtest.cc

  • Committer: Package Import Robot
  • Author(s): Robert S. Edmonds, Micah Anderson, Colin Watson, Steve Langasek, Robert S. Edmonds
  • Date: 2013-10-12 18:32:37 UTC
  • mfrom: (1.3.1) (10.1.4 sid)
  • Revision ID: package-import@ubuntu.com-20131012183237-jz6tvmj9tn68atrf
Tags: 2.5.0-1
[ Micah Anderson ]
* New upstream version. (Closes: #704731.)
* Update debian/watch.
* Refresh patches.

[ Colin Watson ]
* Use the autotools-dev dh addon to update config.guess/config.sub for
  arm64. (Closes: #725976.)

[ Steve Langasek ]
* Don't recommend protobuf-compiler from the bindings, it's not used and
  this doesn't need to be pulled in at runtime. (Closes: #703628.)
* Mark protobuf-compiler Multi-Arch: foreign; the output of this command
  is architecture-independent source, we don't need the version of the
  compiler to match the target arch.
* Bump to debhelper compat 9, so that our libs get installed to the
  multiarch locations.
* Mark the library packages Multi-Arch: same.
* Fix debian/rules to support cross-building of the python bindings.
* Build-depend on libpython-dev, not python-dev, for cross-build
  compatibility.
* (Closes: #726083.)

[ Robert S. Edmonds ]
* Upload to experimental.
* Bump ABI version from 7 to 8.
* Bump Standards-Version to 3.9.4.
* Convert from python-support to dh-python.
* Drop support for python2.6.
* python-protobuf: switch back to the pure Python implementation, as
  upstream appears to no longer be maintaining the current C++ based Python
  binding. See the following upstream issues for details:
  - https://code.google.com/p/protobuf/issues/detail?id=434
  - https://code.google.com/p/protobuf/issues/detail?id=503

Show diffs side-by-side

added added

removed removed

Lines of Context:
31
31
//
32
32
// The Google C++ Testing Framework (Google Test)
33
33
 
34
 
#include <gtest/gtest.h>
35
 
#include <gtest/gtest-spi.h>
 
34
#include "gtest/gtest.h"
 
35
#include "gtest/gtest-spi.h"
36
36
 
37
37
#include <ctype.h>
38
38
#include <math.h>
39
39
#include <stdarg.h>
40
40
#include <stdio.h>
41
41
#include <stdlib.h>
 
42
#include <time.h>
42
43
#include <wchar.h>
43
44
#include <wctype.h>
44
45
 
45
 
#include <ostream>
 
46
#include <algorithm>
 
47
#include <ostream>  // NOLINT
 
48
#include <sstream>
 
49
#include <vector>
46
50
 
47
51
#if GTEST_OS_LINUX
48
52
 
49
53
// TODO(kenton@google.com): Use autoconf to detect availability of
50
54
// gettimeofday().
51
 
#define GTEST_HAS_GETTIMEOFDAY_ 1
 
55
# define GTEST_HAS_GETTIMEOFDAY_ 1
52
56
 
53
 
#include <fcntl.h>
54
 
#include <limits.h>
55
 
#include <sched.h>
 
57
# include <fcntl.h>  // NOLINT
 
58
# include <limits.h>  // NOLINT
 
59
# include <sched.h>  // NOLINT
56
60
// Declares vsnprintf().  This header is not available on Windows.
57
 
#include <strings.h>
58
 
#include <sys/mman.h>
59
 
#include <sys/time.h>
60
 
#include <unistd.h>
61
 
#include <string>
62
 
#include <vector>
 
61
# include <strings.h>  // NOLINT
 
62
# include <sys/mman.h>  // NOLINT
 
63
# include <sys/time.h>  // NOLINT
 
64
# include <unistd.h>  // NOLINT
 
65
# include <string>
63
66
 
64
67
#elif GTEST_OS_SYMBIAN
65
 
#define GTEST_HAS_GETTIMEOFDAY_ 1
66
 
#include <sys/time.h>  // NOLINT
 
68
# define GTEST_HAS_GETTIMEOFDAY_ 1
 
69
# include <sys/time.h>  // NOLINT
67
70
 
68
71
#elif GTEST_OS_ZOS
69
 
#define GTEST_HAS_GETTIMEOFDAY_ 1
70
 
#include <sys/time.h>  // NOLINT
 
72
# define GTEST_HAS_GETTIMEOFDAY_ 1
 
73
# include <sys/time.h>  // NOLINT
71
74
 
72
75
// On z/OS we additionally need strings.h for strcasecmp.
73
 
#include <strings.h>  // NOLINT
 
76
# include <strings.h>  // NOLINT
74
77
 
75
78
#elif GTEST_OS_WINDOWS_MOBILE  // We are on Windows CE.
76
79
 
77
 
#include <windows.h>  // NOLINT
 
80
# include <windows.h>  // NOLINT
78
81
 
79
82
#elif GTEST_OS_WINDOWS  // We are on Windows proper.
80
83
 
81
 
#include <io.h>  // NOLINT
82
 
#include <sys/timeb.h>  // NOLINT
83
 
#include <sys/types.h>  // NOLINT
84
 
#include <sys/stat.h>  // NOLINT
 
84
# include <io.h>  // NOLINT
 
85
# include <sys/timeb.h>  // NOLINT
 
86
# include <sys/types.h>  // NOLINT
 
87
# include <sys/stat.h>  // NOLINT
85
88
 
86
 
#if GTEST_OS_WINDOWS_MINGW
 
89
# if GTEST_OS_WINDOWS_MINGW
87
90
// MinGW has gettimeofday() but not _ftime64().
88
91
// TODO(kenton@google.com): Use autoconf to detect availability of
89
92
//   gettimeofday().
90
93
// TODO(kenton@google.com): There are other ways to get the time on
91
94
//   Windows, like GetTickCount() or GetSystemTimeAsFileTime().  MinGW
92
95
//   supports these.  consider using them instead.
93
 
#define GTEST_HAS_GETTIMEOFDAY_ 1
94
 
#include <sys/time.h>  // NOLINT
95
 
#endif  // GTEST_OS_WINDOWS_MINGW
 
96
#  define GTEST_HAS_GETTIMEOFDAY_ 1
 
97
#  include <sys/time.h>  // NOLINT
 
98
# endif  // GTEST_OS_WINDOWS_MINGW
96
99
 
97
100
// cpplint thinks that the header is already included, so we want to
98
101
// silence it.
99
 
#include <windows.h>  // NOLINT
 
102
# include <windows.h>  // NOLINT
100
103
 
101
104
#else
102
105
 
103
106
// Assume other platforms have gettimeofday().
104
107
// TODO(kenton@google.com): Use autoconf to detect availability of
105
108
//   gettimeofday().
106
 
#define GTEST_HAS_GETTIMEOFDAY_ 1
 
109
# define GTEST_HAS_GETTIMEOFDAY_ 1
107
110
 
108
111
// cpplint thinks that the header is already included, so we want to
109
112
// silence it.
110
 
#include <sys/time.h>  // NOLINT
111
 
#include <unistd.h>  // NOLINT
 
113
# include <sys/time.h>  // NOLINT
 
114
# include <unistd.h>  // NOLINT
112
115
 
113
116
#endif  // GTEST_OS_LINUX
114
117
 
115
118
#if GTEST_HAS_EXCEPTIONS
116
 
#include <stdexcept>
 
119
# include <stdexcept>
 
120
#endif
 
121
 
 
122
#if GTEST_CAN_STREAM_RESULTS_
 
123
# include <arpa/inet.h>  // NOLINT
 
124
# include <netdb.h>  // NOLINT
117
125
#endif
118
126
 
119
127
// Indicates that this translation unit is part of Google Test's
126
134
#undef GTEST_IMPLEMENTATION_
127
135
 
128
136
#if GTEST_OS_WINDOWS
129
 
#define vsnprintf _vsnprintf
 
137
# define vsnprintf _vsnprintf
130
138
#endif  // GTEST_OS_WINDOWS
131
139
 
132
140
namespace testing {
133
141
 
 
142
using internal::CountIf;
 
143
using internal::ForEach;
 
144
using internal::GetElementOr;
 
145
using internal::Shuffle;
 
146
 
134
147
// Constants.
135
148
 
136
149
// A test whose test case name or test name matches this filter is
161
174
// stack trace.
162
175
const char kStackTraceMarker[] = "\nStack trace:\n";
163
176
 
 
177
// g_help_flag is true iff the --help flag or an equivalent form is
 
178
// specified on the command line.
 
179
bool g_help_flag = false;
 
180
 
164
181
}  // namespace internal
165
182
 
166
183
GTEST_DEFINE_bool_(
175
192
 
176
193
GTEST_DEFINE_bool_(
177
194
    catch_exceptions,
178
 
    internal::BoolFromGTestEnv("catch_exceptions", false),
 
195
    internal::BoolFromGTestEnv("catch_exceptions", true),
179
196
    "True iff " GTEST_NAME_
180
197
    " should catch exceptions and treat them as test failures.");
181
198
 
242
259
 
243
260
GTEST_DEFINE_int32_(
244
261
    stack_trace_depth,
245
 
        internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
 
262
    internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
246
263
    "The maximum number of stack frames to print when an "
247
264
    "assertion fails.  The valid range is 0 through 100, inclusive.");
248
265
 
 
266
GTEST_DEFINE_string_(
 
267
    stream_result_to,
 
268
    internal::StringFromGTestEnv("stream_result_to", ""),
 
269
    "This flag specifies the host name and the port number on which to stream "
 
270
    "test results. Example: \"localhost:555\". The flag is effective only on "
 
271
    "Linux.");
 
272
 
249
273
GTEST_DEFINE_bool_(
250
274
    throw_on_failure,
251
275
    internal::BoolFromGTestEnv("throw_on_failure", false),
274
298
  return state_ % range;
275
299
}
276
300
 
277
 
// g_help_flag is true iff the --help flag or an equivalent form is
278
 
// specified on the command line.
279
 
static bool g_help_flag = false;
280
 
 
281
301
// GTestIsInitialized() returns true iff the user has initialized
282
302
// Google Test.  Useful for catching the user mistake of not initializing
283
303
// Google Test before calling RUN_ALL_TESTS().
286
306
// Test.  g_init_gtest_count is set to the number of times
287
307
// InitGoogleTest() has been called.  We don't protect this variable
288
308
// under a mutex as it is only accessed in the main thread.
289
 
int g_init_gtest_count = 0;
 
309
GTEST_API_ int g_init_gtest_count = 0;
290
310
static bool GTestIsInitialized() { return g_init_gtest_count != 0; }
291
311
 
292
312
// Iterates over a vector of TestCases, keeping a running sum of the
293
313
// results of calling a given int-returning method on each.
294
314
// Returns the sum.
295
 
static int SumOverTestCaseList(const internal::Vector<TestCase*>& case_list,
 
315
static int SumOverTestCaseList(const std::vector<TestCase*>& case_list,
296
316
                               int (TestCase::*method)() const) {
297
317
  int sum = 0;
298
 
  for (int i = 0; i < case_list.size(); i++) {
299
 
    sum += (case_list.GetElement(i)->*method)();
 
318
  for (size_t i = 0; i < case_list.size(); i++) {
 
319
    sum += (case_list[i]->*method)();
300
320
  }
301
321
  return sum;
302
322
}
341
361
}
342
362
 
343
363
// Mutex for linked pointers.
344
 
Mutex g_linked_ptr_mutex(Mutex::NO_CONSTRUCTOR_NEEDED_FOR_STATIC_MUTEX);
 
364
GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex);
345
365
 
346
366
// Application pathname gotten in InitGoogleTest.
347
 
String g_executable_path;
 
367
std::string g_executable_path;
348
368
 
349
369
// Returns the current application's name, removing directory path if that
350
370
// is present.
363
383
// Functions for processing the gtest_output flag.
364
384
 
365
385
// Returns the output format, or "" for normal printed output.
366
 
String UnitTestOptions::GetOutputFormat() {
 
386
std::string UnitTestOptions::GetOutputFormat() {
367
387
  const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
368
 
  if (gtest_output_flag == NULL) return String("");
 
388
  if (gtest_output_flag == NULL) return std::string("");
369
389
 
370
390
  const char* const colon = strchr(gtest_output_flag, ':');
371
391
  return (colon == NULL) ?
372
 
      String(gtest_output_flag) :
373
 
      String(gtest_output_flag, colon - gtest_output_flag);
 
392
      std::string(gtest_output_flag) :
 
393
      std::string(gtest_output_flag, colon - gtest_output_flag);
374
394
}
375
395
 
376
396
// Returns the name of the requested output file, or the default if none
377
397
// was explicitly specified.
378
 
String UnitTestOptions::GetAbsolutePathToOutputFile() {
 
398
std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
379
399
  const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
380
400
  if (gtest_output_flag == NULL)
381
 
    return String("");
 
401
    return "";
382
402
 
383
403
  const char* const colon = strchr(gtest_output_flag, ':');
384
404
  if (colon == NULL)
385
 
    return String(internal::FilePath::ConcatPaths(
386
 
               internal::FilePath(
387
 
                   UnitTest::GetInstance()->original_working_dir()),
388
 
               internal::FilePath(kDefaultOutputFile)).ToString() );
 
405
    return internal::FilePath::ConcatPaths(
 
406
        internal::FilePath(
 
407
            UnitTest::GetInstance()->original_working_dir()),
 
408
        internal::FilePath(kDefaultOutputFile)).string();
389
409
 
390
410
  internal::FilePath output_name(colon + 1);
391
411
  if (!output_name.IsAbsolutePath())
398
418
        internal::FilePath(colon + 1));
399
419
 
400
420
  if (!output_name.IsDirectory())
401
 
    return output_name.ToString();
 
421
    return output_name.string();
402
422
 
403
423
  internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
404
424
      output_name, internal::GetCurrentExecutableName(),
405
425
      GetOutputFormat().c_str()));
406
 
  return result.ToString();
 
426
  return result.string();
407
427
}
408
428
 
409
429
// Returns true iff the wildcard pattern matches the string.  The
428
448
  }
429
449
}
430
450
 
431
 
bool UnitTestOptions::MatchesFilter(const String& name, const char* filter) {
 
451
bool UnitTestOptions::MatchesFilter(
 
452
    const std::string& name, const char* filter) {
432
453
  const char *cur_pattern = filter;
433
454
  for (;;) {
434
455
    if (PatternMatchesString(cur_pattern, name.c_str())) {
448
469
  }
449
470
}
450
471
 
451
 
// TODO(keithray): move String function implementations to gtest-string.cc.
452
 
 
453
472
// Returns true iff the user-specified filter matches the test case
454
473
// name and the test name.
455
 
bool UnitTestOptions::FilterMatchesTest(const String &test_case_name,
456
 
                                        const String &test_name) {
457
 
  const String& full_name = String::Format("%s.%s",
458
 
                                           test_case_name.c_str(),
459
 
                                           test_name.c_str());
 
474
bool UnitTestOptions::FilterMatchesTest(const std::string &test_case_name,
 
475
                                        const std::string &test_name) {
 
476
  const std::string& full_name = test_case_name + "." + test_name.c_str();
460
477
 
461
478
  // Split --gtest_filter at '-', if there is one, to separate into
462
479
  // positive filter and negative filter portions
463
480
  const char* const p = GTEST_FLAG(filter).c_str();
464
481
  const char* const dash = strchr(p, '-');
465
 
  String positive;
466
 
  String negative;
 
482
  std::string positive;
 
483
  std::string negative;
467
484
  if (dash == NULL) {
468
485
    positive = GTEST_FLAG(filter).c_str();  // Whole string is a positive filter
469
 
    negative = String("");
 
486
    negative = "";
470
487
  } else {
471
 
    positive = String(p, dash - p);  // Everything up to the dash
472
 
    negative = String(dash+1);       // Everything after the dash
 
488
    positive = std::string(p, dash);   // Everything up to the dash
 
489
    negative = std::string(dash + 1);  // Everything after the dash
473
490
    if (positive.empty()) {
474
491
      // Treat '-test1' as the same as '*-test1'
475
492
      positive = kUniversalFilter;
482
499
          !MatchesFilter(full_name, negative.c_str()));
483
500
}
484
501
 
485
 
#if GTEST_OS_WINDOWS
 
502
#if GTEST_HAS_SEH
486
503
// Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
487
504
// given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
488
505
// This function is useful as an __except condition.
489
506
int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
490
 
  // Google Test should handle an exception if:
 
507
  // Google Test should handle a SEH exception if:
491
508
  //   1. the user wants it to, AND
492
 
  //   2. this is not a breakpoint exception.
493
 
  return (GTEST_FLAG(catch_exceptions) &&
494
 
          exception_code != EXCEPTION_BREAKPOINT) ?
495
 
      EXCEPTION_EXECUTE_HANDLER :
496
 
      EXCEPTION_CONTINUE_SEARCH;
 
509
  //   2. this is not a breakpoint exception, AND
 
510
  //   3. this is not a C++ exception (VC++ implements them via SEH,
 
511
  //      apparently).
 
512
  //
 
513
  // SEH exception code for C++ exceptions.
 
514
  // (see http://support.microsoft.com/kb/185294 for more information).
 
515
  const DWORD kCxxExceptionCode = 0xe06d7363;
 
516
 
 
517
  bool should_handle = true;
 
518
 
 
519
  if (!GTEST_FLAG(catch_exceptions))
 
520
    should_handle = false;
 
521
  else if (exception_code == EXCEPTION_BREAKPOINT)
 
522
    should_handle = false;
 
523
  else if (exception_code == kCxxExceptionCode)
 
524
    should_handle = false;
 
525
 
 
526
  return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
497
527
}
498
 
#endif  // GTEST_OS_WINDOWS
 
528
#endif  // GTEST_HAS_SEH
499
529
 
500
530
}  // namespace internal
501
531
 
575
605
                              const char* /* substr_expr */,
576
606
                              const TestPartResultArray& results,
577
607
                              TestPartResult::Type type,
578
 
                              const char* substr) {
579
 
  const String expected(type == TestPartResult::kFatalFailure ?
 
608
                              const string& substr) {
 
609
  const std::string expected(type == TestPartResult::kFatalFailure ?
580
610
                        "1 fatal failure" :
581
611
                        "1 non-fatal failure");
582
612
  Message msg;
586
616
    for (int i = 0; i < results.size(); i++) {
587
617
      msg << "\n" << results.GetTestPartResult(i);
588
618
    }
589
 
    return AssertionFailure(msg);
 
619
    return AssertionFailure() << msg;
590
620
  }
591
621
 
592
622
  const TestPartResult& r = results.GetTestPartResult(0);
593
623
  if (r.type() != type) {
594
 
    msg << "Expected: " << expected << "\n"
595
 
        << "  Actual:\n"
596
 
        << r;
597
 
    return AssertionFailure(msg);
 
624
    return AssertionFailure() << "Expected: " << expected << "\n"
 
625
                              << "  Actual:\n"
 
626
                              << r;
598
627
  }
599
628
 
600
 
  if (strstr(r.message(), substr) == NULL) {
601
 
    msg << "Expected: " << expected << " containing \""
602
 
        << substr << "\"\n"
603
 
        << "  Actual:\n"
604
 
        << r;
605
 
    return AssertionFailure(msg);
 
629
  if (strstr(r.message(), substr.c_str()) == NULL) {
 
630
    return AssertionFailure() << "Expected: " << expected << " containing \""
 
631
                              << substr << "\"\n"
 
632
                              << "  Actual:\n"
 
633
                              << r;
606
634
  }
607
635
 
608
636
  return AssertionSuccess();
614
642
SingleFailureChecker:: SingleFailureChecker(
615
643
    const TestPartResultArray* results,
616
644
    TestPartResult::Type type,
617
 
    const char* substr)
 
645
    const string& substr)
618
646
    : results_(results),
619
647
      type_(type),
620
648
      substr_(substr) {}
624
652
// type and contains the given substring.  If that's not the case, a
625
653
// non-fatal failure will be generated.
626
654
SingleFailureChecker::~SingleFailureChecker() {
627
 
  EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_.c_str());
 
655
  EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_);
628
656
}
629
657
 
630
658
DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
672
700
 
673
701
// Gets the number of successful test cases.
674
702
int UnitTestImpl::successful_test_case_count() const {
675
 
  return test_cases_.CountIf(TestCasePassed);
 
703
  return CountIf(test_cases_, TestCasePassed);
676
704
}
677
705
 
678
706
// Gets the number of failed test cases.
679
707
int UnitTestImpl::failed_test_case_count() const {
680
 
  return test_cases_.CountIf(TestCaseFailed);
 
708
  return CountIf(test_cases_, TestCaseFailed);
681
709
}
682
710
 
683
711
// Gets the number of all test cases.
684
712
int UnitTestImpl::total_test_case_count() const {
685
 
  return test_cases_.size();
 
713
  return static_cast<int>(test_cases_.size());
686
714
}
687
715
 
688
716
// Gets the number of all test cases that contain at least one test
689
717
// that should run.
690
718
int UnitTestImpl::test_case_to_run_count() const {
691
 
  return test_cases_.CountIf(ShouldRunTestCase);
 
719
  return CountIf(test_cases_, ShouldRunTestCase);
692
720
}
693
721
 
694
722
// Gets the number of successful tests.
716
744
  return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count);
717
745
}
718
746
 
719
 
// Returns the current OS stack trace as a String.
 
747
// Returns the current OS stack trace as an std::string.
720
748
//
721
749
// The maximum number of stack frames to be included is specified by
722
750
// the gtest_stack_trace_depth flag.  The skip_count parameter
726
754
// For example, if Foo() calls Bar(), which in turn calls
727
755
// CurrentOsStackTraceExceptTop(1), Foo() will be included in the
728
756
// trace but Bar() and CurrentOsStackTraceExceptTop() won't.
729
 
String UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
 
757
std::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
730
758
  (void)skip_count;
731
 
  return String("");
 
759
  return "";
732
760
}
733
761
 
734
762
// Returns the current time in milliseconds.
756
784
  return 0;
757
785
#elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_
758
786
  __timeb64 now;
759
 
#ifdef _MSC_VER
 
787
 
 
788
# ifdef _MSC_VER
 
789
 
760
790
  // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996
761
791
  // (deprecated function) there.
762
792
  // TODO(kenton@google.com): Use GetTickCount()?  Or use
763
793
  //   SystemTimeToFileTime()
764
 
#pragma warning(push)          // Saves the current warning state.
765
 
#pragma warning(disable:4996)  // Temporarily disables warning 4996.
766
 
  _ftime64(&now);
767
 
#pragma warning(pop)           // Restores the warning state.
768
 
#else
769
 
  _ftime64(&now);
770
 
#endif  // _MSC_VER
 
794
#  pragma warning(push)          // Saves the current warning state.
 
795
#  pragma warning(disable:4996)  // Temporarily disables warning 4996.
 
796
  _ftime64(&now);
 
797
#  pragma warning(pop)           // Restores the warning state.
 
798
# else
 
799
 
 
800
  _ftime64(&now);
 
801
 
 
802
# endif  // _MSC_VER
 
803
 
771
804
  return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
772
805
#elif GTEST_HAS_GETTIMEOFDAY_
773
806
  struct timeval now;
774
807
  gettimeofday(&now, NULL);
775
808
  return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
776
809
#else
777
 
#error "Don't know how to get the current time on your system."
 
810
# error "Don't know how to get the current time on your system."
778
811
#endif
779
812
}
780
813
 
781
814
// Utilities
782
815
 
783
 
// class String
784
 
 
785
 
// Returns the input enclosed in double quotes if it's not NULL;
786
 
// otherwise returns "(null)".  For example, "\"Hello\"" is returned
787
 
// for input "Hello".
788
 
//
789
 
// This is useful for printing a C string in the syntax of a literal.
790
 
//
791
 
// Known issue: escape sequences are not handled yet.
792
 
String String::ShowCStringQuoted(const char* c_str) {
793
 
  return c_str ? String::Format("\"%s\"", c_str) : String("(null)");
794
 
}
795
 
 
796
 
// Copies at most length characters from str into a newly-allocated
797
 
// piece of memory of size length+1.  The memory is allocated with new[].
798
 
// A terminating null byte is written to the memory, and a pointer to it
799
 
// is returned.  If str is NULL, NULL is returned.
800
 
static char* CloneString(const char* str, size_t length) {
801
 
  if (str == NULL) {
802
 
    return NULL;
803
 
  } else {
804
 
    char* const clone = new char[length + 1];
805
 
    posix::StrNCpy(clone, str, length);
806
 
    clone[length] = '\0';
807
 
    return clone;
808
 
  }
809
 
}
810
 
 
811
 
// Clones a 0-terminated C string, allocating memory using new.  The
812
 
// caller is responsible for deleting[] the return value.  Returns the
813
 
// cloned string, or NULL if the input is NULL.
814
 
const char * String::CloneCString(const char* c_str) {
815
 
  return (c_str == NULL) ?
816
 
                    NULL : CloneString(c_str, strlen(c_str));
817
 
}
 
816
// class String.
818
817
 
819
818
#if GTEST_OS_WINDOWS_MOBILE
820
819
// Creates a UTF-16 wide string from the given ANSI string, allocating
871
870
// encoding, and streams the result to the given Message object.
872
871
static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
873
872
                                     Message* msg) {
874
 
  // TODO(wan): consider allowing a testing::String object to
875
 
  // contain '\0'.  This will make it behave more like std::string,
876
 
  // and will allow ToUtf8String() to return the correct encoding
877
 
  // for '\0' s.t. we can get rid of the conditional here (and in
878
 
  // several other places).
879
873
  for (size_t i = 0; i != length; ) {  // NOLINT
880
874
    if (wstr[i] != L'\0') {
881
875
      *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
910
904
}
911
905
#endif  // GTEST_HAS_GLOBAL_WSTRING
912
906
 
913
 
namespace internal {
914
 
 
915
 
// Formats a value to be used in a failure message.
916
 
 
917
 
// For a char value, we print it as a C++ char literal and as an
918
 
// unsigned integer (both in decimal and in hexadecimal).
919
 
String FormatForFailureMessage(char ch) {
920
 
  const unsigned int ch_as_uint = ch;
921
 
  // A String object cannot contain '\0', so we print "\\0" when ch is
922
 
  // '\0'.
923
 
  return String::Format("'%s' (%u, 0x%X)",
924
 
                        ch ? String::Format("%c", ch).c_str() : "\\0",
925
 
                        ch_as_uint, ch_as_uint);
926
 
}
927
 
 
928
 
// For a wchar_t value, we print it as a C++ wchar_t literal and as an
929
 
// unsigned integer (both in decimal and in hexidecimal).
930
 
String FormatForFailureMessage(wchar_t wchar) {
931
 
  // The C++ standard doesn't specify the exact size of the wchar_t
932
 
  // type.  It just says that it shall have the same size as another
933
 
  // integral type, called its underlying type.
934
 
  //
935
 
  // Therefore, in order to print a wchar_t value in the numeric form,
936
 
  // we first convert it to the largest integral type (UInt64) and
937
 
  // then print the converted value.
938
 
  //
939
 
  // We use streaming to print the value as "%llu" doesn't work
940
 
  // correctly with MSVC 7.1.
941
 
  const UInt64 wchar_as_uint64 = wchar;
942
 
  Message msg;
943
 
  // A String object cannot contain '\0', so we print "\\0" when wchar is
944
 
  // L'\0'.
945
 
  char buffer[32];  // CodePointToUtf8 requires a buffer that big.
946
 
  msg << "L'"
947
 
      << (wchar ? CodePointToUtf8(static_cast<UInt32>(wchar), buffer) : "\\0")
948
 
      << "' (" << wchar_as_uint64 << ", 0x" << ::std::setbase(16)
949
 
      << wchar_as_uint64 << ")";
950
 
  return msg.GetString();
951
 
}
952
 
 
953
 
}  // namespace internal
954
 
 
955
 
// AssertionResult constructor.
956
 
AssertionResult::AssertionResult(const internal::String& failure_message)
957
 
    : failure_message_(failure_message) {
958
 
}
959
 
 
 
907
// AssertionResult constructors.
 
908
// Used in EXPECT_TRUE/FALSE(assertion_result).
 
909
AssertionResult::AssertionResult(const AssertionResult& other)
 
910
    : success_(other.success_),
 
911
      message_(other.message_.get() != NULL ?
 
912
               new ::std::string(*other.message_) :
 
913
               static_cast< ::std::string*>(NULL)) {
 
914
}
 
915
 
 
916
// Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
 
917
AssertionResult AssertionResult::operator!() const {
 
918
  AssertionResult negation(!success_);
 
919
  if (message_.get() != NULL)
 
920
    negation << *message_;
 
921
  return negation;
 
922
}
960
923
 
961
924
// Makes a successful assertion result.
962
925
AssertionResult AssertionSuccess() {
963
 
  return AssertionResult();
 
926
  return AssertionResult(true);
964
927
}
965
928
 
 
929
// Makes a failed assertion result.
 
930
AssertionResult AssertionFailure() {
 
931
  return AssertionResult(false);
 
932
}
966
933
 
967
934
// Makes a failed assertion result with the given failure message.
 
935
// Deprecated; use AssertionFailure() << message.
968
936
AssertionResult AssertionFailure(const Message& message) {
969
 
  return AssertionResult(message.GetString());
 
937
  return AssertionFailure() << message;
970
938
}
971
939
 
972
940
namespace internal {
988
956
// be inserted into the message.
989
957
AssertionResult EqFailure(const char* expected_expression,
990
958
                          const char* actual_expression,
991
 
                          const String& expected_value,
992
 
                          const String& actual_value,
 
959
                          const std::string& expected_value,
 
960
                          const std::string& actual_value,
993
961
                          bool ignoring_case) {
994
962
  Message msg;
995
963
  msg << "Value of: " << actual_expression;
1005
973
    msg << "\nWhich is: " << expected_value;
1006
974
  }
1007
975
 
1008
 
  return AssertionFailure(msg);
 
976
  return AssertionFailure() << msg;
1009
977
}
1010
978
 
 
979
// Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
 
980
std::string GetBoolAssertionFailureMessage(
 
981
    const AssertionResult& assertion_result,
 
982
    const char* expression_text,
 
983
    const char* actual_predicate_value,
 
984
    const char* expected_predicate_value) {
 
985
  const char* actual_message = assertion_result.message();
 
986
  Message msg;
 
987
  msg << "Value of: " << expression_text
 
988
      << "\n  Actual: " << actual_predicate_value;
 
989
  if (actual_message[0] != '\0')
 
990
    msg << " (" << actual_message << ")";
 
991
  msg << "\nExpected: " << expected_predicate_value;
 
992
  return msg.GetString();
 
993
}
1011
994
 
1012
995
// Helper function for implementing ASSERT_NEAR.
1013
996
AssertionResult DoubleNearPredFormat(const char* expr1,
1021
1004
 
1022
1005
  // TODO(wan): do not print the value of an expression if it's
1023
1006
  // already a literal.
1024
 
  Message msg;
1025
 
  msg << "The difference between " << expr1 << " and " << expr2
 
1007
  return AssertionFailure()
 
1008
      << "The difference between " << expr1 << " and " << expr2
1026
1009
      << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"
1027
1010
      << expr1 << " evaluates to " << val1 << ",\n"
1028
1011
      << expr2 << " evaluates to " << val2 << ", and\n"
1029
1012
      << abs_error_expr << " evaluates to " << abs_error << ".";
1030
 
  return AssertionFailure(msg);
1031
1013
}
1032
1014
 
1033
1015
 
1052
1034
  // val2 is NaN, as the IEEE floating-point standard requires that
1053
1035
  // any predicate involving a NaN must return false.
1054
1036
 
1055
 
  StrStream val1_ss;
 
1037
  ::std::stringstream val1_ss;
1056
1038
  val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
1057
1039
          << val1;
1058
1040
 
1059
 
  StrStream val2_ss;
 
1041
  ::std::stringstream val2_ss;
1060
1042
  val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
1061
1043
          << val2;
1062
1044
 
1063
 
  Message msg;
1064
 
  msg << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
1065
 
      << "  Actual: " << StrStreamToString(&val1_ss) << " vs "
1066
 
      << StrStreamToString(&val2_ss);
1067
 
 
1068
 
  return AssertionFailure(msg);
 
1045
  return AssertionFailure()
 
1046
      << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
 
1047
      << "  Actual: " << StringStreamToString(&val1_ss) << " vs "
 
1048
      << StringStreamToString(&val2_ss);
1069
1049
}
1070
1050
 
1071
1051
}  // namespace internal
1112
1092
  if (val1 op val2) {\
1113
1093
    return AssertionSuccess();\
1114
1094
  } else {\
1115
 
    Message msg;\
1116
 
    msg << "Expected: (" << expr1 << ") " #op " (" << expr2\
 
1095
    return AssertionFailure() \
 
1096
        << "Expected: (" << expr1 << ") " #op " (" << expr2\
1117
1097
        << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
1118
1098
        << " vs " << FormatForComparisonFailureMessage(val2, val1);\
1119
 
    return AssertionFailure(msg);\
1120
1099
  }\
1121
1100
}
1122
1101
 
1149
1128
 
1150
1129
  return EqFailure(expected_expression,
1151
1130
                   actual_expression,
1152
 
                   String::ShowCStringQuoted(expected),
1153
 
                   String::ShowCStringQuoted(actual),
 
1131
                   PrintToString(expected),
 
1132
                   PrintToString(actual),
1154
1133
                   false);
1155
1134
}
1156
1135
 
1165
1144
 
1166
1145
  return EqFailure(expected_expression,
1167
1146
                   actual_expression,
1168
 
                   String::ShowCStringQuoted(expected),
1169
 
                   String::ShowCStringQuoted(actual),
 
1147
                   PrintToString(expected),
 
1148
                   PrintToString(actual),
1170
1149
                   true);
1171
1150
}
1172
1151
 
1178
1157
  if (!String::CStringEquals(s1, s2)) {
1179
1158
    return AssertionSuccess();
1180
1159
  } else {
1181
 
    Message msg;
1182
 
    msg << "Expected: (" << s1_expression << ") != ("
1183
 
        << s2_expression << "), actual: \""
1184
 
        << s1 << "\" vs \"" << s2 << "\"";
1185
 
    return AssertionFailure(msg);
 
1160
    return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
 
1161
                              << s2_expression << "), actual: \""
 
1162
                              << s1 << "\" vs \"" << s2 << "\"";
1186
1163
  }
1187
1164
}
1188
1165
 
1194
1171
  if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
1195
1172
    return AssertionSuccess();
1196
1173
  } else {
1197
 
    Message msg;
1198
 
    msg << "Expected: (" << s1_expression << ") != ("
 
1174
    return AssertionFailure()
 
1175
        << "Expected: (" << s1_expression << ") != ("
1199
1176
        << s2_expression << ") (ignoring case), actual: \""
1200
1177
        << s1 << "\" vs \"" << s2 << "\"";
1201
 
    return AssertionFailure(msg);
1202
1178
  }
1203
1179
}
1204
1180
 
1247
1223
 
1248
1224
  const bool is_wide_string = sizeof(needle[0]) > 1;
1249
1225
  const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
1250
 
  return AssertionFailure(
1251
 
      Message()
 
1226
  return AssertionFailure()
1252
1227
      << "Value of: " << needle_expr << "\n"
1253
1228
      << "  Actual: " << begin_string_quote << needle << "\"\n"
1254
1229
      << "Expected: " << (expected_to_be_substring ? "" : "not ")
1255
1230
      << "a substring of " << haystack_expr << "\n"
1256
 
      << "Which is: " << begin_string_quote << haystack << "\"");
 
1231
      << "Which is: " << begin_string_quote << haystack << "\"";
1257
1232
}
1258
1233
 
1259
1234
}  // namespace
1286
1261
  return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1287
1262
}
1288
1263
 
1289
 
#if GTEST_HAS_STD_STRING
1290
1264
AssertionResult IsSubstring(
1291
1265
    const char* needle_expr, const char* haystack_expr,
1292
1266
    const ::std::string& needle, const ::std::string& haystack) {
1298
1272
    const ::std::string& needle, const ::std::string& haystack) {
1299
1273
  return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1300
1274
}
1301
 
#endif  // GTEST_HAS_STD_STRING
1302
1275
 
1303
1276
#if GTEST_HAS_STD_WSTRING
1304
1277
AssertionResult IsSubstring(
1324
1297
AssertionResult HRESULTFailureHelper(const char* expr,
1325
1298
                                     const char* expected,
1326
1299
                                     long hr) {  // NOLINT
1327
 
#if GTEST_OS_WINDOWS_MOBILE
 
1300
# if GTEST_OS_WINDOWS_MOBILE
 
1301
 
1328
1302
  // Windows CE doesn't support FormatMessage.
1329
1303
  const char error_text[] = "";
1330
 
#else
 
1304
 
 
1305
# else
 
1306
 
1331
1307
  // Looks up the human-readable system message for the HRESULT code
1332
1308
  // and since we're not passing any params to FormatMessage, we don't
1333
1309
  // want inserts expanded.
1344
1320
                                          kBufSize,  // buf size
1345
1321
                                          NULL);  // no arguments for inserts
1346
1322
  // Trims tailing white space (FormatMessage leaves a trailing cr-lf)
1347
 
  for (; message_length && isspace(error_text[message_length - 1]);
 
1323
  for (; message_length && IsSpace(error_text[message_length - 1]);
1348
1324
          --message_length) {
1349
1325
    error_text[message_length - 1] = '\0';
1350
1326
  }
1351
 
#endif  // GTEST_OS_WINDOWS_MOBILE
1352
 
 
1353
 
  const String error_hex(String::Format("0x%08X ", hr));
1354
 
  Message msg;
1355
 
  msg << "Expected: " << expr << " " << expected << ".\n"
 
1327
 
 
1328
# endif  // GTEST_OS_WINDOWS_MOBILE
 
1329
 
 
1330
  const std::string error_hex(String::Format("0x%08X ", hr));
 
1331
  return ::testing::AssertionFailure()
 
1332
      << "Expected: " << expr << " " << expected << ".\n"
1356
1333
      << "  Actual: " << error_hex << error_text << "\n";
1357
 
 
1358
 
  return ::testing::AssertionFailure(msg);
1359
1334
}
1360
1335
 
1361
1336
}  // namespace
1486
1461
// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
1487
1462
// and contains invalid UTF-16 surrogate pairs, values in those pairs
1488
1463
// will be encoded as individual Unicode characters from Basic Normal Plane.
1489
 
String WideStringToUtf8(const wchar_t* str, int num_chars) {
 
1464
std::string WideStringToUtf8(const wchar_t* str, int num_chars) {
1490
1465
  if (num_chars == -1)
1491
1466
    num_chars = static_cast<int>(wcslen(str));
1492
1467
 
1493
 
  StrStream stream;
 
1468
  ::std::stringstream stream;
1494
1469
  for (int i = 0; i < num_chars; ++i) {
1495
1470
    UInt32 unicode_code_point;
1496
1471
 
1507
1482
    char buffer[32];  // CodePointToUtf8 requires a buffer this big.
1508
1483
    stream << CodePointToUtf8(unicode_code_point, buffer);
1509
1484
  }
1510
 
  return StrStreamToString(&stream);
 
1485
  return StringStreamToString(&stream);
1511
1486
}
1512
1487
 
1513
 
// Converts a wide C string to a String using the UTF-8 encoding.
 
1488
// Converts a wide C string to an std::string using the UTF-8 encoding.
1514
1489
// NULL will be converted to "(null)".
1515
 
String String::ShowWideCString(const wchar_t * wide_c_str) {
1516
 
  if (wide_c_str == NULL) return String("(null)");
1517
 
 
1518
 
  return String(internal::WideStringToUtf8(wide_c_str, -1).c_str());
1519
 
}
1520
 
 
1521
 
// Similar to ShowWideCString(), except that this function encloses
1522
 
// the converted string in double quotes.
1523
 
String String::ShowWideCStringQuoted(const wchar_t* wide_c_str) {
1524
 
  if (wide_c_str == NULL) return String("(null)");
1525
 
 
1526
 
  return String::Format("L\"%s\"",
1527
 
                        String::ShowWideCString(wide_c_str).c_str());
 
1490
std::string String::ShowWideCString(const wchar_t * wide_c_str) {
 
1491
  if (wide_c_str == NULL)  return "(null)";
 
1492
 
 
1493
  return internal::WideStringToUtf8(wide_c_str, -1);
1528
1494
}
1529
1495
 
1530
1496
// Compares two wide C strings.  Returns true iff they have the same
1552
1518
 
1553
1519
  return EqFailure(expected_expression,
1554
1520
                   actual_expression,
1555
 
                   String::ShowWideCStringQuoted(expected),
1556
 
                   String::ShowWideCStringQuoted(actual),
 
1521
                   PrintToString(expected),
 
1522
                   PrintToString(actual),
1557
1523
                   false);
1558
1524
}
1559
1525
 
1566
1532
    return AssertionSuccess();
1567
1533
  }
1568
1534
 
1569
 
  Message msg;
1570
 
  msg << "Expected: (" << s1_expression << ") != ("
1571
 
      << s2_expression << "), actual: "
1572
 
      << String::ShowWideCStringQuoted(s1)
1573
 
      << " vs " << String::ShowWideCStringQuoted(s2);
1574
 
  return AssertionFailure(msg);
 
1535
  return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
 
1536
                            << s2_expression << "), actual: "
 
1537
                            << PrintToString(s1)
 
1538
                            << " vs " << PrintToString(s2);
1575
1539
}
1576
1540
 
1577
1541
// Compares two C strings, ignoring case.  Returns true iff they have
1602
1566
  // current locale.
1603
1567
bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
1604
1568
                                              const wchar_t* rhs) {
1605
 
  if ( lhs == NULL ) return rhs == NULL;
 
1569
  if (lhs == NULL) return rhs == NULL;
1606
1570
 
1607
 
  if ( rhs == NULL ) return false;
 
1571
  if (rhs == NULL) return false;
1608
1572
 
1609
1573
#if GTEST_OS_WINDOWS
1610
1574
  return _wcsicmp(lhs, rhs) == 0;
1611
 
#elif GTEST_OS_LINUX
 
1575
#elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID
1612
1576
  return wcscasecmp(lhs, rhs) == 0;
1613
1577
#else
1614
 
  // Mac OS X and Cygwin don't define wcscasecmp.  Other unknown OSes
1615
 
  // may not define it either.
 
1578
  // Android, Mac OS X and Cygwin don't define wcscasecmp.
 
1579
  // Other unknown OSes may not define it either.
1616
1580
  wint_t left, right;
1617
1581
  do {
1618
1582
    left = towlower(*lhs++);
1622
1586
#endif  // OS selector
1623
1587
}
1624
1588
 
1625
 
// Compares this with another String.
1626
 
// Returns < 0 if this is less than rhs, 0 if this is equal to rhs, or > 0
1627
 
// if this is greater than rhs.
1628
 
int String::Compare(const String & rhs) const {
1629
 
  const char* const lhs_c_str = c_str();
1630
 
  const char* const rhs_c_str = rhs.c_str();
1631
 
 
1632
 
  if (lhs_c_str == NULL) {
1633
 
    return rhs_c_str == NULL ? 0 : -1;  // NULL < anything except NULL
1634
 
  } else if (rhs_c_str == NULL) {
1635
 
    return 1;
1636
 
  }
1637
 
 
1638
 
  const size_t shorter_str_len =
1639
 
      length() <= rhs.length() ? length() : rhs.length();
1640
 
  for (size_t i = 0; i != shorter_str_len; i++) {
1641
 
    if (lhs_c_str[i] < rhs_c_str[i]) {
1642
 
      return -1;
1643
 
    } else if (lhs_c_str[i] > rhs_c_str[i]) {
1644
 
      return 1;
1645
 
    }
1646
 
  }
1647
 
  return (length() < rhs.length()) ? -1 :
1648
 
      (length() > rhs.length()) ? 1 : 0;
1649
 
}
1650
 
 
1651
 
// Returns true iff this String ends with the given suffix.  *Any*
1652
 
// String is considered to end with a NULL or empty suffix.
1653
 
bool String::EndsWith(const char* suffix) const {
1654
 
  if (suffix == NULL || CStringEquals(suffix, "")) return true;
1655
 
 
1656
 
  if (c_str() == NULL) return false;
1657
 
 
1658
 
  const size_t this_len = strlen(c_str());
1659
 
  const size_t suffix_len = strlen(suffix);
1660
 
  return (this_len >= suffix_len) &&
1661
 
         CStringEquals(c_str() + this_len - suffix_len, suffix);
1662
 
}
1663
 
 
1664
 
// Returns true iff this String ends with the given suffix, ignoring case.
1665
 
// Any String is considered to end with a NULL or empty suffix.
1666
 
bool String::EndsWithCaseInsensitive(const char* suffix) const {
1667
 
  if (suffix == NULL || CStringEquals(suffix, "")) return true;
1668
 
 
1669
 
  if (c_str() == NULL) return false;
1670
 
 
1671
 
  const size_t this_len = strlen(c_str());
1672
 
  const size_t suffix_len = strlen(suffix);
1673
 
  return (this_len >= suffix_len) &&
1674
 
         CaseInsensitiveCStringEquals(c_str() + this_len - suffix_len, suffix);
1675
 
}
1676
 
 
1677
 
// Formats a list of arguments to a String, using the same format
 
1589
// Returns true iff str ends with the given suffix, ignoring case.
 
1590
// Any string is considered to end with an empty suffix.
 
1591
bool String::EndsWithCaseInsensitive(
 
1592
    const std::string& str, const std::string& suffix) {
 
1593
  const size_t str_len = str.length();
 
1594
  const size_t suffix_len = suffix.length();
 
1595
  return (str_len >= suffix_len) &&
 
1596
         CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len,
 
1597
                                      suffix.c_str());
 
1598
}
 
1599
 
 
1600
// Formats a list of arguments to an std::string, using the same format
1678
1601
// spec string as for printf.
1679
1602
//
1680
1603
// We do not use the StringPrintf class as it is not universally
1684
1607
// If 4096 characters are not enough to format the input, or if
1685
1608
// there's an error, "<formatting error or buffer exceeded>" is
1686
1609
// returned.
1687
 
String String::Format(const char * format, ...) {
 
1610
std::string String::Format(const char * format, ...) {
1688
1611
  va_list args;
1689
1612
  va_start(args, format);
1690
1613
 
1694
1617
  // MSVC 8 deprecates vsnprintf(), so we want to suppress warning
1695
1618
  // 4996 (deprecated function) there.
1696
1619
#ifdef _MSC_VER  // We are using MSVC.
1697
 
#pragma warning(push)          // Saves the current warning state.
1698
 
#pragma warning(disable:4996)  // Temporarily disables warning 4996.
 
1620
# pragma warning(push)          // Saves the current warning state.
 
1621
# pragma warning(disable:4996)  // Temporarily disables warning 4996.
 
1622
 
1699
1623
  const int size = vsnprintf(buffer, kBufferSize, format, args);
1700
 
#pragma warning(pop)           // Restores the warning state.
 
1624
 
 
1625
# pragma warning(pop)           // Restores the warning state.
1701
1626
#else  // We are not using MSVC.
1702
1627
  const int size = vsnprintf(buffer, kBufferSize, format, args);
1703
1628
#endif  // _MSC_VER
1709
1634
  // always returns a negative value.  For simplicity, we lump the two
1710
1635
  // error cases together.
1711
1636
  if (size < 0 || size >= kBufferSize) {
1712
 
    return String("<formatting error or buffer exceeded>");
 
1637
    return "<formatting error or buffer exceeded>";
1713
1638
  } else {
1714
 
    return String(buffer, size);
 
1639
    return std::string(buffer, size);
1715
1640
  }
1716
1641
}
1717
1642
 
1718
 
// Converts the buffer in a StrStream to a String, converting NUL
 
1643
// Converts the buffer in a stringstream to an std::string, converting NUL
1719
1644
// bytes to "\\0" along the way.
1720
 
String StrStreamToString(StrStream* ss) {
1721
 
#if GTEST_HAS_STD_STRING
 
1645
std::string StringStreamToString(::std::stringstream* ss) {
1722
1646
  const ::std::string& str = ss->str();
1723
1647
  const char* const start = str.c_str();
1724
1648
  const char* const end = start + str.length();
1725
 
#else
1726
 
  const char* const start = ss->str();
1727
 
  const char* const end = start + ss->pcount();
1728
 
#endif  // GTEST_HAS_STD_STRING
1729
1649
 
1730
 
  // We need to use a helper StrStream to do this transformation
1731
 
  // because String doesn't support push_back().
1732
 
  StrStream helper;
 
1650
  std::string result;
 
1651
  result.reserve(2 * (end - start));
1733
1652
  for (const char* ch = start; ch != end; ++ch) {
1734
1653
    if (*ch == '\0') {
1735
 
      helper << "\\0";  // Replaces NUL with "\\0";
 
1654
      result += "\\0";  // Replaces NUL with "\\0";
1736
1655
    } else {
1737
 
      helper.put(*ch);
 
1656
      result += *ch;
1738
1657
    }
1739
1658
  }
1740
1659
 
1741
 
#if GTEST_HAS_STD_STRING
1742
 
  return String(helper.str().c_str());
1743
 
#else
1744
 
  const String str(helper.str(), helper.pcount());
1745
 
  helper.freeze(false);
1746
 
  ss->freeze(false);
1747
 
  return str;
1748
 
#endif  // GTEST_HAS_STD_STRING
 
1660
  return result;
1749
1661
}
1750
1662
 
1751
1663
// Appends the user-supplied message to the Google-Test-generated message.
1752
 
String AppendUserMessage(const String& gtest_msg,
1753
 
                         const Message& user_msg) {
 
1664
std::string AppendUserMessage(const std::string& gtest_msg,
 
1665
                              const Message& user_msg) {
1754
1666
  // Appends the user message if it's non-empty.
1755
 
  const String user_msg_string = user_msg.GetString();
 
1667
  const std::string user_msg_string = user_msg.GetString();
1756
1668
  if (user_msg_string.empty()) {
1757
1669
    return gtest_msg;
1758
1670
  }
1759
1671
 
1760
 
  Message msg;
1761
 
  msg << gtest_msg << "\n" << user_msg_string;
1762
 
 
1763
 
  return msg.GetString();
 
1672
  return gtest_msg + "\n" + user_msg_string;
1764
1673
}
1765
1674
 
1766
1675
}  // namespace internal
1769
1678
 
1770
1679
// Creates an empty TestResult.
1771
1680
TestResult::TestResult()
1772
 
    : test_part_results_(new internal::Vector<TestPartResult>),
1773
 
      test_properties_(new internal::Vector<TestProperty>),
1774
 
      death_test_count_(0),
 
1681
    : death_test_count_(0),
1775
1682
      elapsed_time_(0) {
1776
1683
}
1777
1684
 
1783
1690
// range from 0 to total_part_count() - 1. If i is not in that range,
1784
1691
// aborts the program.
1785
1692
const TestPartResult& TestResult::GetTestPartResult(int i) const {
1786
 
  return test_part_results_->GetElement(i);
 
1693
  if (i < 0 || i >= total_part_count())
 
1694
    internal::posix::Abort();
 
1695
  return test_part_results_.at(i);
1787
1696
}
1788
1697
 
1789
1698
// Returns the i-th test property. i can range from 0 to
1790
1699
// test_property_count() - 1. If i is not in that range, aborts the
1791
1700
// program.
1792
1701
const TestProperty& TestResult::GetTestProperty(int i) const {
1793
 
  return test_properties_->GetElement(i);
 
1702
  if (i < 0 || i >= test_property_count())
 
1703
    internal::posix::Abort();
 
1704
  return test_properties_.at(i);
1794
1705
}
1795
1706
 
1796
1707
// Clears the test part results.
1797
1708
void TestResult::ClearTestPartResults() {
1798
 
  test_part_results_->Clear();
 
1709
  test_part_results_.clear();
1799
1710
}
1800
1711
 
1801
1712
// Adds a test part result to the list.
1802
1713
void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
1803
 
  test_part_results_->PushBack(test_part_result);
 
1714
  test_part_results_.push_back(test_part_result);
1804
1715
}
1805
1716
 
1806
1717
// Adds a test property to the list. If a property with the same key as the
1811
1722
    return;
1812
1723
  }
1813
1724
  internal::MutexLock lock(&test_properites_mutex_);
1814
 
  TestProperty* const property_with_matching_key =
1815
 
      test_properties_->FindIf(
1816
 
          internal::TestPropertyKeyIs(test_property.key()));
1817
 
  if (property_with_matching_key == NULL) {
1818
 
    test_properties_->PushBack(test_property);
 
1725
  const std::vector<TestProperty>::iterator property_with_matching_key =
 
1726
      std::find_if(test_properties_.begin(), test_properties_.end(),
 
1727
                   internal::TestPropertyKeyIs(test_property.key()));
 
1728
  if (property_with_matching_key == test_properties_.end()) {
 
1729
    test_properties_.push_back(test_property);
1819
1730
    return;
1820
1731
  }
1821
1732
  property_with_matching_key->SetValue(test_property.value());
1824
1735
// Adds a failure if the key is a reserved attribute of Google Test
1825
1736
// testcase tags.  Returns true if the property is valid.
1826
1737
bool TestResult::ValidateTestProperty(const TestProperty& test_property) {
1827
 
  internal::String key(test_property.key());
 
1738
  const std::string& key = test_property.key();
1828
1739
  if (key == "name" || key == "status" || key == "time" || key == "classname") {
1829
1740
    ADD_FAILURE()
1830
1741
        << "Reserved key used in RecordProperty(): "
1838
1749
 
1839
1750
// Clears the object.
1840
1751
void TestResult::Clear() {
1841
 
  test_part_results_->Clear();
1842
 
  test_properties_->Clear();
 
1752
  test_part_results_.clear();
 
1753
  test_properties_.clear();
1843
1754
  death_test_count_ = 0;
1844
1755
  elapsed_time_ = 0;
1845
1756
}
1860
1771
 
1861
1772
// Returns true iff the test fatally failed.
1862
1773
bool TestResult::HasFatalFailure() const {
1863
 
  return test_part_results_->CountIf(TestPartFatallyFailed) > 0;
 
1774
  return CountIf(test_part_results_, TestPartFatallyFailed) > 0;
1864
1775
}
1865
1776
 
1866
1777
// Returns true iff the test part non-fatally failed.
1870
1781
 
1871
1782
// Returns true iff the test has a non-fatal failure.
1872
1783
bool TestResult::HasNonfatalFailure() const {
1873
 
  return test_part_results_->CountIf(TestPartNonfatallyFailed) > 0;
 
1784
  return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0;
1874
1785
}
1875
1786
 
1876
1787
// Gets the number of all test parts.  This is the sum of the number
1877
1788
// of successful test parts and the number of failed test parts.
1878
1789
int TestResult::total_part_count() const {
1879
 
  return test_part_results_->size();
 
1790
  return static_cast<int>(test_part_results_.size());
1880
1791
}
1881
1792
 
1882
1793
// Returns the number of the test properties.
1883
1794
int TestResult::test_property_count() const {
1884
 
  return test_properties_->size();
 
1795
  return static_cast<int>(test_properties_.size());
1885
1796
}
1886
1797
 
1887
1798
// class Test
1925
1836
namespace internal {
1926
1837
 
1927
1838
void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
1928
 
                                    const String& message) {
 
1839
                                    const std::string& message) {
1929
1840
  // This function is a friend of UnitTest and as such has access to
1930
1841
  // AddTestPartResult.
1931
1842
  UnitTest::GetInstance()->AddTestPartResult(
1933
1844
      NULL,  // No info about the source file where the exception occurred.
1934
1845
      -1,    // We have no info on which line caused the exception.
1935
1846
      message,
1936
 
      String());  // No stack trace, either.
 
1847
      "");   // No stack trace, either.
1937
1848
}
1938
1849
 
1939
1850
}  // namespace internal
1940
1851
 
1941
 
#if GTEST_OS_WINDOWS
1942
 
// We are on Windows.
1943
 
 
1944
 
// Adds an "exception thrown" fatal failure to the current test.
1945
 
static void AddExceptionThrownFailure(DWORD exception_code,
1946
 
                                      const char* location) {
1947
 
  Message message;
1948
 
  message << "Exception thrown with code 0x" << std::setbase(16) <<
1949
 
    exception_code << std::setbase(10) << " in " << location << ".";
1950
 
 
1951
 
  internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
1952
 
                                           message.GetString());
1953
 
}
1954
 
 
1955
 
#endif  // GTEST_OS_WINDOWS
1956
 
 
1957
1852
// Google Test requires all tests in the same test case to use the same test
1958
1853
// fixture class.  This function checks if the current test has the
1959
1854
// same fixture class as the first test in the current test case.  If
1964
1859
  const TestCase* const test_case = impl->current_test_case();
1965
1860
 
1966
1861
  // Info about the first test in the current test case.
1967
 
  const internal::TestInfoImpl* const first_test_info =
1968
 
      test_case->test_info_list().GetElement(0)->impl();
1969
 
  const internal::TypeId first_fixture_id = first_test_info->fixture_class_id();
 
1862
  const TestInfo* const first_test_info = test_case->test_info_list()[0];
 
1863
  const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_;
1970
1864
  const char* const first_test_name = first_test_info->name();
1971
1865
 
1972
1866
  // Info about the current test.
1973
 
  const internal::TestInfoImpl* const this_test_info =
1974
 
      impl->current_test_info()->impl();
1975
 
  const internal::TypeId this_fixture_id = this_test_info->fixture_class_id();
 
1867
  const TestInfo* const this_test_info = impl->current_test_info();
 
1868
  const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_;
1976
1869
  const char* const this_test_name = this_test_info->name();
1977
1870
 
1978
1871
  if (this_fixture_id != first_fixture_id) {
2022
1915
  return true;
2023
1916
}
2024
1917
 
 
1918
#if GTEST_HAS_SEH
 
1919
 
 
1920
// Adds an "exception thrown" fatal failure to the current test.  This
 
1921
// function returns its result via an output parameter pointer because VC++
 
1922
// prohibits creation of objects with destructors on stack in functions
 
1923
// using __try (see error C2712).
 
1924
static std::string* FormatSehExceptionMessage(DWORD exception_code,
 
1925
                                              const char* location) {
 
1926
  Message message;
 
1927
  message << "SEH exception with code 0x" << std::setbase(16) <<
 
1928
    exception_code << std::setbase(10) << " thrown in " << location << ".";
 
1929
 
 
1930
  return new std::string(message.GetString());
 
1931
}
 
1932
 
 
1933
#endif  // GTEST_HAS_SEH
 
1934
 
 
1935
#if GTEST_HAS_EXCEPTIONS
 
1936
 
 
1937
// Adds an "exception thrown" fatal failure to the current test.
 
1938
static std::string FormatCxxExceptionMessage(const char* description,
 
1939
                                             const char* location) {
 
1940
  Message message;
 
1941
  if (description != NULL) {
 
1942
    message << "C++ exception with description \"" << description << "\"";
 
1943
  } else {
 
1944
    message << "Unknown C++ exception";
 
1945
  }
 
1946
  message << " thrown in " << location << ".";
 
1947
 
 
1948
  return message.GetString();
 
1949
}
 
1950
 
 
1951
static std::string PrintTestPartResultToString(
 
1952
    const TestPartResult& test_part_result);
 
1953
 
 
1954
// A failed Google Test assertion will throw an exception of this type when
 
1955
// GTEST_FLAG(throw_on_failure) is true (if exceptions are enabled).  We
 
1956
// derive it from std::runtime_error, which is for errors presumably
 
1957
// detectable only at run time.  Since std::runtime_error inherits from
 
1958
// std::exception, many testing frameworks know how to extract and print the
 
1959
// message inside it.
 
1960
class GoogleTestFailureException : public ::std::runtime_error {
 
1961
 public:
 
1962
  explicit GoogleTestFailureException(const TestPartResult& failure)
 
1963
      : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
 
1964
};
 
1965
#endif  // GTEST_HAS_EXCEPTIONS
 
1966
 
 
1967
namespace internal {
 
1968
// We put these helper functions in the internal namespace as IBM's xlC
 
1969
// compiler rejects the code if they were declared static.
 
1970
 
 
1971
// Runs the given method and handles SEH exceptions it throws, when
 
1972
// SEH is supported; returns the 0-value for type Result in case of an
 
1973
// SEH exception.  (Microsoft compilers cannot handle SEH and C++
 
1974
// exceptions in the same function.  Therefore, we provide a separate
 
1975
// wrapper function for handling SEH exceptions.)
 
1976
template <class T, typename Result>
 
1977
Result HandleSehExceptionsInMethodIfSupported(
 
1978
    T* object, Result (T::*method)(), const char* location) {
 
1979
#if GTEST_HAS_SEH
 
1980
  __try {
 
1981
    return (object->*method)();
 
1982
  } __except (internal::UnitTestOptions::GTestShouldProcessSEH(  // NOLINT
 
1983
      GetExceptionCode())) {
 
1984
    // We create the exception message on the heap because VC++ prohibits
 
1985
    // creation of objects with destructors on stack in functions using __try
 
1986
    // (see error C2712).
 
1987
    std::string* exception_message = FormatSehExceptionMessage(
 
1988
        GetExceptionCode(), location);
 
1989
    internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
 
1990
                                             *exception_message);
 
1991
    delete exception_message;
 
1992
    return static_cast<Result>(0);
 
1993
  }
 
1994
#else
 
1995
  (void)location;
 
1996
  return (object->*method)();
 
1997
#endif  // GTEST_HAS_SEH
 
1998
}
 
1999
 
 
2000
// Runs the given method and catches and reports C++ and/or SEH-style
 
2001
// exceptions, if they are supported; returns the 0-value for type
 
2002
// Result in case of an SEH exception.
 
2003
template <class T, typename Result>
 
2004
Result HandleExceptionsInMethodIfSupported(
 
2005
    T* object, Result (T::*method)(), const char* location) {
 
2006
  // NOTE: The user code can affect the way in which Google Test handles
 
2007
  // exceptions by setting GTEST_FLAG(catch_exceptions), but only before
 
2008
  // RUN_ALL_TESTS() starts. It is technically possible to check the flag
 
2009
  // after the exception is caught and either report or re-throw the
 
2010
  // exception based on the flag's value:
 
2011
  //
 
2012
  // try {
 
2013
  //   // Perform the test method.
 
2014
  // } catch (...) {
 
2015
  //   if (GTEST_FLAG(catch_exceptions))
 
2016
  //     // Report the exception as failure.
 
2017
  //   else
 
2018
  //     throw;  // Re-throws the original exception.
 
2019
  // }
 
2020
  //
 
2021
  // However, the purpose of this flag is to allow the program to drop into
 
2022
  // the debugger when the exception is thrown. On most platforms, once the
 
2023
  // control enters the catch block, the exception origin information is
 
2024
  // lost and the debugger will stop the program at the point of the
 
2025
  // re-throw in this function -- instead of at the point of the original
 
2026
  // throw statement in the code under test.  For this reason, we perform
 
2027
  // the check early, sacrificing the ability to affect Google Test's
 
2028
  // exception handling in the method where the exception is thrown.
 
2029
  if (internal::GetUnitTestImpl()->catch_exceptions()) {
 
2030
#if GTEST_HAS_EXCEPTIONS
 
2031
    try {
 
2032
      return HandleSehExceptionsInMethodIfSupported(object, method, location);
 
2033
    } catch (const GoogleTestFailureException&) {  // NOLINT
 
2034
      // This exception doesn't originate in code under test. It makes no
 
2035
      // sense to report it as a test failure.
 
2036
      throw;
 
2037
    } catch (const std::exception& e) {  // NOLINT
 
2038
      internal::ReportFailureInUnknownLocation(
 
2039
          TestPartResult::kFatalFailure,
 
2040
          FormatCxxExceptionMessage(e.what(), location));
 
2041
    } catch (...) {  // NOLINT
 
2042
      internal::ReportFailureInUnknownLocation(
 
2043
          TestPartResult::kFatalFailure,
 
2044
          FormatCxxExceptionMessage(NULL, location));
 
2045
    }
 
2046
    return static_cast<Result>(0);
 
2047
#else
 
2048
    return HandleSehExceptionsInMethodIfSupported(object, method, location);
 
2049
#endif  // GTEST_HAS_EXCEPTIONS
 
2050
  } else {
 
2051
    return (object->*method)();
 
2052
  }
 
2053
}
 
2054
 
 
2055
}  // namespace internal
 
2056
 
2025
2057
// Runs the test and updates the test result.
2026
2058
void Test::Run() {
2027
2059
  if (!HasSameFixtureClass()) return;
2028
2060
 
2029
2061
  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2030
 
#if GTEST_HAS_SEH
2031
 
  // Catch SEH-style exceptions.
2032
 
  impl->os_stack_trace_getter()->UponLeavingGTest();
2033
 
  __try {
2034
 
    SetUp();
2035
 
  } __except(internal::UnitTestOptions::GTestShouldProcessSEH(
2036
 
      GetExceptionCode())) {
2037
 
    AddExceptionThrownFailure(GetExceptionCode(), "SetUp()");
2038
 
  }
2039
 
 
2040
 
  // We will run the test only if SetUp() had no fatal failure.
2041
 
  if (!HasFatalFailure()) {
2042
 
    impl->os_stack_trace_getter()->UponLeavingGTest();
2043
 
    __try {
2044
 
      TestBody();
2045
 
    } __except(internal::UnitTestOptions::GTestShouldProcessSEH(
2046
 
        GetExceptionCode())) {
2047
 
      AddExceptionThrownFailure(GetExceptionCode(), "the test body");
2048
 
    }
2049
 
  }
2050
 
 
2051
 
  // However, we want to clean up as much as possible.  Hence we will
2052
 
  // always call TearDown(), even if SetUp() or the test body has
2053
 
  // failed.
2054
 
  impl->os_stack_trace_getter()->UponLeavingGTest();
2055
 
  __try {
2056
 
    TearDown();
2057
 
  } __except(internal::UnitTestOptions::GTestShouldProcessSEH(
2058
 
      GetExceptionCode())) {
2059
 
    AddExceptionThrownFailure(GetExceptionCode(), "TearDown()");
2060
 
  }
2061
 
 
2062
 
#else  // We are on a compiler or platform that doesn't support SEH.
2063
 
  impl->os_stack_trace_getter()->UponLeavingGTest();
2064
 
  SetUp();
2065
 
 
 
2062
  impl->os_stack_trace_getter()->UponLeavingGTest();
 
2063
  internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()");
2066
2064
  // We will run the test only if SetUp() was successful.
2067
2065
  if (!HasFatalFailure()) {
2068
2066
    impl->os_stack_trace_getter()->UponLeavingGTest();
2069
 
    TestBody();
 
2067
    internal::HandleExceptionsInMethodIfSupported(
 
2068
        this, &Test::TestBody, "the test body");
2070
2069
  }
2071
2070
 
2072
2071
  // However, we want to clean up as much as possible.  Hence we will
2073
2072
  // always call TearDown(), even if SetUp() or the test body has
2074
2073
  // failed.
2075
2074
  impl->os_stack_trace_getter()->UponLeavingGTest();
2076
 
  TearDown();
2077
 
#endif  // GTEST_HAS_SEH
 
2075
  internal::HandleExceptionsInMethodIfSupported(
 
2076
      this, &Test::TearDown, "TearDown()");
2078
2077
}
2079
2078
 
2080
 
 
2081
2079
// Returns true iff the current test has a fatal failure.
2082
2080
bool Test::HasFatalFailure() {
2083
2081
  return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
2092
2090
// class TestInfo
2093
2091
 
2094
2092
// Constructs a TestInfo object. It assumes ownership of the test factory
2095
 
// object via impl_.
2096
 
TestInfo::TestInfo(const char* test_case_name,
2097
 
                   const char* name,
2098
 
                   const char* test_case_comment,
2099
 
                   const char* comment,
 
2093
// object.
 
2094
// TODO(vladl@google.com): Make a_test_case_name and a_name const string&'s
 
2095
// to signify they cannot be NULLs.
 
2096
TestInfo::TestInfo(const char* a_test_case_name,
 
2097
                   const char* a_name,
 
2098
                   const char* a_type_param,
 
2099
                   const char* a_value_param,
2100
2100
                   internal::TypeId fixture_class_id,
2101
 
                   internal::TestFactoryBase* factory) {
2102
 
  impl_ = new internal::TestInfoImpl(this, test_case_name, name,
2103
 
                                     test_case_comment, comment,
2104
 
                                     fixture_class_id, factory);
2105
 
}
 
2101
                   internal::TestFactoryBase* factory)
 
2102
    : test_case_name_(a_test_case_name),
 
2103
      name_(a_name),
 
2104
      type_param_(a_type_param ? new std::string(a_type_param) : NULL),
 
2105
      value_param_(a_value_param ? new std::string(a_value_param) : NULL),
 
2106
      fixture_class_id_(fixture_class_id),
 
2107
      should_run_(false),
 
2108
      is_disabled_(false),
 
2109
      matches_filter_(false),
 
2110
      factory_(factory),
 
2111
      result_() {}
2106
2112
 
2107
2113
// Destructs a TestInfo object.
2108
 
TestInfo::~TestInfo() {
2109
 
  delete impl_;
2110
 
}
 
2114
TestInfo::~TestInfo() { delete factory_; }
2111
2115
 
2112
2116
namespace internal {
2113
2117
 
2118
2122
//
2119
2123
//   test_case_name:   name of the test case
2120
2124
//   name:             name of the test
2121
 
//   test_case_comment: a comment on the test case that will be included in
2122
 
//                      the test output
2123
 
//   comment:          a comment on the test that will be included in the
2124
 
//                     test output
 
2125
//   type_param:       the name of the test's type parameter, or NULL if
 
2126
//                     this is not a typed or a type-parameterized test.
 
2127
//   value_param:      text representation of the test's value parameter,
 
2128
//                     or NULL if this is not a value-parameterized test.
2125
2129
//   fixture_class_id: ID of the test fixture class
2126
2130
//   set_up_tc:        pointer to the function that sets up the test case
2127
2131
//   tear_down_tc:     pointer to the function that tears down the test case
2130
2134
//                     ownership of the factory object.
2131
2135
TestInfo* MakeAndRegisterTestInfo(
2132
2136
    const char* test_case_name, const char* name,
2133
 
    const char* test_case_comment, const char* comment,
 
2137
    const char* type_param,
 
2138
    const char* value_param,
2134
2139
    TypeId fixture_class_id,
2135
2140
    SetUpTestCaseFunc set_up_tc,
2136
2141
    TearDownTestCaseFunc tear_down_tc,
2137
2142
    TestFactoryBase* factory) {
2138
2143
  TestInfo* const test_info =
2139
 
      new TestInfo(test_case_name, name, test_case_comment, comment,
 
2144
      new TestInfo(test_case_name, name, type_param, value_param,
2140
2145
                   fixture_class_id, factory);
2141
2146
  GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
2142
2147
  return test_info;
2163
2168
 
2164
2169
}  // namespace internal
2165
2170
 
2166
 
// Returns the test case name.
2167
 
const char* TestInfo::test_case_name() const {
2168
 
  return impl_->test_case_name();
2169
 
}
2170
 
 
2171
 
// Returns the test name.
2172
 
const char* TestInfo::name() const {
2173
 
  return impl_->name();
2174
 
}
2175
 
 
2176
 
// Returns the test case comment.
2177
 
const char* TestInfo::test_case_comment() const {
2178
 
  return impl_->test_case_comment();
2179
 
}
2180
 
 
2181
 
// Returns the test comment.
2182
 
const char* TestInfo::comment() const {
2183
 
  return impl_->comment();
2184
 
}
2185
 
 
2186
 
// Returns true if this test should run.
2187
 
bool TestInfo::should_run() const { return impl_->should_run(); }
2188
 
 
2189
 
// Returns true if this test matches the user-specified filter.
2190
 
bool TestInfo::matches_filter() const { return impl_->matches_filter(); }
2191
 
 
2192
 
// Returns the result of the test.
2193
 
const TestResult* TestInfo::result() const { return impl_->result(); }
2194
 
 
2195
 
// Increments the number of death tests encountered in this test so
2196
 
// far.
2197
 
int TestInfo::increment_death_test_count() {
2198
 
  return impl_->result()->increment_death_test_count();
2199
 
}
2200
 
 
2201
2171
namespace {
2202
2172
 
2203
2173
// A predicate that checks the test name of a TestInfo against a known
2218
2188
 
2219
2189
  // Returns true iff the test name of test_info matches name_.
2220
2190
  bool operator()(const TestInfo * test_info) const {
2221
 
    return test_info && internal::String(test_info->name()).Compare(name_) == 0;
 
2191
    return test_info && test_info->name() == name_;
2222
2192
  }
2223
2193
 
2224
2194
 private:
2225
 
  internal::String name_;
 
2195
  std::string name_;
2226
2196
};
2227
2197
 
2228
2198
}  // namespace
2241
2211
#endif
2242
2212
}
2243
2213
 
 
2214
}  // namespace internal
 
2215
 
2244
2216
// Creates the test object, runs it, records its result, and then
2245
2217
// deletes it.
2246
 
void TestInfoImpl::Run() {
 
2218
void TestInfo::Run() {
2247
2219
  if (!should_run_) return;
2248
2220
 
2249
2221
  // Tells UnitTest where to store test result.
2250
 
  UnitTestImpl* const impl = internal::GetUnitTestImpl();
2251
 
  impl->set_current_test_info(parent_);
 
2222
  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
 
2223
  impl->set_current_test_info(this);
2252
2224
 
2253
2225
  TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
2254
2226
 
2255
2227
  // Notifies the unit test event listeners that a test is about to start.
2256
 
  repeater->OnTestStart(*parent_);
 
2228
  repeater->OnTestStart(*this);
2257
2229
 
2258
 
  const TimeInMillis start = GetTimeInMillis();
 
2230
  const TimeInMillis start = internal::GetTimeInMillis();
2259
2231
 
2260
2232
  impl->os_stack_trace_getter()->UponLeavingGTest();
2261
 
#if GTEST_HAS_SEH
2262
 
  // Catch SEH-style exceptions.
2263
 
  Test* test = NULL;
2264
 
 
2265
 
  __try {
2266
 
    // Creates the test object.
2267
 
    test = factory_->CreateTest();
2268
 
  } __except(internal::UnitTestOptions::GTestShouldProcessSEH(
2269
 
      GetExceptionCode())) {
2270
 
    AddExceptionThrownFailure(GetExceptionCode(),
2271
 
                              "the test fixture's constructor");
2272
 
    return;
2273
 
  }
2274
 
#else  // We are on a compiler or platform that doesn't support SEH.
2275
 
 
2276
 
  // TODO(wan): If test->Run() throws, test won't be deleted.  This is
2277
 
  // not a problem now as we don't use exceptions.  If we were to
2278
 
  // enable exceptions, we should revise the following to be
2279
 
  // exception-safe.
2280
2233
 
2281
2234
  // Creates the test object.
2282
 
  Test* test = factory_->CreateTest();
2283
 
#endif  // GTEST_HAS_SEH
 
2235
  Test* const test = internal::HandleExceptionsInMethodIfSupported(
 
2236
      factory_, &internal::TestFactoryBase::CreateTest,
 
2237
      "the test fixture's constructor");
2284
2238
 
2285
 
  // Runs the test only if the constructor of the test fixture didn't
2286
 
  // generate a fatal failure.
2287
 
  if (!Test::HasFatalFailure()) {
 
2239
  // Runs the test only if the test object was created and its
 
2240
  // constructor didn't generate a fatal failure.
 
2241
  if ((test != NULL) && !Test::HasFatalFailure()) {
 
2242
    // This doesn't throw as all user code that can throw are wrapped into
 
2243
    // exception handling code.
2288
2244
    test->Run();
2289
2245
  }
2290
2246
 
2291
2247
  // Deletes the test object.
2292
2248
  impl->os_stack_trace_getter()->UponLeavingGTest();
2293
 
  delete test;
2294
 
  test = NULL;
 
2249
  internal::HandleExceptionsInMethodIfSupported(
 
2250
      test, &Test::DeleteSelf_, "the test fixture's destructor");
2295
2251
 
2296
 
  result_.set_elapsed_time(GetTimeInMillis() - start);
 
2252
  result_.set_elapsed_time(internal::GetTimeInMillis() - start);
2297
2253
 
2298
2254
  // Notifies the unit test event listener that a test has just finished.
2299
 
  repeater->OnTestEnd(*parent_);
 
2255
  repeater->OnTestEnd(*this);
2300
2256
 
2301
2257
  // Tells UnitTest to stop associating assertion results to this
2302
2258
  // test.
2303
2259
  impl->set_current_test_info(NULL);
2304
2260
}
2305
2261
 
2306
 
}  // namespace internal
2307
 
 
2308
2262
// class TestCase
2309
2263
 
2310
2264
// Gets the number of successful tests in this test case.
2311
2265
int TestCase::successful_test_count() const {
2312
 
  return test_info_list_->CountIf(TestPassed);
 
2266
  return CountIf(test_info_list_, TestPassed);
2313
2267
}
2314
2268
 
2315
2269
// Gets the number of failed tests in this test case.
2316
2270
int TestCase::failed_test_count() const {
2317
 
  return test_info_list_->CountIf(TestFailed);
 
2271
  return CountIf(test_info_list_, TestFailed);
2318
2272
}
2319
2273
 
2320
2274
int TestCase::disabled_test_count() const {
2321
 
  return test_info_list_->CountIf(TestDisabled);
 
2275
  return CountIf(test_info_list_, TestDisabled);
2322
2276
}
2323
2277
 
2324
2278
// Get the number of tests in this test case that should run.
2325
2279
int TestCase::test_to_run_count() const {
2326
 
  return test_info_list_->CountIf(ShouldRunTest);
 
2280
  return CountIf(test_info_list_, ShouldRunTest);
2327
2281
}
2328
2282
 
2329
2283
// Gets the number of all tests.
2330
2284
int TestCase::total_test_count() const {
2331
 
  return test_info_list_->size();
 
2285
  return static_cast<int>(test_info_list_.size());
2332
2286
}
2333
2287
 
2334
2288
// Creates a TestCase with the given name.
2336
2290
// Arguments:
2337
2291
//
2338
2292
//   name:         name of the test case
 
2293
//   a_type_param: the name of the test case's type parameter, or NULL if
 
2294
//                 this is not a typed or a type-parameterized test case.
2339
2295
//   set_up_tc:    pointer to the function that sets up the test case
2340
2296
//   tear_down_tc: pointer to the function that tears down the test case
2341
 
TestCase::TestCase(const char* name, const char* comment,
 
2297
TestCase::TestCase(const char* a_name, const char* a_type_param,
2342
2298
                   Test::SetUpTestCaseFunc set_up_tc,
2343
2299
                   Test::TearDownTestCaseFunc tear_down_tc)
2344
 
    : name_(name),
2345
 
      comment_(comment),
2346
 
      test_info_list_(new internal::Vector<TestInfo*>),
2347
 
      test_indices_(new internal::Vector<int>),
 
2300
    : name_(a_name),
 
2301
      type_param_(a_type_param ? new std::string(a_type_param) : NULL),
2348
2302
      set_up_tc_(set_up_tc),
2349
2303
      tear_down_tc_(tear_down_tc),
2350
2304
      should_run_(false),
2354
2308
// Destructor of TestCase.
2355
2309
TestCase::~TestCase() {
2356
2310
  // Deletes every Test in the collection.
2357
 
  test_info_list_->ForEach(internal::Delete<TestInfo>);
 
2311
  ForEach(test_info_list_, internal::Delete<TestInfo>);
2358
2312
}
2359
2313
 
2360
2314
// Returns the i-th test among all the tests. i can range from 0 to
2361
2315
// total_test_count() - 1. If i is not in that range, returns NULL.
2362
2316
const TestInfo* TestCase::GetTestInfo(int i) const {
2363
 
  const int index = test_indices_->GetElementOr(i, -1);
2364
 
  return index < 0 ? NULL : test_info_list_->GetElement(index);
 
2317
  const int index = GetElementOr(test_indices_, i, -1);
 
2318
  return index < 0 ? NULL : test_info_list_[index];
2365
2319
}
2366
2320
 
2367
2321
// Returns the i-th test among all the tests. i can range from 0 to
2368
2322
// total_test_count() - 1. If i is not in that range, returns NULL.
2369
2323
TestInfo* TestCase::GetMutableTestInfo(int i) {
2370
 
  const int index = test_indices_->GetElementOr(i, -1);
2371
 
  return index < 0 ? NULL : test_info_list_->GetElement(index);
 
2324
  const int index = GetElementOr(test_indices_, i, -1);
 
2325
  return index < 0 ? NULL : test_info_list_[index];
2372
2326
}
2373
2327
 
2374
2328
// Adds a test to this test case.  Will delete the test upon
2375
2329
// destruction of the TestCase object.
2376
2330
void TestCase::AddTestInfo(TestInfo * test_info) {
2377
 
  test_info_list_->PushBack(test_info);
2378
 
  test_indices_->PushBack(test_indices_->size());
 
2331
  test_info_list_.push_back(test_info);
 
2332
  test_indices_.push_back(static_cast<int>(test_indices_.size()));
2379
2333
}
2380
2334
 
2381
2335
// Runs every test in this TestCase.
2389
2343
 
2390
2344
  repeater->OnTestCaseStart(*this);
2391
2345
  impl->os_stack_trace_getter()->UponLeavingGTest();
2392
 
  set_up_tc_();
 
2346
  internal::HandleExceptionsInMethodIfSupported(
 
2347
      this, &TestCase::RunSetUpTestCase, "SetUpTestCase()");
2393
2348
 
2394
2349
  const internal::TimeInMillis start = internal::GetTimeInMillis();
2395
2350
  for (int i = 0; i < total_test_count(); i++) {
2396
 
    GetMutableTestInfo(i)->impl()->Run();
 
2351
    GetMutableTestInfo(i)->Run();
2397
2352
  }
2398
2353
  elapsed_time_ = internal::GetTimeInMillis() - start;
2399
2354
 
2400
2355
  impl->os_stack_trace_getter()->UponLeavingGTest();
2401
 
  tear_down_tc_();
 
2356
  internal::HandleExceptionsInMethodIfSupported(
 
2357
      this, &TestCase::RunTearDownTestCase, "TearDownTestCase()");
 
2358
 
2402
2359
  repeater->OnTestCaseEnd(*this);
2403
2360
  impl->set_current_test_case(NULL);
2404
2361
}
2405
2362
 
2406
2363
// Clears the results of all tests in this test case.
2407
2364
void TestCase::ClearResult() {
2408
 
  test_info_list_->ForEach(internal::TestInfoImpl::ClearTestResult);
2409
 
}
2410
 
 
2411
 
// Returns true iff test passed.
2412
 
bool TestCase::TestPassed(const TestInfo * test_info) {
2413
 
  const internal::TestInfoImpl* const impl = test_info->impl();
2414
 
  return impl->should_run() && impl->result()->Passed();
2415
 
}
2416
 
 
2417
 
// Returns true iff test failed.
2418
 
bool TestCase::TestFailed(const TestInfo * test_info) {
2419
 
  const internal::TestInfoImpl* const impl = test_info->impl();
2420
 
  return impl->should_run() && impl->result()->Failed();
2421
 
}
2422
 
 
2423
 
// Returns true iff test is disabled.
2424
 
bool TestCase::TestDisabled(const TestInfo * test_info) {
2425
 
  return test_info->impl()->is_disabled();
2426
 
}
2427
 
 
2428
 
// Returns true if the given test should run.
2429
 
bool TestCase::ShouldRunTest(const TestInfo *test_info) {
2430
 
  return test_info->impl()->should_run();
 
2365
  ForEach(test_info_list_, TestInfo::ClearTestResult);
2431
2366
}
2432
2367
 
2433
2368
// Shuffles the tests in this test case.
2434
2369
void TestCase::ShuffleTests(internal::Random* random) {
2435
 
  test_indices_->Shuffle(random);
 
2370
  Shuffle(random, &test_indices_);
2436
2371
}
2437
2372
 
2438
2373
// Restores the test order to before the first shuffle.
2439
2374
void TestCase::UnshuffleTests() {
2440
 
  for (int i = 0; i < test_indices_->size(); i++) {
2441
 
    test_indices_->GetMutableElement(i) = i;
 
2375
  for (size_t i = 0; i < test_indices_.size(); i++) {
 
2376
    test_indices_[i] = static_cast<int>(i);
2442
2377
  }
2443
2378
}
2444
2379
 
2447
2382
//
2448
2383
// FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
2449
2384
// FormatCountableNoun(5, "book", "books") returns "5 books".
2450
 
static internal::String FormatCountableNoun(int count,
2451
 
                                            const char * singular_form,
2452
 
                                            const char * plural_form) {
 
2385
static std::string FormatCountableNoun(int count,
 
2386
                                       const char * singular_form,
 
2387
                                       const char * plural_form) {
2453
2388
  return internal::String::Format("%d %s", count,
2454
2389
                                  count == 1 ? singular_form : plural_form);
2455
2390
}
2456
2391
 
2457
2392
// Formats the count of tests.
2458
 
static internal::String FormatTestCount(int test_count) {
 
2393
static std::string FormatTestCount(int test_count) {
2459
2394
  return FormatCountableNoun(test_count, "test", "tests");
2460
2395
}
2461
2396
 
2462
2397
// Formats the count of test cases.
2463
 
static internal::String FormatTestCaseCount(int test_case_count) {
 
2398
static std::string FormatTestCaseCount(int test_case_count) {
2464
2399
  return FormatCountableNoun(test_case_count, "test case", "test cases");
2465
2400
}
2466
2401
 
2480
2415
#else
2481
2416
      return "Failure\n";
2482
2417
#endif
 
2418
    default:
 
2419
      return "Unknown result type";
2483
2420
  }
2484
 
 
2485
 
  return "Unknown result type";
2486
2421
}
2487
2422
 
2488
 
// Prints a TestPartResult to a String.
2489
 
static internal::String PrintTestPartResultToString(
 
2423
// Prints a TestPartResult to an std::string.
 
2424
static std::string PrintTestPartResultToString(
2490
2425
    const TestPartResult& test_part_result) {
2491
2426
  return (Message()
2492
2427
          << internal::FormatFileLocation(test_part_result.file_name(),
2497
2432
 
2498
2433
// Prints a TestPartResult.
2499
2434
static void PrintTestPartResult(const TestPartResult& test_part_result) {
2500
 
  const internal::String& result =
 
2435
  const std::string& result =
2501
2436
      PrintTestPartResultToString(test_part_result);
2502
2437
  printf("%s\n", result.c_str());
2503
2438
  fflush(stdout);
2568
2503
        String::CStringEquals(term, "xterm") ||
2569
2504
        String::CStringEquals(term, "xterm-color") ||
2570
2505
        String::CStringEquals(term, "xterm-256color") ||
 
2506
        String::CStringEquals(term, "screen") ||
2571
2507
        String::CStringEquals(term, "linux") ||
2572
2508
        String::CStringEquals(term, "cygwin");
2573
2509
    return stdout_is_tty && term_supports_color;
2591
2527
  va_list args;
2592
2528
  va_start(args, fmt);
2593
2529
 
2594
 
#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
 
2530
#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS || GTEST_OS_IOS
2595
2531
  const bool use_color = false;
2596
2532
#else
2597
2533
  static const bool in_color_mode =
2614
2550
  GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
2615
2551
  const WORD old_color_attrs = buffer_info.wAttributes;
2616
2552
 
 
2553
  // We need to flush the stream buffers into the console before each
 
2554
  // SetConsoleTextAttribute call lest it affect the text that is already
 
2555
  // printed but has not yet reached the console.
 
2556
  fflush(stdout);
2617
2557
  SetConsoleTextAttribute(stdout_handle,
2618
2558
                          GetColorAttribute(color) | FOREGROUND_INTENSITY);
2619
2559
  vprintf(fmt, args);
2620
2560
 
 
2561
  fflush(stdout);
2621
2562
  // Restores the text color.
2622
2563
  SetConsoleTextAttribute(stdout_handle, old_color_attrs);
2623
2564
#else
2628
2569
  va_end(args);
2629
2570
}
2630
2571
 
 
2572
void PrintFullTestCommentIfPresent(const TestInfo& test_info) {
 
2573
  const char* const type_param = test_info.type_param();
 
2574
  const char* const value_param = test_info.value_param();
 
2575
 
 
2576
  if (type_param != NULL || value_param != NULL) {
 
2577
    printf(", where ");
 
2578
    if (type_param != NULL) {
 
2579
      printf("TypeParam = %s", type_param);
 
2580
      if (value_param != NULL)
 
2581
        printf(" and ");
 
2582
    }
 
2583
    if (value_param != NULL) {
 
2584
      printf("GetParam() = %s", value_param);
 
2585
    }
 
2586
  }
 
2587
}
 
2588
 
2631
2589
// This class implements the TestEventListener interface.
2632
2590
//
2633
2591
// Class PrettyUnitTestResultPrinter is copyable.
2655
2613
 
2656
2614
 private:
2657
2615
  static void PrintFailedTests(const UnitTest& unit_test);
2658
 
 
2659
 
  internal::String test_case_name_;
2660
2616
};
2661
2617
 
2662
2618
  // Fired before each iteration of tests starts.
2669
2625
 
2670
2626
  // Prints the filter if it's not *.  This reminds the user that some
2671
2627
  // tests may be skipped.
2672
 
  if (!internal::String::CStringEquals(filter, kUniversalFilter)) {
 
2628
  if (!String::CStringEquals(filter, kUniversalFilter)) {
2673
2629
    ColoredPrintf(COLOR_YELLOW,
2674
2630
                  "Note: %s filter = %s\n", GTEST_NAME_, filter);
2675
2631
  }
2676
2632
 
2677
2633
  if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
 
2634
    const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
2678
2635
    ColoredPrintf(COLOR_YELLOW,
2679
 
                  "Note: This is test shard %s of %s.\n",
2680
 
                  internal::posix::GetEnv(kTestShardIndex),
 
2636
                  "Note: This is test shard %d of %s.\n",
 
2637
                  static_cast<int>(shard_index) + 1,
2681
2638
                  internal::posix::GetEnv(kTestTotalShards));
2682
2639
  }
2683
2640
 
2702
2659
}
2703
2660
 
2704
2661
void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {
2705
 
  test_case_name_ = test_case.name();
2706
 
  const internal::String counts =
 
2662
  const std::string counts =
2707
2663
      FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
2708
2664
  ColoredPrintf(COLOR_GREEN, "[----------] ");
2709
 
  printf("%s from %s", counts.c_str(), test_case_name_.c_str());
2710
 
  if (test_case.comment()[0] == '\0') {
 
2665
  printf("%s from %s", counts.c_str(), test_case.name());
 
2666
  if (test_case.type_param() == NULL) {
2711
2667
    printf("\n");
2712
2668
  } else {
2713
 
    printf(", where %s\n", test_case.comment());
 
2669
    printf(", where TypeParam = %s\n", test_case.type_param());
2714
2670
  }
2715
2671
  fflush(stdout);
2716
2672
}
2717
2673
 
2718
2674
void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
2719
2675
  ColoredPrintf(COLOR_GREEN,  "[ RUN      ] ");
2720
 
  PrintTestName(test_case_name_.c_str(), test_info.name());
2721
 
  if (test_info.comment()[0] == '\0') {
2722
 
    printf("\n");
2723
 
  } else {
2724
 
    printf(", where %s\n", test_info.comment());
2725
 
  }
 
2676
  PrintTestName(test_info.test_case_name(), test_info.name());
 
2677
  printf("\n");
2726
2678
  fflush(stdout);
2727
2679
}
2728
2680
 
2744
2696
  } else {
2745
2697
    ColoredPrintf(COLOR_RED, "[  FAILED  ] ");
2746
2698
  }
2747
 
  PrintTestName(test_case_name_.c_str(), test_info.name());
 
2699
  PrintTestName(test_info.test_case_name(), test_info.name());
 
2700
  if (test_info.result()->Failed())
 
2701
    PrintFullTestCommentIfPresent(test_info);
 
2702
 
2748
2703
  if (GTEST_FLAG(print_time)) {
2749
2704
    printf(" (%s ms)\n", internal::StreamableToString(
2750
2705
           test_info.result()->elapsed_time()).c_str());
2757
2712
void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {
2758
2713
  if (!GTEST_FLAG(print_time)) return;
2759
2714
 
2760
 
  test_case_name_ = test_case.name();
2761
 
  const internal::String counts =
 
2715
  const std::string counts =
2762
2716
      FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
2763
2717
  ColoredPrintf(COLOR_GREEN, "[----------] ");
2764
2718
  printf("%s from %s (%s ms total)\n\n",
2765
 
         counts.c_str(), test_case_name_.c_str(),
 
2719
         counts.c_str(), test_case.name(),
2766
2720
         internal::StreamableToString(test_case.elapsed_time()).c_str());
2767
2721
  fflush(stdout);
2768
2722
}
2793
2747
      }
2794
2748
      ColoredPrintf(COLOR_RED, "[  FAILED  ] ");
2795
2749
      printf("%s.%s", test_case.name(), test_info.name());
2796
 
      if (test_case.comment()[0] != '\0' ||
2797
 
          test_info.comment()[0] != '\0') {
2798
 
        printf(", where %s", test_case.comment());
2799
 
        if (test_case.comment()[0] != '\0' &&
2800
 
            test_info.comment()[0] != '\0') {
2801
 
          printf(" and ");
2802
 
        }
2803
 
      }
2804
 
      printf("%s\n", test_info.comment());
 
2750
      PrintFullTestCommentIfPresent(test_info);
 
2751
      printf("\n");
2805
2752
    }
2806
2753
  }
2807
2754
}
2808
2755
 
2809
 
 void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
2810
 
                                                      int /*iteration*/) {
 
2756
void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
 
2757
                                                     int /*iteration*/) {
2811
2758
  ColoredPrintf(COLOR_GREEN,  "[==========] ");
2812
2759
  printf("%s from %s ran.",
2813
2760
         FormatTestCount(unit_test.test_to_run_count()).c_str(),
2880
2827
  // in death test child processes.
2881
2828
  bool forwarding_enabled_;
2882
2829
  // The list of listeners that receive events.
2883
 
  Vector<TestEventListener*> listeners_;
 
2830
  std::vector<TestEventListener*> listeners_;
2884
2831
 
2885
2832
  GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater);
2886
2833
};
2887
2834
 
2888
2835
TestEventRepeater::~TestEventRepeater() {
2889
 
  for (int i = 0; i < listeners_.size(); i++) {
2890
 
    delete listeners_.GetElement(i);
2891
 
  }
 
2836
  ForEach(listeners_, Delete<TestEventListener>);
2892
2837
}
2893
2838
 
2894
2839
void TestEventRepeater::Append(TestEventListener *listener) {
2895
 
  listeners_.PushBack(listener);
 
2840
  listeners_.push_back(listener);
2896
2841
}
2897
2842
 
2898
2843
// TODO(vladl@google.com): Factor the search functionality into Vector::Find.
2899
2844
TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {
2900
 
  for (int i = 0; i < listeners_.size(); ++i) {
2901
 
    if (listeners_.GetElement(i) == listener) {
2902
 
      listeners_.Erase(i);
 
2845
  for (size_t i = 0; i < listeners_.size(); ++i) {
 
2846
    if (listeners_[i] == listener) {
 
2847
      listeners_.erase(listeners_.begin() + i);
2903
2848
      return listener;
2904
2849
    }
2905
2850
  }
2912
2857
#define GTEST_REPEATER_METHOD_(Name, Type) \
2913
2858
void TestEventRepeater::Name(const Type& parameter) { \
2914
2859
  if (forwarding_enabled_) { \
2915
 
    for (int i = 0; i < listeners_.size(); i++) { \
2916
 
      listeners_.GetElement(i)->Name(parameter); \
 
2860
    for (size_t i = 0; i < listeners_.size(); i++) { \
 
2861
      listeners_[i]->Name(parameter); \
2917
2862
    } \
2918
2863
  } \
2919
2864
}
2923
2868
void TestEventRepeater::Name(const Type& parameter) { \
2924
2869
  if (forwarding_enabled_) { \
2925
2870
    for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \
2926
 
      listeners_.GetElement(i)->Name(parameter); \
 
2871
      listeners_[i]->Name(parameter); \
2927
2872
    } \
2928
2873
  } \
2929
2874
}
2946
2891
void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,
2947
2892
                                             int iteration) {
2948
2893
  if (forwarding_enabled_) {
2949
 
    for (int i = 0; i < listeners_.size(); i++) {
2950
 
      listeners_.GetElement(i)->OnTestIterationStart(unit_test, iteration);
 
2894
    for (size_t i = 0; i < listeners_.size(); i++) {
 
2895
      listeners_[i]->OnTestIterationStart(unit_test, iteration);
2951
2896
    }
2952
2897
  }
2953
2898
}
2956
2901
                                           int iteration) {
2957
2902
  if (forwarding_enabled_) {
2958
2903
    for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) {
2959
 
      listeners_.GetElement(i)->OnTestIterationEnd(unit_test, iteration);
 
2904
      listeners_[i]->OnTestIterationEnd(unit_test, iteration);
2960
2905
    }
2961
2906
  }
2962
2907
}
2986
2931
  // is_attribute is true, the text is meant to appear as an attribute
2987
2932
  // value, and normalizable whitespace is preserved by replacing it
2988
2933
  // with character references.
2989
 
  static String EscapeXml(const char* str, bool is_attribute);
 
2934
  static std::string EscapeXml(const char* str, bool is_attribute);
2990
2935
 
2991
2936
  // Returns the given string with all characters invalid in XML removed.
2992
 
  static String RemoveInvalidXmlCharacters(const char* str);
 
2937
  static string RemoveInvalidXmlCharacters(const string& str);
2993
2938
 
2994
2939
  // Convenience wrapper around EscapeXml when str is an attribute value.
2995
 
  static String EscapeXmlAttribute(const char* str) {
 
2940
  static std::string EscapeXmlAttribute(const char* str) {
2996
2941
    return EscapeXml(str, true);
2997
2942
  }
2998
2943
 
2999
2944
  // Convenience wrapper around EscapeXml when str is not an attribute value.
3000
 
  static String EscapeXmlText(const char* str) { return EscapeXml(str, false); }
 
2945
  static std::string EscapeXmlText(const char* str) {
 
2946
    return EscapeXml(str, false);
 
2947
  }
3001
2948
 
3002
2949
  // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
3003
2950
  static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
3015
2962
 
3016
2963
  // Produces a string representing the test properties in a result as space
3017
2964
  // delimited XML attributes based on the property key="value" pairs.
3018
 
  // When the String is not empty, it includes a space at the beginning,
 
2965
  // When the std::string is not empty, it includes a space at the beginning,
3019
2966
  // to delimit this attribute from prior attributes.
3020
 
  static String TestPropertiesAsXmlAttributes(const TestResult& result);
 
2967
  static std::string TestPropertiesAsXmlAttributes(const TestResult& result);
3021
2968
 
3022
2969
  // The output file.
3023
 
  const String output_file_;
 
2970
  const std::string output_file_;
3024
2971
 
3025
2972
  GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);
3026
2973
};
3078
3025
// most invalid characters can be retained using character references.
3079
3026
// TODO(wan): It might be nice to have a minimally invasive, human-readable
3080
3027
// escaping scheme for invalid characters, rather than dropping them.
3081
 
String XmlUnitTestResultPrinter::EscapeXml(const char* str, bool is_attribute) {
 
3028
std::string XmlUnitTestResultPrinter::EscapeXml(
 
3029
    const char* str, bool is_attribute) {
3082
3030
  Message m;
3083
3031
 
3084
3032
  if (str != NULL) {
3123
3071
// Returns the given string with all characters invalid in XML removed.
3124
3072
// Currently invalid characters are dropped from the string. An
3125
3073
// alternative is to replace them with certain characters such as . or ?.
3126
 
String XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(const char* str) {
3127
 
  char* const output = new char[strlen(str) + 1];
3128
 
  char* appender = output;
3129
 
  for (char ch = *str; ch != '\0'; ch = *++str)
3130
 
    if (IsValidXmlCharacter(ch))
3131
 
      *appender++ = ch;
3132
 
  *appender = '\0';
 
3074
string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(const string& str) {
 
3075
  string output;
 
3076
  output.reserve(str.size());
 
3077
  for (string::const_iterator it = str.begin(); it != str.end(); ++it)
 
3078
    if (IsValidXmlCharacter(*it))
 
3079
      output.push_back(*it);
3133
3080
 
3134
 
  String ret_value(output);
3135
 
  delete[] output;
3136
 
  return ret_value;
 
3081
  return output;
3137
3082
}
3138
3083
 
3139
3084
// The following routines generate an XML representation of a UnitTest
3152
3097
//   </testsuite>
3153
3098
// </testsuites>
3154
3099
 
3155
 
// Formats the given time in milliseconds as seconds.  The returned
3156
 
// C-string is owned by this function and cannot be released by the
3157
 
// caller.  Calling the function again invalidates the previous
3158
 
// result.
3159
 
const char* FormatTimeInMillisAsSeconds(TimeInMillis ms) {
3160
 
  static String str;
3161
 
  str = (Message() << (ms/1000.0)).GetString();
3162
 
  return str.c_str();
 
3100
// Formats the given time in milliseconds as seconds.
 
3101
std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {
 
3102
  ::std::stringstream ss;
 
3103
  ss << ms/1000.0;
 
3104
  return ss.str();
 
3105
}
 
3106
 
 
3107
// Converts the given epoch time in milliseconds to a date string in the ISO
 
3108
// 8601 format, without the timezone information.
 
3109
std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) {
 
3110
  // Using non-reentrant version as localtime_r is not portable.
 
3111
  time_t seconds = static_cast<time_t>(ms / 1000);
 
3112
#ifdef _MSC_VER
 
3113
# pragma warning(push)          // Saves the current warning state.
 
3114
# pragma warning(disable:4996)  // Temporarily disables warning 4996
 
3115
                                // (function or variable may be unsafe).
 
3116
  const struct tm* const time_struct = localtime(&seconds);  // NOLINT
 
3117
# pragma warning(pop)           // Restores the warning state again.
 
3118
#else
 
3119
  const struct tm* const time_struct = localtime(&seconds);  // NOLINT
 
3120
#endif
 
3121
  if (time_struct == NULL)
 
3122
    return "";  // Invalid ms value
 
3123
 
 
3124
  return String::Format("%d-%02d-%02dT%02d:%02d:%02d",  // YYYY-MM-DDThh:mm:ss
 
3125
                        time_struct->tm_year + 1900,
 
3126
                        time_struct->tm_mon + 1,
 
3127
                        time_struct->tm_mday,
 
3128
                        time_struct->tm_hour,
 
3129
                        time_struct->tm_min,
 
3130
                        time_struct->tm_sec);
3163
3131
}
3164
3132
 
3165
3133
// Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
3170
3138
  for (;;) {
3171
3139
    const char* const next_segment = strstr(segment, "]]>");
3172
3140
    if (next_segment != NULL) {
3173
 
      stream->write(segment, next_segment - segment);
 
3141
      stream->write(
 
3142
          segment, static_cast<std::streamsize>(next_segment - segment));
3174
3143
      *stream << "]]>]]&gt;<![CDATA[";
3175
3144
      segment = next_segment + strlen("]]>");
3176
3145
    } else {
3188
3157
                                                 const TestInfo& test_info) {
3189
3158
  const TestResult& result = *test_info.result();
3190
3159
  *stream << "    <testcase name=\""
3191
 
          << EscapeXmlAttribute(test_info.name()).c_str()
3192
 
          << "\" status=\""
 
3160
          << EscapeXmlAttribute(test_info.name()).c_str() << "\"";
 
3161
 
 
3162
  if (test_info.value_param() != NULL) {
 
3163
    *stream << " value_param=\"" << EscapeXmlAttribute(test_info.value_param())
 
3164
            << "\"";
 
3165
  }
 
3166
  if (test_info.type_param() != NULL) {
 
3167
    *stream << " type_param=\"" << EscapeXmlAttribute(test_info.type_param())
 
3168
            << "\"";
 
3169
  }
 
3170
 
 
3171
  *stream << " status=\""
3193
3172
          << (test_info.should_run() ? "run" : "notrun")
3194
3173
          << "\" time=\""
3195
3174
          << FormatTimeInMillisAsSeconds(result.elapsed_time())
3200
3179
  for (int i = 0; i < result.total_part_count(); ++i) {
3201
3180
    const TestPartResult& part = result.GetTestPartResult(i);
3202
3181
    if (part.failed()) {
3203
 
      if (++failures == 1)
 
3182
      if (++failures == 1) {
3204
3183
        *stream << ">\n";
 
3184
      }
 
3185
      const string location = internal::FormatCompilerIndependentFileLocation(
 
3186
          part.file_name(), part.line_number());
 
3187
      const string summary = location + "\n" + part.summary();
3205
3188
      *stream << "      <failure message=\""
3206
 
              << EscapeXmlAttribute(part.summary()).c_str()
 
3189
              << EscapeXmlAttribute(summary.c_str())
3207
3190
              << "\" type=\"\">";
3208
 
      const String message = RemoveInvalidXmlCharacters(String::Format(
3209
 
          "%s:%d\n%s",
3210
 
          part.file_name(), part.line_number(),
3211
 
          part.message()).c_str());
3212
 
      OutputXmlCDataSection(stream, message.c_str());
 
3191
      const string detail = location + "\n" + part.message();
 
3192
      OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
3213
3193
      *stream << "</failure>\n";
3214
3194
    }
3215
3195
  }
3232
3212
          test_case.disabled_test_count());
3233
3213
  fprintf(out,
3234
3214
          "errors=\"0\" time=\"%s\">\n",
3235
 
          FormatTimeInMillisAsSeconds(test_case.elapsed_time()));
 
3215
          FormatTimeInMillisAsSeconds(test_case.elapsed_time()).c_str());
3236
3216
  for (int i = 0; i < test_case.total_test_count(); ++i) {
3237
 
    StrStream stream;
 
3217
    ::std::stringstream stream;
3238
3218
    OutputXmlTestInfo(&stream, test_case.name(), *test_case.GetTestInfo(i));
3239
 
    fprintf(out, "%s", StrStreamToString(&stream).c_str());
 
3219
    fprintf(out, "%s", StringStreamToString(&stream).c_str());
3240
3220
  }
3241
3221
  fprintf(out, "  </testsuite>\n");
3242
3222
}
3247
3227
  fprintf(out, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
3248
3228
  fprintf(out,
3249
3229
          "<testsuites tests=\"%d\" failures=\"%d\" disabled=\"%d\" "
3250
 
          "errors=\"0\" time=\"%s\" ",
 
3230
          "errors=\"0\" timestamp=\"%s\" time=\"%s\" ",
3251
3231
          unit_test.total_test_count(),
3252
3232
          unit_test.failed_test_count(),
3253
3233
          unit_test.disabled_test_count(),
3254
 
          FormatTimeInMillisAsSeconds(unit_test.elapsed_time()));
 
3234
          FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp()).c_str(),
 
3235
          FormatTimeInMillisAsSeconds(unit_test.elapsed_time()).c_str());
3255
3236
  if (GTEST_FLAG(shuffle)) {
3256
3237
    fprintf(out, "random_seed=\"%d\" ", unit_test.random_seed());
3257
3238
  }
3263
3244
 
3264
3245
// Produces a string representing the test properties in a result as space
3265
3246
// delimited XML attributes based on the property key="value" pairs.
3266
 
String XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
 
3247
std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
3267
3248
    const TestResult& result) {
3268
3249
  Message attributes;
3269
3250
  for (int i = 0; i < result.test_property_count(); ++i) {
3276
3257
 
3277
3258
// End XmlUnitTestResultPrinter
3278
3259
 
 
3260
#if GTEST_CAN_STREAM_RESULTS_
 
3261
 
 
3262
// Streams test results to the given port on the given host machine.
 
3263
class StreamingListener : public EmptyTestEventListener {
 
3264
 public:
 
3265
  // Escapes '=', '&', '%', and '\n' characters in str as "%xx".
 
3266
  static string UrlEncode(const char* str);
 
3267
 
 
3268
  StreamingListener(const string& host, const string& port)
 
3269
      : sockfd_(-1), host_name_(host), port_num_(port) {
 
3270
    MakeConnection();
 
3271
    Send("gtest_streaming_protocol_version=1.0\n");
 
3272
  }
 
3273
 
 
3274
  virtual ~StreamingListener() {
 
3275
    if (sockfd_ != -1)
 
3276
      CloseConnection();
 
3277
  }
 
3278
 
 
3279
  void OnTestProgramStart(const UnitTest& /* unit_test */) {
 
3280
    Send("event=TestProgramStart\n");
 
3281
  }
 
3282
 
 
3283
  void OnTestProgramEnd(const UnitTest& unit_test) {
 
3284
    // Note that Google Test current only report elapsed time for each
 
3285
    // test iteration, not for the entire test program.
 
3286
    Send(String::Format("event=TestProgramEnd&passed=%d\n",
 
3287
                        unit_test.Passed()));
 
3288
 
 
3289
    // Notify the streaming server to stop.
 
3290
    CloseConnection();
 
3291
  }
 
3292
 
 
3293
  void OnTestIterationStart(const UnitTest& /* unit_test */, int iteration) {
 
3294
    Send(String::Format("event=TestIterationStart&iteration=%d\n",
 
3295
                        iteration));
 
3296
  }
 
3297
 
 
3298
  void OnTestIterationEnd(const UnitTest& unit_test, int /* iteration */) {
 
3299
    Send(String::Format("event=TestIterationEnd&passed=%d&elapsed_time=%sms\n",
 
3300
                        unit_test.Passed(),
 
3301
                        StreamableToString(unit_test.elapsed_time()).c_str()));
 
3302
  }
 
3303
 
 
3304
  void OnTestCaseStart(const TestCase& test_case) {
 
3305
    Send(String::Format("event=TestCaseStart&name=%s\n", test_case.name()));
 
3306
  }
 
3307
 
 
3308
  void OnTestCaseEnd(const TestCase& test_case) {
 
3309
    Send(String::Format("event=TestCaseEnd&passed=%d&elapsed_time=%sms\n",
 
3310
                        test_case.Passed(),
 
3311
                        StreamableToString(test_case.elapsed_time()).c_str()));
 
3312
  }
 
3313
 
 
3314
  void OnTestStart(const TestInfo& test_info) {
 
3315
    Send(String::Format("event=TestStart&name=%s\n", test_info.name()));
 
3316
  }
 
3317
 
 
3318
  void OnTestEnd(const TestInfo& test_info) {
 
3319
    Send(String::Format(
 
3320
        "event=TestEnd&passed=%d&elapsed_time=%sms\n",
 
3321
        (test_info.result())->Passed(),
 
3322
        StreamableToString((test_info.result())->elapsed_time()).c_str()));
 
3323
  }
 
3324
 
 
3325
  void OnTestPartResult(const TestPartResult& test_part_result) {
 
3326
    const char* file_name = test_part_result.file_name();
 
3327
    if (file_name == NULL)
 
3328
      file_name = "";
 
3329
    Send(String::Format("event=TestPartResult&file=%s&line=%d&message=",
 
3330
                        UrlEncode(file_name).c_str(),
 
3331
                        test_part_result.line_number()));
 
3332
    Send(UrlEncode(test_part_result.message()) + "\n");
 
3333
  }
 
3334
 
 
3335
 private:
 
3336
  // Creates a client socket and connects to the server.
 
3337
  void MakeConnection();
 
3338
 
 
3339
  // Closes the socket.
 
3340
  void CloseConnection() {
 
3341
    GTEST_CHECK_(sockfd_ != -1)
 
3342
        << "CloseConnection() can be called only when there is a connection.";
 
3343
 
 
3344
    close(sockfd_);
 
3345
    sockfd_ = -1;
 
3346
  }
 
3347
 
 
3348
  // Sends a string to the socket.
 
3349
  void Send(const string& message) {
 
3350
    GTEST_CHECK_(sockfd_ != -1)
 
3351
        << "Send() can be called only when there is a connection.";
 
3352
 
 
3353
    const int len = static_cast<int>(message.length());
 
3354
    if (write(sockfd_, message.c_str(), len) != len) {
 
3355
      GTEST_LOG_(WARNING)
 
3356
          << "stream_result_to: failed to stream to "
 
3357
          << host_name_ << ":" << port_num_;
 
3358
    }
 
3359
  }
 
3360
 
 
3361
  int sockfd_;   // socket file descriptor
 
3362
  const string host_name_;
 
3363
  const string port_num_;
 
3364
 
 
3365
  GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener);
 
3366
};  // class StreamingListener
 
3367
 
 
3368
// Checks if str contains '=', '&', '%' or '\n' characters. If yes,
 
3369
// replaces them by "%xx" where xx is their hexadecimal value. For
 
3370
// example, replaces "=" with "%3D".  This algorithm is O(strlen(str))
 
3371
// in both time and space -- important as the input str may contain an
 
3372
// arbitrarily long test failure message and stack trace.
 
3373
string StreamingListener::UrlEncode(const char* str) {
 
3374
  string result;
 
3375
  result.reserve(strlen(str) + 1);
 
3376
  for (char ch = *str; ch != '\0'; ch = *++str) {
 
3377
    switch (ch) {
 
3378
      case '%':
 
3379
      case '=':
 
3380
      case '&':
 
3381
      case '\n':
 
3382
        result.append(String::Format("%%%02x", static_cast<unsigned char>(ch)));
 
3383
        break;
 
3384
      default:
 
3385
        result.push_back(ch);
 
3386
        break;
 
3387
    }
 
3388
  }
 
3389
  return result;
 
3390
}
 
3391
 
 
3392
void StreamingListener::MakeConnection() {
 
3393
  GTEST_CHECK_(sockfd_ == -1)
 
3394
      << "MakeConnection() can't be called when there is already a connection.";
 
3395
 
 
3396
  addrinfo hints;
 
3397
  memset(&hints, 0, sizeof(hints));
 
3398
  hints.ai_family = AF_UNSPEC;    // To allow both IPv4 and IPv6 addresses.
 
3399
  hints.ai_socktype = SOCK_STREAM;
 
3400
  addrinfo* servinfo = NULL;
 
3401
 
 
3402
  // Use the getaddrinfo() to get a linked list of IP addresses for
 
3403
  // the given host name.
 
3404
  const int error_num = getaddrinfo(
 
3405
      host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
 
3406
  if (error_num != 0) {
 
3407
    GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: "
 
3408
                        << gai_strerror(error_num);
 
3409
  }
 
3410
 
 
3411
  // Loop through all the results and connect to the first we can.
 
3412
  for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != NULL;
 
3413
       cur_addr = cur_addr->ai_next) {
 
3414
    sockfd_ = socket(
 
3415
        cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol);
 
3416
    if (sockfd_ != -1) {
 
3417
      // Connect the client socket to the server socket.
 
3418
      if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
 
3419
        close(sockfd_);
 
3420
        sockfd_ = -1;
 
3421
      }
 
3422
    }
 
3423
  }
 
3424
 
 
3425
  freeaddrinfo(servinfo);  // all done with this structure
 
3426
 
 
3427
  if (sockfd_ == -1) {
 
3428
    GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to "
 
3429
                        << host_name_ << ":" << port_num_;
 
3430
  }
 
3431
}
 
3432
 
 
3433
// End of class Streaming Listener
 
3434
#endif  // GTEST_CAN_STREAM_RESULTS__
 
3435
 
3279
3436
// Class ScopedTrace
3280
3437
 
3281
3438
// Pushes the given source file location and message onto a per-thread
3282
3439
// trace stack maintained by Google Test.
3283
 
// L < UnitTest::mutex_
3284
 
ScopedTrace::ScopedTrace(const char* file, int line, const Message& message) {
 
3440
ScopedTrace::ScopedTrace(const char* file, int line, const Message& message)
 
3441
    GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
3285
3442
  TraceInfo trace;
3286
3443
  trace.file = file;
3287
3444
  trace.line = line;
3291
3448
}
3292
3449
 
3293
3450
// Pops the info pushed by the c'tor.
3294
 
// L < UnitTest::mutex_
3295
 
ScopedTrace::~ScopedTrace() {
 
3451
ScopedTrace::~ScopedTrace()
 
3452
    GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
3296
3453
  UnitTest::GetInstance()->PopGTestTrace();
3297
3454
}
3298
3455
 
3299
3456
 
3300
3457
// class OsStackTraceGetter
3301
3458
 
3302
 
// Returns the current OS stack trace as a String.  Parameters:
 
3459
// Returns the current OS stack trace as an std::string.  Parameters:
3303
3460
//
3304
3461
//   max_depth  - the maximum number of stack frames to be included
3305
3462
//                in the trace.
3306
3463
//   skip_count - the number of top frames to be skipped; doesn't count
3307
3464
//                against max_depth.
3308
3465
//
3309
 
// L < mutex_
3310
 
// We use "L < mutex_" to denote that the function may acquire mutex_.
3311
 
String OsStackTraceGetter::CurrentStackTrace(int, int) {
3312
 
  return String("");
 
3466
string OsStackTraceGetter::CurrentStackTrace(int /* max_depth */,
 
3467
                                             int /* skip_count */)
 
3468
    GTEST_LOCK_EXCLUDED_(mutex_) {
 
3469
  return "";
3313
3470
}
3314
3471
 
3315
 
// L < mutex_
3316
 
void OsStackTraceGetter::UponLeavingGTest() {
 
3472
void OsStackTraceGetter::UponLeavingGTest()
 
3473
    GTEST_LOCK_EXCLUDED_(mutex_) {
3317
3474
}
3318
3475
 
3319
3476
const char* const
3467
3624
// Gets the number of tests that should run.
3468
3625
int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
3469
3626
 
 
3627
// Gets the time of the test program start, in ms from the start of the
 
3628
// UNIX epoch.
 
3629
internal::TimeInMillis UnitTest::start_timestamp() const {
 
3630
    return impl()->start_timestamp();
 
3631
}
 
3632
 
3470
3633
// Gets the elapsed time, in milliseconds.
3471
3634
internal::TimeInMillis UnitTest::elapsed_time() const {
3472
3635
  return impl()->elapsed_time();
3512
3675
    return NULL;
3513
3676
  }
3514
3677
 
3515
 
  impl_->environments()->PushBack(env);
3516
 
  impl_->environments_in_reverse_order()->PushFront(env);
 
3678
  impl_->environments().push_back(env);
3517
3679
  return env;
3518
3680
}
3519
3681
 
3520
 
#if GTEST_HAS_EXCEPTIONS
3521
 
// A failed Google Test assertion will throw an exception of this type
3522
 
// when exceptions are enabled.  We derive it from std::runtime_error,
3523
 
// which is for errors presumably detectable only at run time.  Since
3524
 
// std::runtime_error inherits from std::exception, many testing
3525
 
// frameworks know how to extract and print the message inside it.
3526
 
class GoogleTestFailureException : public ::std::runtime_error {
3527
 
 public:
3528
 
  explicit GoogleTestFailureException(const TestPartResult& failure)
3529
 
      : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
3530
 
};
3531
 
#endif
3532
 
 
3533
3682
// Adds a TestPartResult to the current TestResult object.  All Google Test
3534
3683
// assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
3535
3684
// this to report their results.  The user code should use the
3536
3685
// assertion macros instead of calling this directly.
3537
 
// L < mutex_
3538
 
void UnitTest::AddTestPartResult(TestPartResult::Type result_type,
3539
 
                                 const char* file_name,
3540
 
                                 int line_number,
3541
 
                                 const internal::String& message,
3542
 
                                 const internal::String& os_stack_trace) {
 
3686
void UnitTest::AddTestPartResult(
 
3687
    TestPartResult::Type result_type,
 
3688
    const char* file_name,
 
3689
    int line_number,
 
3690
    const std::string& message,
 
3691
    const std::string& os_stack_trace)
 
3692
        GTEST_LOCK_EXCLUDED_(mutex_) {
3543
3693
  Message msg;
3544
3694
  msg << message;
3545
3695
 
3546
3696
  internal::MutexLock lock(&mutex_);
3547
 
  if (impl_->gtest_trace_stack()->size() > 0) {
 
3697
  if (impl_->gtest_trace_stack().size() > 0) {
3548
3698
    msg << "\n" << GTEST_NAME_ << " trace:";
3549
3699
 
3550
 
    for (int i = 0; i < impl_->gtest_trace_stack()->size(); i++) {
3551
 
      const internal::TraceInfo& trace =
3552
 
          impl_->gtest_trace_stack()->GetElement(i);
 
3700
    for (int i = static_cast<int>(impl_->gtest_trace_stack().size());
 
3701
         i > 0; --i) {
 
3702
      const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
3553
3703
      msg << "\n" << internal::FormatFileLocation(trace.file, trace.line)
3554
3704
          << " " << trace.message;
3555
3705
    }
3578
3728
      // the --gtest_catch_exceptions flags are specified.
3579
3729
      DebugBreak();
3580
3730
#else
3581
 
      *static_cast<int*>(NULL) = 1;
 
3731
      // Dereference NULL through a volatile pointer to prevent the compiler
 
3732
      // from removing. We use this rather than abort() or __builtin_trap() for
 
3733
      // portability: Symbian doesn't implement abort() well, and some debuggers
 
3734
      // don't correctly trap abort().
 
3735
      *static_cast<volatile int*>(NULL) = 1;
3582
3736
#endif  // GTEST_OS_WINDOWS
3583
3737
    } else if (GTEST_FLAG(throw_on_failure)) {
3584
3738
#if GTEST_HAS_EXCEPTIONS
3606
3760
// We don't protect this under mutex_, as we only support calling it
3607
3761
// from the main thread.
3608
3762
int UnitTest::Run() {
 
3763
  // Captures the value of GTEST_FLAG(catch_exceptions).  This value will be
 
3764
  // used for the duration of the program.
 
3765
  impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions));
 
3766
 
3609
3767
#if GTEST_HAS_SEH
3610
 
  // Catch SEH-style exceptions.
3611
 
 
3612
3768
  const bool in_death_test_child_process =
3613
3769
      internal::GTEST_FLAG(internal_run_death_test).length() > 0;
3614
3770
 
3615
3771
  // Either the user wants Google Test to catch exceptions thrown by the
3616
3772
  // tests or this is executing in the context of death test child
3617
3773
  // process. In either case the user does not want to see pop-up dialogs
3618
 
  // about crashes - they are expected..
3619
 
  if (GTEST_FLAG(catch_exceptions) || in_death_test_child_process) {
3620
 
#if !GTEST_OS_WINDOWS_MOBILE
 
3774
  // about crashes - they are expected.
 
3775
  if (impl()->catch_exceptions() || in_death_test_child_process) {
 
3776
# if !GTEST_OS_WINDOWS_MOBILE
3621
3777
    // SetErrorMode doesn't exist on CE.
3622
3778
    SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
3623
3779
                 SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
3624
 
#endif  // !GTEST_OS_WINDOWS_MOBILE
 
3780
# endif  // !GTEST_OS_WINDOWS_MOBILE
3625
3781
 
3626
 
#if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
 
3782
# if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
3627
3783
    // Death test children can be terminated with _abort().  On Windows,
3628
3784
    // _abort() can show a dialog with a warning message.  This forces the
3629
3785
    // abort message to go to stderr instead.
3630
3786
    _set_error_mode(_OUT_TO_STDERR);
3631
 
#endif
 
3787
# endif
3632
3788
 
3633
 
#if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
 
3789
# if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
3634
3790
    // In the debug version, Visual Studio pops up a separate dialog
3635
3791
    // offering a choice to debug the aborted program. We need to suppress
3636
3792
    // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
3646
3802
      _set_abort_behavior(
3647
3803
          0x0,                                    // Clear the following flags:
3648
3804
          _WRITE_ABORT_MSG | _CALL_REPORTFAULT);  // pop-up window, core dump.
3649
 
#endif
3650
 
  }
3651
 
 
3652
 
  __try {
3653
 
    return impl_->RunAllTests();
3654
 
  } __except(internal::UnitTestOptions::GTestShouldProcessSEH(
3655
 
      GetExceptionCode())) {
3656
 
    printf("Exception thrown with code 0x%x.\nFAIL\n", GetExceptionCode());
3657
 
    fflush(stdout);
3658
 
    return 1;
3659
 
  }
3660
 
 
3661
 
#else  // We are on a compiler or platform that doesn't support SEH.
3662
 
 
3663
 
  return impl_->RunAllTests();
 
3805
# endif
 
3806
  }
3664
3807
#endif  // GTEST_HAS_SEH
 
3808
 
 
3809
  return internal::HandleExceptionsInMethodIfSupported(
 
3810
      impl(),
 
3811
      &internal::UnitTestImpl::RunAllTests,
 
3812
      "auxiliary test code (environments or event listeners)") ? 0 : 1;
3665
3813
}
3666
3814
 
3667
3815
// Returns the working directory when the first TEST() or TEST_F() was
3672
3820
 
3673
3821
// Returns the TestCase object for the test that's currently running,
3674
3822
// or NULL if no test is running.
3675
 
// L < mutex_
3676
 
const TestCase* UnitTest::current_test_case() const {
 
3823
const TestCase* UnitTest::current_test_case() const
 
3824
    GTEST_LOCK_EXCLUDED_(mutex_) {
3677
3825
  internal::MutexLock lock(&mutex_);
3678
3826
  return impl_->current_test_case();
3679
3827
}
3680
3828
 
3681
3829
// Returns the TestInfo object for the test that's currently running,
3682
3830
// or NULL if no test is running.
3683
 
// L < mutex_
3684
 
const TestInfo* UnitTest::current_test_info() const {
 
3831
const TestInfo* UnitTest::current_test_info() const
 
3832
    GTEST_LOCK_EXCLUDED_(mutex_) {
3685
3833
  internal::MutexLock lock(&mutex_);
3686
3834
  return impl_->current_test_info();
3687
3835
}
3692
3840
#if GTEST_HAS_PARAM_TEST
3693
3841
// Returns ParameterizedTestCaseRegistry object used to keep track of
3694
3842
// value-parameterized tests and instantiate and register them.
3695
 
// L < mutex_
3696
3843
internal::ParameterizedTestCaseRegistry&
3697
 
    UnitTest::parameterized_test_registry() {
 
3844
    UnitTest::parameterized_test_registry()
 
3845
        GTEST_LOCK_EXCLUDED_(mutex_) {
3698
3846
  return impl_->parameterized_test_registry();
3699
3847
}
3700
3848
#endif  // GTEST_HAS_PARAM_TEST
3711
3859
 
3712
3860
// Pushes a trace defined by SCOPED_TRACE() on to the per-thread
3713
3861
// Google Test trace stack.
3714
 
// L < mutex_
3715
 
void UnitTest::PushGTestTrace(const internal::TraceInfo& trace) {
 
3862
void UnitTest::PushGTestTrace(const internal::TraceInfo& trace)
 
3863
    GTEST_LOCK_EXCLUDED_(mutex_) {
3716
3864
  internal::MutexLock lock(&mutex_);
3717
 
  impl_->gtest_trace_stack()->PushFront(trace);
 
3865
  impl_->gtest_trace_stack().push_back(trace);
3718
3866
}
3719
3867
 
3720
3868
// Pops a trace from the per-thread Google Test trace stack.
3721
 
// L < mutex_
3722
 
void UnitTest::PopGTestTrace() {
 
3869
void UnitTest::PopGTestTrace()
 
3870
    GTEST_LOCK_EXCLUDED_(mutex_) {
3723
3871
  internal::MutexLock lock(&mutex_);
3724
 
  impl_->gtest_trace_stack()->PopFront(NULL);
 
3872
  impl_->gtest_trace_stack().pop_back();
3725
3873
}
3726
3874
 
3727
3875
namespace internal {
3729
3877
UnitTestImpl::UnitTestImpl(UnitTest* parent)
3730
3878
    : parent_(parent),
3731
3879
#ifdef _MSC_VER
3732
 
#pragma warning(push)                    // Saves the current warning state.
3733
 
#pragma warning(disable:4355)            // Temporarily disables warning 4355
 
3880
# pragma warning(push)                    // Saves the current warning state.
 
3881
# pragma warning(disable:4355)            // Temporarily disables warning 4355
3734
3882
                                         // (using this in initializer).
3735
3883
      default_global_test_part_result_reporter_(this),
3736
3884
      default_per_thread_test_part_result_reporter_(this),
3737
 
#pragma warning(pop)                     // Restores the warning state again.
 
3885
# pragma warning(pop)                     // Restores the warning state again.
3738
3886
#else
3739
3887
      default_global_test_part_result_reporter_(this),
3740
3888
      default_per_thread_test_part_result_reporter_(this),
3755
3903
      post_flag_parse_init_performed_(false),
3756
3904
      random_seed_(0),  // Will be overridden by the flag before first use.
3757
3905
      random_(0),  // Will be reseeded before first use.
3758
 
#if GTEST_HAS_DEATH_TEST
 
3906
      start_timestamp_(0),
3759
3907
      elapsed_time_(0),
 
3908
#if GTEST_HAS_DEATH_TEST
3760
3909
      internal_run_death_test_flag_(NULL),
3761
 
      death_test_factory_(new DefaultDeathTestFactory) {
3762
 
#else
3763
 
      elapsed_time_(0) {
3764
 
#endif  // GTEST_HAS_DEATH_TEST
 
3910
      death_test_factory_(new DefaultDeathTestFactory),
 
3911
#endif
 
3912
      // Will be overridden by the flag before first use.
 
3913
      catch_exceptions_(false) {
3765
3914
  listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);
3766
3915
}
3767
3916
 
3768
3917
UnitTestImpl::~UnitTestImpl() {
3769
3918
  // Deletes every TestCase.
3770
 
  test_cases_.ForEach(internal::Delete<TestCase>);
 
3919
  ForEach(test_cases_, internal::Delete<TestCase>);
3771
3920
 
3772
3921
  // Deletes every Environment.
3773
 
  environments_.ForEach(internal::Delete<Environment>);
 
3922
  ForEach(environments_, internal::Delete<Environment>);
3774
3923
 
3775
3924
  delete os_stack_trace_getter_;
3776
3925
}
3787
3936
// Initializes event listeners performing XML output as specified by
3788
3937
// UnitTestOptions. Must not be called before InitGoogleTest.
3789
3938
void UnitTestImpl::ConfigureXmlOutput() {
3790
 
  const String& output_format = UnitTestOptions::GetOutputFormat();
 
3939
  const std::string& output_format = UnitTestOptions::GetOutputFormat();
3791
3940
  if (output_format == "xml") {
3792
3941
    listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
3793
3942
        UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
3798
3947
  }
3799
3948
}
3800
3949
 
 
3950
#if GTEST_CAN_STREAM_RESULTS_
 
3951
// Initializes event listeners for streaming test results in string form.
 
3952
// Must not be called before InitGoogleTest.
 
3953
void UnitTestImpl::ConfigureStreamingOutput() {
 
3954
  const std::string& target = GTEST_FLAG(stream_result_to);
 
3955
  if (!target.empty()) {
 
3956
    const size_t pos = target.find(':');
 
3957
    if (pos != std::string::npos) {
 
3958
      listeners()->Append(new StreamingListener(target.substr(0, pos),
 
3959
                                                target.substr(pos+1)));
 
3960
    } else {
 
3961
      printf("WARNING: unrecognized streaming target \"%s\" ignored.\n",
 
3962
             target.c_str());
 
3963
      fflush(stdout);
 
3964
    }
 
3965
  }
 
3966
}
 
3967
#endif  // GTEST_CAN_STREAM_RESULTS_
 
3968
 
3801
3969
// Performs initialization dependent upon flag values obtained in
3802
3970
// ParseGoogleTestFlagsOnly.  Is called from InitGoogleTest after the call to
3803
3971
// ParseGoogleTestFlagsOnly.  In case a user neglects to call InitGoogleTest
3821
3989
    // Configures listeners for XML output. This makes it possible for users
3822
3990
    // to shut down the default XML output before invoking RUN_ALL_TESTS.
3823
3991
    ConfigureXmlOutput();
 
3992
 
 
3993
#if GTEST_CAN_STREAM_RESULTS_
 
3994
    // Configures listeners for streaming test results to the specified server.
 
3995
    ConfigureStreamingOutput();
 
3996
#endif  // GTEST_CAN_STREAM_RESULTS_
3824
3997
  }
3825
3998
}
3826
3999
 
3835
4008
class TestCaseNameIs {
3836
4009
 public:
3837
4010
  // Constructor.
3838
 
  explicit TestCaseNameIs(const String& name)
 
4011
  explicit TestCaseNameIs(const std::string& name)
3839
4012
      : name_(name) {}
3840
4013
 
3841
4014
  // Returns true iff the name of test_case matches name_.
3844
4017
  }
3845
4018
 
3846
4019
 private:
3847
 
  String name_;
 
4020
  std::string name_;
3848
4021
};
3849
4022
 
3850
4023
// Finds and returns a TestCase with the given name.  If one doesn't
3855
4028
// Arguments:
3856
4029
//
3857
4030
//   test_case_name: name of the test case
 
4031
//   type_param:     the name of the test case's type parameter, or NULL if
 
4032
//                   this is not a typed or a type-parameterized test case.
3858
4033
//   set_up_tc:      pointer to the function that sets up the test case
3859
4034
//   tear_down_tc:   pointer to the function that tears down the test case
3860
4035
TestCase* UnitTestImpl::GetTestCase(const char* test_case_name,
3861
 
                                    const char* comment,
 
4036
                                    const char* type_param,
3862
4037
                                    Test::SetUpTestCaseFunc set_up_tc,
3863
4038
                                    Test::TearDownTestCaseFunc tear_down_tc) {
3864
4039
  // Can we find a TestCase with the given name?
3865
 
  TestCase** test_case = test_cases_.FindIf(TestCaseNameIs(test_case_name));
 
4040
  const std::vector<TestCase*>::const_iterator test_case =
 
4041
      std::find_if(test_cases_.begin(), test_cases_.end(),
 
4042
                   TestCaseNameIs(test_case_name));
3866
4043
 
3867
 
  if (test_case != NULL)
 
4044
  if (test_case != test_cases_.end())
3868
4045
    return *test_case;
3869
4046
 
3870
4047
  // No.  Let's create one.
3871
4048
  TestCase* const new_test_case =
3872
 
      new TestCase(test_case_name, comment, set_up_tc, tear_down_tc);
 
4049
      new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc);
3873
4050
 
3874
4051
  // Is this a death test case?
3875
 
  if (internal::UnitTestOptions::MatchesFilter(String(test_case_name),
 
4052
  if (internal::UnitTestOptions::MatchesFilter(test_case_name,
3876
4053
                                               kDeathTestCaseFilter)) {
3877
4054
    // Yes.  Inserts the test case after the last death test case
3878
4055
    // defined so far.  This only works when the test cases haven't
3879
4056
    // been shuffled.  Otherwise we may end up running a death test
3880
4057
    // after a non-death test.
3881
 
    test_cases_.Insert(new_test_case, ++last_death_test_case_);
 
4058
    ++last_death_test_case_;
 
4059
    test_cases_.insert(test_cases_.begin() + last_death_test_case_,
 
4060
                       new_test_case);
3882
4061
  } else {
3883
4062
    // No.  Appends to the end of the list.
3884
 
    test_cases_.PushBack(new_test_case);
 
4063
    test_cases_.push_back(new_test_case);
3885
4064
  }
3886
4065
 
3887
 
  test_case_indices_.PushBack(test_case_indices_.size());
 
4066
  test_case_indices_.push_back(static_cast<int>(test_case_indices_.size()));
3888
4067
  return new_test_case;
3889
4068
}
3890
4069
 
3891
4070
// Helpers for setting up / tearing down the given environment.  They
3892
 
// are for use in the Vector::ForEach() method.
 
4071
// are for use in the ForEach() function.
3893
4072
static void SetUpEnvironment(Environment* env) { env->SetUp(); }
3894
4073
static void TearDownEnvironment(Environment* env) { env->TearDown(); }
3895
4074
 
3896
4075
// Runs all tests in this UnitTest object, prints the result, and
3897
 
// returns 0 if all tests are successful, or 1 otherwise.  If any
3898
 
// exception is thrown during a test on Windows, this test is
3899
 
// considered to be failed, but the rest of the tests will still be
3900
 
// run.  (We disable exceptions on Linux and Mac OS X, so the issue
3901
 
// doesn't apply there.)
 
4076
// returns true if all tests are successful.  If any exception is
 
4077
// thrown during a test, the test is considered to be failed, but the
 
4078
// rest of the tests will still be run.
 
4079
//
3902
4080
// When parameterized tests are enabled, it expands and registers
3903
4081
// parameterized tests first in RegisterParameterizedTests().
3904
4082
// All other functions called from RunAllTests() may safely assume that
3905
4083
// parameterized tests are ready to be counted and run.
3906
 
int UnitTestImpl::RunAllTests() {
 
4084
bool UnitTestImpl::RunAllTests() {
3907
4085
  // Makes sure InitGoogleTest() was called.
3908
4086
  if (!GTestIsInitialized()) {
3909
4087
    printf("%s",
3910
4088
           "\nThis test program did NOT call ::testing::InitGoogleTest "
3911
4089
           "before calling RUN_ALL_TESTS().  Please fix it.\n");
3912
 
    return 1;
 
4090
    return false;
3913
4091
  }
3914
4092
 
3915
4093
  // Do not run any test if the --help flag was specified.
3916
4094
  if (g_help_flag)
3917
 
    return 0;
 
4095
    return true;
3918
4096
 
3919
4097
  // Repeats the call to the post-flag parsing initialization in case the
3920
4098
  // user didn't call InitGoogleTest.
3946
4124
  if (GTEST_FLAG(list_tests)) {
3947
4125
    // This must be called *after* FilterTests() has been called.
3948
4126
    ListTestsMatchingFilter();
3949
 
    return 0;
 
4127
    return true;
3950
4128
  }
3951
4129
 
3952
4130
  random_seed_ = GTEST_FLAG(shuffle) ?
3957
4135
 
3958
4136
  TestEventListener* repeater = listeners()->repeater();
3959
4137
 
 
4138
  start_timestamp_ = GetTimeInMillis();
3960
4139
  repeater->OnTestProgramStart(*parent_);
3961
4140
 
3962
4141
  // How many times to repeat the tests?  We don't want to repeat them
3965
4144
  // Repeats forever if the repeat count is negative.
3966
4145
  const bool forever = repeat < 0;
3967
4146
  for (int i = 0; forever || i != repeat; i++) {
3968
 
    ClearResult();
 
4147
    // We want to preserve failures generated by ad-hoc test
 
4148
    // assertions executed before RUN_ALL_TESTS().
 
4149
    ClearNonAdHocTestResult();
3969
4150
 
3970
4151
    const TimeInMillis start = GetTimeInMillis();
3971
4152
 
3985
4166
    if (has_tests_to_run) {
3986
4167
      // Sets up all environments beforehand.
3987
4168
      repeater->OnEnvironmentsSetUpStart(*parent_);
3988
 
      environments_.ForEach(SetUpEnvironment);
 
4169
      ForEach(environments_, SetUpEnvironment);
3989
4170
      repeater->OnEnvironmentsSetUpEnd(*parent_);
3990
4171
 
3991
4172
      // Runs the tests only if there was no fatal failure during global
3992
4173
      // set-up.
3993
4174
      if (!Test::HasFatalFailure()) {
3994
 
        for (int i = 0; i < total_test_case_count(); i++) {
3995
 
          GetMutableTestCase(i)->Run();
 
4175
        for (int test_index = 0; test_index < total_test_case_count();
 
4176
             test_index++) {
 
4177
          GetMutableTestCase(test_index)->Run();
3996
4178
        }
3997
4179
      }
3998
4180
 
3999
4181
      // Tears down all environments in reverse order afterwards.
4000
4182
      repeater->OnEnvironmentsTearDownStart(*parent_);
4001
 
      environments_in_reverse_order_.ForEach(TearDownEnvironment);
 
4183
      std::for_each(environments_.rbegin(), environments_.rend(),
 
4184
                    TearDownEnvironment);
4002
4185
      repeater->OnEnvironmentsTearDownEnd(*parent_);
4003
4186
    }
4004
4187
 
4028
4211
 
4029
4212
  repeater->OnTestProgramEnd(*parent_);
4030
4213
 
4031
 
  // Returns 0 if all tests passed, or 1 other wise.
4032
 
  return failed ? 1 : 0;
 
4214
  return !failed;
4033
4215
}
4034
4216
 
4035
4217
// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
4103
4285
// Parses the environment variable var as an Int32. If it is unset,
4104
4286
// returns default_val. If it is not an Int32, prints an error
4105
4287
// and aborts.
4106
 
Int32 Int32FromEnvOrDie(const char* const var, Int32 default_val) {
 
4288
Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) {
4107
4289
  const char* str_val = posix::GetEnv(var);
4108
4290
  if (str_val == NULL) {
4109
4291
    return default_val;
4144
4326
  // this shard.
4145
4327
  int num_runnable_tests = 0;
4146
4328
  int num_selected_tests = 0;
4147
 
  for (int i = 0; i < test_cases_.size(); i++) {
4148
 
    TestCase* const test_case = test_cases_.GetElement(i);
4149
 
    const String &test_case_name = test_case->name();
 
4329
  for (size_t i = 0; i < test_cases_.size(); i++) {
 
4330
    TestCase* const test_case = test_cases_[i];
 
4331
    const std::string &test_case_name = test_case->name();
4150
4332
    test_case->set_should_run(false);
4151
4333
 
4152
 
    for (int j = 0; j < test_case->test_info_list().size(); j++) {
4153
 
      TestInfo* const test_info = test_case->test_info_list().GetElement(j);
4154
 
      const String test_name(test_info->name());
 
4334
    for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
 
4335
      TestInfo* const test_info = test_case->test_info_list()[j];
 
4336
      const std::string test_name(test_info->name());
4155
4337
      // A test is disabled if test case name or test name matches
4156
4338
      // kDisableTestFilter.
4157
4339
      const bool is_disabled =
4159
4341
                                                   kDisableTestFilter) ||
4160
4342
          internal::UnitTestOptions::MatchesFilter(test_name,
4161
4343
                                                   kDisableTestFilter);
4162
 
      test_info->impl()->set_is_disabled(is_disabled);
 
4344
      test_info->is_disabled_ = is_disabled;
4163
4345
 
4164
4346
      const bool matches_filter =
4165
4347
          internal::UnitTestOptions::FilterMatchesTest(test_case_name,
4166
4348
                                                       test_name);
4167
 
      test_info->impl()->set_matches_filter(matches_filter);
 
4349
      test_info->matches_filter_ = matches_filter;
4168
4350
 
4169
4351
      const bool is_runnable =
4170
4352
          (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
4178
4360
      num_runnable_tests += is_runnable;
4179
4361
      num_selected_tests += is_selected;
4180
4362
 
4181
 
      test_info->impl()->set_should_run(is_selected);
 
4363
      test_info->should_run_ = is_selected;
4182
4364
      test_case->set_should_run(test_case->should_run() || is_selected);
4183
4365
    }
4184
4366
  }
4187
4369
 
4188
4370
// Prints the names of the tests matching the user-specified filter flag.
4189
4371
void UnitTestImpl::ListTestsMatchingFilter() {
4190
 
  for (int i = 0; i < test_cases_.size(); i++) {
4191
 
    const TestCase* const test_case = test_cases_.GetElement(i);
 
4372
  for (size_t i = 0; i < test_cases_.size(); i++) {
 
4373
    const TestCase* const test_case = test_cases_[i];
4192
4374
    bool printed_test_case_name = false;
4193
4375
 
4194
 
    for (int j = 0; j < test_case->test_info_list().size(); j++) {
 
4376
    for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
4195
4377
      const TestInfo* const test_info =
4196
 
          test_case->test_info_list().GetElement(j);
4197
 
      if (test_info->matches_filter()) {
 
4378
          test_case->test_info_list()[j];
 
4379
      if (test_info->matches_filter_) {
4198
4380
        if (!printed_test_case_name) {
4199
4381
          printed_test_case_name = true;
4200
4382
          printf("%s.\n", test_case->name());
4234
4416
// the TestResult for the ad hoc test if no test is running.
4235
4417
TestResult* UnitTestImpl::current_test_result() {
4236
4418
  return current_test_info_ ?
4237
 
    current_test_info_->impl()->result() : &ad_hoc_test_result_;
 
4419
      &(current_test_info_->result_) : &ad_hoc_test_result_;
4238
4420
}
4239
4421
 
4240
4422
// Shuffles all test cases, and the tests within each test case,
4241
4423
// making sure that death tests are still run first.
4242
4424
void UnitTestImpl::ShuffleTests() {
4243
4425
  // Shuffles the death test cases.
4244
 
  test_case_indices_.ShuffleRange(random(), 0, last_death_test_case_ + 1);
 
4426
  ShuffleRange(random(), 0, last_death_test_case_ + 1, &test_case_indices_);
4245
4427
 
4246
4428
  // Shuffles the non-death test cases.
4247
 
  test_case_indices_.ShuffleRange(random(), last_death_test_case_ + 1,
4248
 
                                  test_cases_.size());
 
4429
  ShuffleRange(random(), last_death_test_case_ + 1,
 
4430
               static_cast<int>(test_cases_.size()), &test_case_indices_);
4249
4431
 
4250
4432
  // Shuffles the tests inside each test case.
4251
 
  for (int i = 0; i < test_cases_.size(); i++) {
4252
 
    test_cases_.GetElement(i)->ShuffleTests(random());
 
4433
  for (size_t i = 0; i < test_cases_.size(); i++) {
 
4434
    test_cases_[i]->ShuffleTests(random());
4253
4435
  }
4254
4436
}
4255
4437
 
4256
4438
// Restores the test cases and tests to their order before the first shuffle.
4257
4439
void UnitTestImpl::UnshuffleTests() {
4258
 
  for (int i = 0; i < test_cases_.size(); i++) {
 
4440
  for (size_t i = 0; i < test_cases_.size(); i++) {
4259
4441
    // Unshuffles the tests in each test case.
4260
 
    test_cases_.GetElement(i)->UnshuffleTests();
 
4442
    test_cases_[i]->UnshuffleTests();
4261
4443
    // Resets the index of each test case.
4262
 
    test_case_indices_.GetMutableElement(i) = i;
 
4444
    test_case_indices_[i] = static_cast<int>(i);
4263
4445
  }
4264
4446
}
4265
4447
 
4266
 
// TestInfoImpl constructor. The new instance assumes ownership of the test
4267
 
// factory object.
4268
 
TestInfoImpl::TestInfoImpl(TestInfo* parent,
4269
 
                           const char* test_case_name,
4270
 
                           const char* name,
4271
 
                           const char* test_case_comment,
4272
 
                           const char* comment,
4273
 
                           TypeId fixture_class_id,
4274
 
                           internal::TestFactoryBase* factory) :
4275
 
    parent_(parent),
4276
 
    test_case_name_(String(test_case_name)),
4277
 
    name_(String(name)),
4278
 
    test_case_comment_(String(test_case_comment)),
4279
 
    comment_(String(comment)),
4280
 
    fixture_class_id_(fixture_class_id),
4281
 
    should_run_(false),
4282
 
    is_disabled_(false),
4283
 
    matches_filter_(false),
4284
 
    factory_(factory) {
4285
 
}
4286
 
 
4287
 
// TestInfoImpl destructor.
4288
 
TestInfoImpl::~TestInfoImpl() {
4289
 
  delete factory_;
4290
 
}
4291
 
 
4292
 
// Returns the current OS stack trace as a String.
 
4448
// Returns the current OS stack trace as an std::string.
4293
4449
//
4294
4450
// The maximum number of stack frames to be included is specified by
4295
4451
// the gtest_stack_trace_depth flag.  The skip_count parameter
4299
4455
// For example, if Foo() calls Bar(), which in turn calls
4300
4456
// GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
4301
4457
// the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
4302
 
String GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/,
4303
 
                                       int skip_count) {
 
4458
std::string GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/,
 
4459
                                            int skip_count) {
4304
4460
  // We pass skip_count + 1 to skip this wrapper function in addition
4305
4461
  // to what the user really wants to skip.
4306
4462
  return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
4307
4463
}
4308
4464
 
4309
 
// Used by the GTEST_HIDE_UNREACHABLE_CODE_ macro to suppress unreachable
4310
 
// code warnings.
 
4465
// Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to
 
4466
// suppress unreachable code warnings.
4311
4467
namespace {
4312
4468
class ClassUniqueToAlwaysTrue {};
4313
4469
}
4324
4480
  return true;
4325
4481
}
4326
4482
 
 
4483
// If *pstr starts with the given prefix, modifies *pstr to be right
 
4484
// past the prefix and returns true; otherwise leaves *pstr unchanged
 
4485
// and returns false.  None of pstr, *pstr, and prefix can be NULL.
 
4486
bool SkipPrefix(const char* prefix, const char** pstr) {
 
4487
  const size_t prefix_len = strlen(prefix);
 
4488
  if (strncmp(*pstr, prefix, prefix_len) == 0) {
 
4489
    *pstr += prefix_len;
 
4490
    return true;
 
4491
  }
 
4492
  return false;
 
4493
}
 
4494
 
4327
4495
// Parses a string as a command line flag.  The string should have
4328
4496
// the format "--flag=value".  When def_optional is true, the "=value"
4329
4497
// part can be omitted.
4336
4504
  if (str == NULL || flag == NULL) return NULL;
4337
4505
 
4338
4506
  // The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
4339
 
  const String flag_str = String::Format("--%s%s", GTEST_FLAG_PREFIX_, flag);
 
4507
  const std::string flag_str = std::string("--") + GTEST_FLAG_PREFIX_ + flag;
4340
4508
  const size_t flag_len = flag_str.length();
4341
4509
  if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;
4342
4510
 
4401
4569
//
4402
4570
// On success, stores the value of the flag in *value, and returns
4403
4571
// true.  On failure, returns false without changing *value.
4404
 
bool ParseStringFlag(const char* str, const char* flag, String* value) {
 
4572
bool ParseStringFlag(const char* str, const char* flag, std::string* value) {
4405
4573
  // Gets the value of the flag as a string.
4406
4574
  const char* const value_str = ParseFlagValue(str, flag, false);
4407
4575
 
4413
4581
  return true;
4414
4582
}
4415
4583
 
 
4584
// Determines whether a string has a prefix that Google Test uses for its
 
4585
// flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.
 
4586
// If Google Test detects that a command line flag has its prefix but is not
 
4587
// recognized, it will print its help message. Flags starting with
 
4588
// GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
 
4589
// internal flags and do not trigger the help message.
 
4590
static bool HasGoogleTestFlagPrefix(const char* str) {
 
4591
  return (SkipPrefix("--", &str) ||
 
4592
          SkipPrefix("-", &str) ||
 
4593
          SkipPrefix("/", &str)) &&
 
4594
         !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
 
4595
         (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
 
4596
          SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str));
 
4597
}
 
4598
 
4416
4599
// Prints a string containing code-encoded text.  The following escape
4417
4600
// sequences can be used in the string to control the text color:
4418
4601
//
4438
4621
      return;
4439
4622
    }
4440
4623
 
4441
 
    ColoredPrintf(color, "%s", String(str, p - str).c_str());
 
4624
    ColoredPrintf(color, "%s", std::string(str, p).c_str());
4442
4625
 
4443
4626
    const char ch = p[1];
4444
4627
    str = p + 2;
4492
4675
    GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n"
4493
4676
"      Generate an XML report in the given directory or with the given file\n"
4494
4677
"      name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n"
 
4678
#if GTEST_CAN_STREAM_RESULTS_
 
4679
"  @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n"
 
4680
"      Stream test results to the given server.\n"
 
4681
#endif  // GTEST_CAN_STREAM_RESULTS_
4495
4682
"\n"
4496
4683
"Assertion Behavior:\n"
4497
4684
#if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
4502
4689
"      Turn assertion failures into debugger break-points.\n"
4503
4690
"  @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n"
4504
4691
"      Turn assertion failures into C++ exceptions.\n"
4505
 
#if GTEST_OS_WINDOWS
4506
 
"  @G--" GTEST_FLAG_PREFIX_ "catch_exceptions@D\n"
4507
 
"      Suppress pop-ups caused by exceptions.\n"
4508
 
#endif  // GTEST_OS_WINDOWS
 
4692
"  @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n"
 
4693
"      Do not report exceptions as test failures. Instead, allow them\n"
 
4694
"      to crash the program or throw a pop-up (on Windows).\n"
4509
4695
"\n"
4510
4696
"Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set "
4511
4697
    "the corresponding\n"
4525
4711
template <typename CharType>
4526
4712
void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
4527
4713
  for (int i = 1; i < *argc; i++) {
4528
 
    const String arg_string = StreamableToString(argv[i]);
 
4714
    const std::string arg_string = StreamableToString(argv[i]);
4529
4715
    const char* const arg = arg_string.c_str();
4530
4716
 
4531
4717
    using internal::ParseBoolFlag;
4553
4739
        ParseInt32Flag(arg, kRandomSeedFlag, &GTEST_FLAG(random_seed)) ||
4554
4740
        ParseInt32Flag(arg, kRepeatFlag, &GTEST_FLAG(repeat)) ||
4555
4741
        ParseBoolFlag(arg, kShuffleFlag, &GTEST_FLAG(shuffle)) ||
4556
 
        ParseBoolFlag(arg, kThrowOnFailureFlag, &GTEST_FLAG(throw_on_failure))
 
4742
        ParseInt32Flag(arg, kStackTraceDepthFlag,
 
4743
                       &GTEST_FLAG(stack_trace_depth)) ||
 
4744
        ParseStringFlag(arg, kStreamResultToFlag,
 
4745
                        &GTEST_FLAG(stream_result_to)) ||
 
4746
        ParseBoolFlag(arg, kThrowOnFailureFlag,
 
4747
                      &GTEST_FLAG(throw_on_failure))
4557
4748
        ) {
4558
4749
      // Yes.  Shift the remainder of the argv list left by one.  Note
4559
4750
      // that argv has (*argc + 1) elements, the last one always being
4570
4761
      // an element.
4571
4762
      i--;
4572
4763
    } else if (arg_string == "--help" || arg_string == "-h" ||
4573
 
               arg_string == "-?" || arg_string == "/?") {
 
4764
               arg_string == "-?" || arg_string == "/?" ||
 
4765
               HasGoogleTestFlagPrefix(arg)) {
 
4766
      // Both help flag and unrecognized Google Test flags (excluding
 
4767
      // internal ones) trigger help display.
4574
4768
      g_help_flag = true;
4575
4769
    }
4576
4770
  }
4608
4802
  internal::g_executable_path = internal::StreamableToString(argv[0]);
4609
4803
 
4610
4804
#if GTEST_HAS_DEATH_TEST
 
4805
 
4611
4806
  g_argvs.clear();
4612
4807
  for (int i = 0; i != *argc; i++) {
4613
4808
    g_argvs.push_back(StreamableToString(argv[i]));
4614
4809
  }
 
4810
 
4615
4811
#endif  // GTEST_HAS_DEATH_TEST
4616
4812
 
4617
4813
  ParseGoogleTestFlagsOnly(argc, argv);