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