~ubuntu-branches/ubuntu/oneiric/protobuf/oneiric

« back to all changes in this revision

Viewing changes to src/gtest/gtest.cc

  • Committer: Bazaar Package Importer
  • Author(s): Iustin Pop
  • Date: 2008-08-03 11:01:44 UTC
  • Revision ID: james.westby@ubuntu.com-20080803110144-uyiw41bf1m2oe17t
Tags: upstream-2.0.0~b
ImportĀ upstreamĀ versionĀ 2.0.0~b

Show diffs side-by-side

added added

removed removed

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