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