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