media/webrtc/trunk/testing/gtest/src/gtest.cc

Thu, 15 Jan 2015 15:55:04 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Thu, 15 Jan 2015 15:55:04 +0100
branch
TOR_BUG_9701
changeset 9
a63d609f5ebe
permissions
-rw-r--r--

Back out 97036ab72558 which inappropriately compared turds to third parties.

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

mercurial