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