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