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