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