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