~seb128/sync-monitor/synchronization-typo

« back to all changes in this revision

Viewing changes to 3rd_party/gmock/gtest/src/gtest.cc

  • Committer: CI bot
  • Author(s): Renato Araujo Oliveira Filho
  • Date: 2014-04-09 06:46:43 UTC
  • mfrom: (17.1.46 initial-release)
  • Revision ID: ps-jenkins@lists.canonical.com-20140409064643-bidc0po4gfxj6vol
Updated package version. Fixes: 1302159, 1302160, 1302171

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