1// Copyright 2008, 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: mheule@google.com (Markus Heule) 31// 32// Google C++ Testing Framework (Google Test) 33// 34// Sometimes it's desirable to build Google Test by compiling a single file. 35// This file serves this purpose. 36 37// This line ensures that gtest.h can be compiled on its own, even 38// when it's fused. 39#include <gtest/gtest.h> 40 41// The following lines pull in the real gtest *.cc files. 42// Copyright 2005, Google Inc. 43// All rights reserved. 44// 45// Redistribution and use in source and binary forms, with or without 46// modification, are permitted provided that the following conditions are 47// met: 48// 49// * Redistributions of source code must retain the above copyright 50// notice, this list of conditions and the following disclaimer. 51// * Redistributions in binary form must reproduce the above 52// copyright notice, this list of conditions and the following disclaimer 53// in the documentation and/or other materials provided with the 54// distribution. 55// * Neither the name of Google Inc. nor the names of its 56// contributors may be used to endorse or promote products derived from 57// this software without specific prior written permission. 58// 59// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 60// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 61// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 62// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 63// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 64// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 65// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 66// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 67// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 68// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 69// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 70// 71// Author: wan@google.com (Zhanyong Wan) 72// 73// The Google C++ Testing Framework (Google Test) 74 75// Copyright 2007, Google Inc. 76// All rights reserved. 77// 78// Redistribution and use in source and binary forms, with or without 79// modification, are permitted provided that the following conditions are 80// met: 81// 82// * Redistributions of source code must retain the above copyright 83// notice, this list of conditions and the following disclaimer. 84// * Redistributions in binary form must reproduce the above 85// copyright notice, this list of conditions and the following disclaimer 86// in the documentation and/or other materials provided with the 87// distribution. 88// * Neither the name of Google Inc. nor the names of its 89// contributors may be used to endorse or promote products derived from 90// this software without specific prior written permission. 91// 92// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 93// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 94// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 95// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 96// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 97// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 98// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 99// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 100// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 101// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 102// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 103// 104// Author: wan@google.com (Zhanyong Wan) 105// 106// Utilities for testing Google Test itself and code that uses Google Test 107// (e.g. frameworks built on top of Google Test). 108 109#ifndef GTEST_INCLUDE_GTEST_GTEST_SPI_H_ 110#define GTEST_INCLUDE_GTEST_GTEST_SPI_H_ 111 112 113namespace testing { 114 115// This helper class can be used to mock out Google Test failure reporting 116// so that we can test Google Test or code that builds on Google Test. 117// 118// An object of this class appends a TestPartResult object to the 119// TestPartResultArray object given in the constructor whenever a Google Test 120// failure is reported. It can either intercept only failures that are 121// generated in the same thread that created this object or it can intercept 122// all generated failures. The scope of this mock object can be controlled with 123// the second argument to the two arguments constructor. 124class GTEST_API_ ScopedFakeTestPartResultReporter 125 : public TestPartResultReporterInterface { 126 public: 127 // The two possible mocking modes of this object. 128 enum InterceptMode { 129 INTERCEPT_ONLY_CURRENT_THREAD, // Intercepts only thread local failures. 130 INTERCEPT_ALL_THREADS // Intercepts all failures. 131 }; 132 133 // The c'tor sets this object as the test part result reporter used 134 // by Google Test. The 'result' parameter specifies where to report the 135 // results. This reporter will only catch failures generated in the current 136 // thread. DEPRECATED 137 explicit ScopedFakeTestPartResultReporter(TestPartResultArray* result); 138 139 // Same as above, but you can choose the interception scope of this object. 140 ScopedFakeTestPartResultReporter(InterceptMode intercept_mode, 141 TestPartResultArray* result); 142 143 // The d'tor restores the previous test part result reporter. 144 virtual ~ScopedFakeTestPartResultReporter(); 145 146 // Appends the TestPartResult object to the TestPartResultArray 147 // received in the constructor. 148 // 149 // This method is from the TestPartResultReporterInterface 150 // interface. 151 virtual void ReportTestPartResult(const TestPartResult& result); 152 private: 153 void Init(); 154 155 const InterceptMode intercept_mode_; 156 TestPartResultReporterInterface* old_reporter_; 157 TestPartResultArray* const result_; 158 159 GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedFakeTestPartResultReporter); 160}; 161 162namespace internal { 163 164// A helper class for implementing EXPECT_FATAL_FAILURE() and 165// EXPECT_NONFATAL_FAILURE(). Its destructor verifies that the given 166// TestPartResultArray contains exactly one failure that has the given 167// type and contains the given substring. If that's not the case, a 168// non-fatal failure will be generated. 169class GTEST_API_ SingleFailureChecker { 170 public: 171 // The constructor remembers the arguments. 172 SingleFailureChecker(const TestPartResultArray* results, 173 TestPartResult::Type type, 174 const char* substr); 175 ~SingleFailureChecker(); 176 private: 177 const TestPartResultArray* const results_; 178 const TestPartResult::Type type_; 179 const String substr_; 180 181 GTEST_DISALLOW_COPY_AND_ASSIGN_(SingleFailureChecker); 182}; 183 184} // namespace internal 185 186} // namespace testing 187 188// A set of macros for testing Google Test assertions or code that's expected 189// to generate Google Test fatal failures. It verifies that the given 190// statement will cause exactly one fatal Google Test failure with 'substr' 191// being part of the failure message. 192// 193// There are two different versions of this macro. EXPECT_FATAL_FAILURE only 194// affects and considers failures generated in the current thread and 195// EXPECT_FATAL_FAILURE_ON_ALL_THREADS does the same but for all threads. 196// 197// The verification of the assertion is done correctly even when the statement 198// throws an exception or aborts the current function. 199// 200// Known restrictions: 201// - 'statement' cannot reference local non-static variables or 202// non-static members of the current object. 203// - 'statement' cannot return a value. 204// - You cannot stream a failure message to this macro. 205// 206// Note that even though the implementations of the following two 207// macros are much alike, we cannot refactor them to use a common 208// helper macro, due to some peculiarity in how the preprocessor 209// works. The AcceptsMacroThatExpandsToUnprotectedComma test in 210// gtest_unittest.cc will fail to compile if we do that. 211#define EXPECT_FATAL_FAILURE(statement, substr) \ 212 do { \ 213 class GTestExpectFatalFailureHelper {\ 214 public:\ 215 static void Execute() { statement; }\ 216 };\ 217 ::testing::TestPartResultArray gtest_failures;\ 218 ::testing::internal::SingleFailureChecker gtest_checker(\ 219 >est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\ 220 {\ 221 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ 222 ::testing::ScopedFakeTestPartResultReporter:: \ 223 INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\ 224 GTestExpectFatalFailureHelper::Execute();\ 225 }\ 226 } while (::testing::internal::AlwaysFalse()) 227 228#define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \ 229 do { \ 230 class GTestExpectFatalFailureHelper {\ 231 public:\ 232 static void Execute() { statement; }\ 233 };\ 234 ::testing::TestPartResultArray gtest_failures;\ 235 ::testing::internal::SingleFailureChecker gtest_checker(\ 236 >est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\ 237 {\ 238 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ 239 ::testing::ScopedFakeTestPartResultReporter:: \ 240 INTERCEPT_ALL_THREADS, >est_failures);\ 241 GTestExpectFatalFailureHelper::Execute();\ 242 }\ 243 } while (::testing::internal::AlwaysFalse()) 244 245// A macro for testing Google Test assertions or code that's expected to 246// generate Google Test non-fatal failures. It asserts that the given 247// statement will cause exactly one non-fatal Google Test failure with 'substr' 248// being part of the failure message. 249// 250// There are two different versions of this macro. EXPECT_NONFATAL_FAILURE only 251// affects and considers failures generated in the current thread and 252// EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS does the same but for all threads. 253// 254// 'statement' is allowed to reference local variables and members of 255// the current object. 256// 257// The verification of the assertion is done correctly even when the statement 258// throws an exception or aborts the current function. 259// 260// Known restrictions: 261// - You cannot stream a failure message to this macro. 262// 263// Note that even though the implementations of the following two 264// macros are much alike, we cannot refactor them to use a common 265// helper macro, due to some peculiarity in how the preprocessor 266// works. If we do that, the code won't compile when the user gives 267// EXPECT_NONFATAL_FAILURE() a statement that contains a macro that 268// expands to code containing an unprotected comma. The 269// AcceptsMacroThatExpandsToUnprotectedComma test in gtest_unittest.cc 270// catches that. 271// 272// For the same reason, we have to write 273// if (::testing::internal::AlwaysTrue()) { statement; } 274// instead of 275// GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) 276// to avoid an MSVC warning on unreachable code. 277#define EXPECT_NONFATAL_FAILURE(statement, substr) \ 278 do {\ 279 ::testing::TestPartResultArray gtest_failures;\ 280 ::testing::internal::SingleFailureChecker gtest_checker(\ 281 >est_failures, ::testing::TestPartResult::kNonFatalFailure, \ 282 (substr));\ 283 {\ 284 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ 285 ::testing::ScopedFakeTestPartResultReporter:: \ 286 INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\ 287 if (::testing::internal::AlwaysTrue()) { statement; }\ 288 }\ 289 } while (::testing::internal::AlwaysFalse()) 290 291#define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \ 292 do {\ 293 ::testing::TestPartResultArray gtest_failures;\ 294 ::testing::internal::SingleFailureChecker gtest_checker(\ 295 >est_failures, ::testing::TestPartResult::kNonFatalFailure, \ 296 (substr));\ 297 {\ 298 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ 299 ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS,\ 300 >est_failures);\ 301 if (::testing::internal::AlwaysTrue()) { statement; }\ 302 }\ 303 } while (::testing::internal::AlwaysFalse()) 304 305#endif // GTEST_INCLUDE_GTEST_GTEST_SPI_H_ 306 307#include <ctype.h> 308#include <math.h> 309#include <stdarg.h> 310#include <stdio.h> 311#include <stdlib.h> 312#include <wchar.h> 313#include <wctype.h> 314 315#include <algorithm> 316#include <ostream> 317#include <sstream> 318#include <vector> 319 320#if GTEST_OS_LINUX 321 322// TODO(kenton@google.com): Use autoconf to detect availability of 323// gettimeofday(). 324#define GTEST_HAS_GETTIMEOFDAY_ 1 325 326#include <fcntl.h> 327#include <limits.h> 328#include <sched.h> 329// Declares vsnprintf(). This header is not available on Windows. 330#include <strings.h> 331#include <sys/mman.h> 332#include <sys/time.h> 333#include <unistd.h> 334#include <string> 335#include <vector> 336 337#elif GTEST_OS_SYMBIAN 338#define GTEST_HAS_GETTIMEOFDAY_ 1 339#include <sys/time.h> // NOLINT 340 341#elif GTEST_OS_ZOS 342#define GTEST_HAS_GETTIMEOFDAY_ 1 343#include <sys/time.h> // NOLINT 344 345// On z/OS we additionally need strings.h for strcasecmp. 346#include <strings.h> // NOLINT 347 348#elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE. 349 350#include <windows.h> // NOLINT 351 352#elif GTEST_OS_WINDOWS // We are on Windows proper. 353 354#include <io.h> // NOLINT 355#include <sys/timeb.h> // NOLINT 356#include <sys/types.h> // NOLINT 357#include <sys/stat.h> // NOLINT 358 359#if GTEST_OS_WINDOWS_MINGW 360// MinGW has gettimeofday() but not _ftime64(). 361// TODO(kenton@google.com): Use autoconf to detect availability of 362// gettimeofday(). 363// TODO(kenton@google.com): There are other ways to get the time on 364// Windows, like GetTickCount() or GetSystemTimeAsFileTime(). MinGW 365// supports these. consider using them instead. 366#define GTEST_HAS_GETTIMEOFDAY_ 1 367#include <sys/time.h> // NOLINT 368#endif // GTEST_OS_WINDOWS_MINGW 369 370// cpplint thinks that the header is already included, so we want to 371// silence it. 372#include <windows.h> // NOLINT 373 374#else 375 376// Assume other platforms have gettimeofday(). 377// TODO(kenton@google.com): Use autoconf to detect availability of 378// gettimeofday(). 379#define GTEST_HAS_GETTIMEOFDAY_ 1 380 381// cpplint thinks that the header is already included, so we want to 382// silence it. 383#include <sys/time.h> // NOLINT 384#include <unistd.h> // NOLINT 385 386#endif // GTEST_OS_LINUX 387 388#if GTEST_HAS_EXCEPTIONS 389#include <stdexcept> 390#endif 391 392// Indicates that this translation unit is part of Google Test's 393// implementation. It must come before gtest-internal-inl.h is 394// included, or there will be a compiler error. This trick is to 395// prevent a user from accidentally including gtest-internal-inl.h in 396// his code. 397#define GTEST_IMPLEMENTATION_ 1 398// Copyright 2005, Google Inc. 399// All rights reserved. 400// 401// Redistribution and use in source and binary forms, with or without 402// modification, are permitted provided that the following conditions are 403// met: 404// 405// * Redistributions of source code must retain the above copyright 406// notice, this list of conditions and the following disclaimer. 407// * Redistributions in binary form must reproduce the above 408// copyright notice, this list of conditions and the following disclaimer 409// in the documentation and/or other materials provided with the 410// distribution. 411// * Neither the name of Google Inc. nor the names of its 412// contributors may be used to endorse or promote products derived from 413// this software without specific prior written permission. 414// 415// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 416// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 417// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 418// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 419// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 420// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 421// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 422// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 423// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 424// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 425// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 426 427// Utility functions and classes used by the Google C++ testing framework. 428// 429// Author: wan@google.com (Zhanyong Wan) 430// 431// This file contains purely Google Test's internal implementation. Please 432// DO NOT #INCLUDE IT IN A USER PROGRAM. 433 434#ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_ 435#define GTEST_SRC_GTEST_INTERNAL_INL_H_ 436 437// GTEST_IMPLEMENTATION_ is defined to 1 iff the current translation unit is 438// part of Google Test's implementation; otherwise it's undefined. 439#if !GTEST_IMPLEMENTATION_ 440// A user is trying to include this from his code - just say no. 441#error "gtest-internal-inl.h is part of Google Test's internal implementation." 442#error "It must not be included except by Google Test itself." 443#endif // GTEST_IMPLEMENTATION_ 444 445#ifndef _WIN32_WCE 446#include <errno.h> 447#endif // !_WIN32_WCE 448#include <stddef.h> 449#include <stdlib.h> // For strtoll/_strtoul64/malloc/free. 450#include <string.h> // For memmove. 451 452#include <algorithm> 453#include <string> 454#include <vector> 455 456 457#if GTEST_OS_WINDOWS 458#include <windows.h> // For DWORD. 459#endif // GTEST_OS_WINDOWS 460 461 462namespace testing { 463 464// Declares the flags. 465// 466// We don't want the users to modify this flag in the code, but want 467// Google Test's own unit tests to be able to access it. Therefore we 468// declare it here as opposed to in gtest.h. 469GTEST_DECLARE_bool_(death_test_use_fork); 470 471namespace internal { 472 473// The value of GetTestTypeId() as seen from within the Google Test 474// library. This is solely for testing GetTestTypeId(). 475GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest; 476 477// Names of the flags (needed for parsing Google Test flags). 478const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests"; 479const char kBreakOnFailureFlag[] = "break_on_failure"; 480const char kCatchExceptionsFlag[] = "catch_exceptions"; 481const char kColorFlag[] = "color"; 482const char kFilterFlag[] = "filter"; 483const char kListTestsFlag[] = "list_tests"; 484const char kOutputFlag[] = "output"; 485const char kPrintTimeFlag[] = "print_time"; 486const char kRandomSeedFlag[] = "random_seed"; 487const char kRepeatFlag[] = "repeat"; 488const char kShuffleFlag[] = "shuffle"; 489const char kStackTraceDepthFlag[] = "stack_trace_depth"; 490const char kThrowOnFailureFlag[] = "throw_on_failure"; 491 492// A valid random seed must be in [1, kMaxRandomSeed]. 493const int kMaxRandomSeed = 99999; 494 495// g_help_flag is true iff the --help flag or an equivalent form is 496// specified on the command line. 497GTEST_API_ extern bool g_help_flag; 498 499// Returns the current time in milliseconds. 500GTEST_API_ TimeInMillis GetTimeInMillis(); 501 502// Returns true iff Google Test should use colors in the output. 503GTEST_API_ bool ShouldUseColor(bool stdout_is_tty); 504 505// Formats the given time in milliseconds as seconds. 506GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms); 507 508// Parses a string for an Int32 flag, in the form of "--flag=value". 509// 510// On success, stores the value of the flag in *value, and returns 511// true. On failure, returns false without changing *value. 512GTEST_API_ bool ParseInt32Flag( 513 const char* str, const char* flag, Int32* value); 514 515// Returns a random seed in range [1, kMaxRandomSeed] based on the 516// given --gtest_random_seed flag value. 517inline int GetRandomSeedFromFlag(Int32 random_seed_flag) { 518 const unsigned int raw_seed = (random_seed_flag == 0) ? 519 static_cast<unsigned int>(GetTimeInMillis()) : 520 static_cast<unsigned int>(random_seed_flag); 521 522 // Normalizes the actual seed to range [1, kMaxRandomSeed] such that 523 // it's easy to type. 524 const int normalized_seed = 525 static_cast<int>((raw_seed - 1U) % 526 static_cast<unsigned int>(kMaxRandomSeed)) + 1; 527 return normalized_seed; 528} 529 530// Returns the first valid random seed after 'seed'. The behavior is 531// undefined if 'seed' is invalid. The seed after kMaxRandomSeed is 532// considered to be 1. 533inline int GetNextRandomSeed(int seed) { 534 GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed) 535 << "Invalid random seed " << seed << " - must be in [1, " 536 << kMaxRandomSeed << "]."; 537 const int next_seed = seed + 1; 538 return (next_seed > kMaxRandomSeed) ? 1 : next_seed; 539} 540 541// This class saves the values of all Google Test flags in its c'tor, and 542// restores them in its d'tor. 543class GTestFlagSaver { 544 public: 545 // The c'tor. 546 GTestFlagSaver() { 547 also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests); 548 break_on_failure_ = GTEST_FLAG(break_on_failure); 549 catch_exceptions_ = GTEST_FLAG(catch_exceptions); 550 color_ = GTEST_FLAG(color); 551 death_test_style_ = GTEST_FLAG(death_test_style); 552 death_test_use_fork_ = GTEST_FLAG(death_test_use_fork); 553 filter_ = GTEST_FLAG(filter); 554 internal_run_death_test_ = GTEST_FLAG(internal_run_death_test); 555 list_tests_ = GTEST_FLAG(list_tests); 556 output_ = GTEST_FLAG(output); 557 print_time_ = GTEST_FLAG(print_time); 558 random_seed_ = GTEST_FLAG(random_seed); 559 repeat_ = GTEST_FLAG(repeat); 560 shuffle_ = GTEST_FLAG(shuffle); 561 stack_trace_depth_ = GTEST_FLAG(stack_trace_depth); 562 throw_on_failure_ = GTEST_FLAG(throw_on_failure); 563 } 564 565 // The d'tor is not virtual. DO NOT INHERIT FROM THIS CLASS. 566 ~GTestFlagSaver() { 567 GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_; 568 GTEST_FLAG(break_on_failure) = break_on_failure_; 569 GTEST_FLAG(catch_exceptions) = catch_exceptions_; 570 GTEST_FLAG(color) = color_; 571 GTEST_FLAG(death_test_style) = death_test_style_; 572 GTEST_FLAG(death_test_use_fork) = death_test_use_fork_; 573 GTEST_FLAG(filter) = filter_; 574 GTEST_FLAG(internal_run_death_test) = internal_run_death_test_; 575 GTEST_FLAG(list_tests) = list_tests_; 576 GTEST_FLAG(output) = output_; 577 GTEST_FLAG(print_time) = print_time_; 578 GTEST_FLAG(random_seed) = random_seed_; 579 GTEST_FLAG(repeat) = repeat_; 580 GTEST_FLAG(shuffle) = shuffle_; 581 GTEST_FLAG(stack_trace_depth) = stack_trace_depth_; 582 GTEST_FLAG(throw_on_failure) = throw_on_failure_; 583 } 584 private: 585 // Fields for saving the original values of flags. 586 bool also_run_disabled_tests_; 587 bool break_on_failure_; 588 bool catch_exceptions_; 589 String color_; 590 String death_test_style_; 591 bool death_test_use_fork_; 592 String filter_; 593 String internal_run_death_test_; 594 bool list_tests_; 595 String output_; 596 bool print_time_; 597 bool pretty_; 598 internal::Int32 random_seed_; 599 internal::Int32 repeat_; 600 bool shuffle_; 601 internal::Int32 stack_trace_depth_; 602 bool throw_on_failure_; 603} GTEST_ATTRIBUTE_UNUSED_; 604 605// Converts a Unicode code point to a narrow string in UTF-8 encoding. 606// code_point parameter is of type UInt32 because wchar_t may not be 607// wide enough to contain a code point. 608// The output buffer str must containt at least 32 characters. 609// The function returns the address of the output buffer. 610// If the code_point is not a valid Unicode code point 611// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be output 612// as '(Invalid Unicode 0xXXXXXXXX)'. 613GTEST_API_ char* CodePointToUtf8(UInt32 code_point, char* str); 614 615// Converts a wide string to a narrow string in UTF-8 encoding. 616// The wide string is assumed to have the following encoding: 617// UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS) 618// UTF-32 if sizeof(wchar_t) == 4 (on Linux) 619// Parameter str points to a null-terminated wide string. 620// Parameter num_chars may additionally limit the number 621// of wchar_t characters processed. -1 is used when the entire string 622// should be processed. 623// If the string contains code points that are not valid Unicode code points 624// (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output 625// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding 626// and contains invalid UTF-16 surrogate pairs, values in those pairs 627// will be encoded as individual Unicode characters from Basic Normal Plane. 628GTEST_API_ String WideStringToUtf8(const wchar_t* str, int num_chars); 629 630// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file 631// if the variable is present. If a file already exists at this location, this 632// function will write over it. If the variable is present, but the file cannot 633// be created, prints an error and exits. 634void WriteToShardStatusFileIfNeeded(); 635 636// Checks whether sharding is enabled by examining the relevant 637// environment variable values. If the variables are present, 638// but inconsistent (e.g., shard_index >= total_shards), prints 639// an error and exits. If in_subprocess_for_death_test, sharding is 640// disabled because it must only be applied to the original test 641// process. Otherwise, we could filter out death tests we intended to execute. 642GTEST_API_ bool ShouldShard(const char* total_shards_str, 643 const char* shard_index_str, 644 bool in_subprocess_for_death_test); 645 646// Parses the environment variable var as an Int32. If it is unset, 647// returns default_val. If it is not an Int32, prints an error and 648// and aborts. 649GTEST_API_ Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val); 650 651// Given the total number of shards, the shard index, and the test id, 652// returns true iff the test should be run on this shard. The test id is 653// some arbitrary but unique non-negative integer assigned to each test 654// method. Assumes that 0 <= shard_index < total_shards. 655GTEST_API_ bool ShouldRunTestOnShard( 656 int total_shards, int shard_index, int test_id); 657 658// STL container utilities. 659 660// Returns the number of elements in the given container that satisfy 661// the given predicate. 662template <class Container, typename Predicate> 663inline int CountIf(const Container& c, Predicate predicate) { 664 return static_cast<int>(std::count_if(c.begin(), c.end(), predicate)); 665} 666 667// Applies a function/functor to each element in the container. 668template <class Container, typename Functor> 669void ForEach(const Container& c, Functor functor) { 670 std::for_each(c.begin(), c.end(), functor); 671} 672 673// Returns the i-th element of the vector, or default_value if i is not 674// in range [0, v.size()). 675template <typename E> 676inline E GetElementOr(const std::vector<E>& v, int i, E default_value) { 677 return (i < 0 || i >= static_cast<int>(v.size())) ? default_value : v[i]; 678} 679 680// Performs an in-place shuffle of a range of the vector's elements. 681// 'begin' and 'end' are element indices as an STL-style range; 682// i.e. [begin, end) are shuffled, where 'end' == size() means to 683// shuffle to the end of the vector. 684template <typename E> 685void ShuffleRange(internal::Random* random, int begin, int end, 686 std::vector<E>* v) { 687 const int size = static_cast<int>(v->size()); 688 GTEST_CHECK_(0 <= begin && begin <= size) 689 << "Invalid shuffle range start " << begin << ": must be in range [0, " 690 << size << "]."; 691 GTEST_CHECK_(begin <= end && end <= size) 692 << "Invalid shuffle range finish " << end << ": must be in range [" 693 << begin << ", " << size << "]."; 694 695 // Fisher-Yates shuffle, from 696 // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle 697 for (int range_width = end - begin; range_width >= 2; range_width--) { 698 const int last_in_range = begin + range_width - 1; 699 const int selected = begin + random->Generate(range_width); 700 std::swap((*v)[selected], (*v)[last_in_range]); 701 } 702} 703 704// Performs an in-place shuffle of the vector's elements. 705template <typename E> 706inline void Shuffle(internal::Random* random, std::vector<E>* v) { 707 ShuffleRange(random, 0, static_cast<int>(v->size()), v); 708} 709 710// A function for deleting an object. Handy for being used as a 711// functor. 712template <typename T> 713static void Delete(T* x) { 714 delete x; 715} 716 717// A predicate that checks the key of a TestProperty against a known key. 718// 719// TestPropertyKeyIs is copyable. 720class TestPropertyKeyIs { 721 public: 722 // Constructor. 723 // 724 // TestPropertyKeyIs has NO default constructor. 725 explicit TestPropertyKeyIs(const char* key) 726 : key_(key) {} 727 728 // Returns true iff the test name of test property matches on key_. 729 bool operator()(const TestProperty& test_property) const { 730 return String(test_property.key()).Compare(key_) == 0; 731 } 732 733 private: 734 String key_; 735}; 736 737class TestInfoImpl { 738 public: 739 TestInfoImpl(TestInfo* parent, const char* test_case_name, 740 const char* name, const char* test_case_comment, 741 const char* comment, TypeId fixture_class_id, 742 internal::TestFactoryBase* factory); 743 ~TestInfoImpl(); 744 745 // Returns true if this test should run. 746 bool should_run() const { return should_run_; } 747 748 // Sets the should_run member. 749 void set_should_run(bool should) { should_run_ = should; } 750 751 // Returns true if this test is disabled. Disabled tests are not run. 752 bool is_disabled() const { return is_disabled_; } 753 754 // Sets the is_disabled member. 755 void set_is_disabled(bool is) { is_disabled_ = is; } 756 757 // Returns true if this test matches the filter specified by the user. 758 bool matches_filter() const { return matches_filter_; } 759 760 // Sets the matches_filter member. 761 void set_matches_filter(bool matches) { matches_filter_ = matches; } 762 763 // Returns the test case name. 764 const char* test_case_name() const { return test_case_name_.c_str(); } 765 766 // Returns the test name. 767 const char* name() const { return name_.c_str(); } 768 769 // Returns the test case comment. 770 const char* test_case_comment() const { return test_case_comment_.c_str(); } 771 772 // Returns the test comment. 773 const char* comment() const { return comment_.c_str(); } 774 775 // Returns the ID of the test fixture class. 776 TypeId fixture_class_id() const { return fixture_class_id_; } 777 778 // Returns the test result. 779 TestResult* result() { return &result_; } 780 const TestResult* result() const { return &result_; } 781 782 // Creates the test object, runs it, records its result, and then 783 // deletes it. 784 void Run(); 785 786 // Clears the test result. 787 void ClearResult() { result_.Clear(); } 788 789 // Clears the test result in the given TestInfo object. 790 static void ClearTestResult(TestInfo * test_info) { 791 test_info->impl()->ClearResult(); 792 } 793 794 private: 795 // These fields are immutable properties of the test. 796 TestInfo* const parent_; // The owner of this object 797 const String test_case_name_; // Test case name 798 const String name_; // Test name 799 const String test_case_comment_; // Test case comment 800 const String comment_; // Test comment 801 const TypeId fixture_class_id_; // ID of the test fixture class 802 bool should_run_; // True iff this test should run 803 bool is_disabled_; // True iff this test is disabled 804 bool matches_filter_; // True if this test matches the 805 // user-specified filter. 806 internal::TestFactoryBase* const factory_; // The factory that creates 807 // the test object 808 809 // This field is mutable and needs to be reset before running the 810 // test for the second time. 811 TestResult result_; 812 813 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestInfoImpl); 814}; 815 816// Class UnitTestOptions. 817// 818// This class contains functions for processing options the user 819// specifies when running the tests. It has only static members. 820// 821// In most cases, the user can specify an option using either an 822// environment variable or a command line flag. E.g. you can set the 823// test filter using either GTEST_FILTER or --gtest_filter. If both 824// the variable and the flag are present, the latter overrides the 825// former. 826class GTEST_API_ UnitTestOptions { 827 public: 828 // Functions for processing the gtest_output flag. 829 830 // Returns the output format, or "" for normal printed output. 831 static String GetOutputFormat(); 832 833 // Returns the absolute path of the requested output file, or the 834 // default (test_detail.xml in the original working directory) if 835 // none was explicitly specified. 836 static String GetAbsolutePathToOutputFile(); 837 838 // Functions for processing the gtest_filter flag. 839 840 // Returns true iff the wildcard pattern matches the string. The 841 // first ':' or '\0' character in pattern marks the end of it. 842 // 843 // This recursive algorithm isn't very efficient, but is clear and 844 // works well enough for matching test names, which are short. 845 static bool PatternMatchesString(const char *pattern, const char *str); 846 847 // Returns true iff the user-specified filter matches the test case 848 // name and the test name. 849 static bool FilterMatchesTest(const String &test_case_name, 850 const String &test_name); 851 852#if GTEST_OS_WINDOWS 853 // Function for supporting the gtest_catch_exception flag. 854 855 // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the 856 // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise. 857 // This function is useful as an __except condition. 858 static int GTestShouldProcessSEH(DWORD exception_code); 859#endif // GTEST_OS_WINDOWS 860 861 // Returns true if "name" matches the ':' separated list of glob-style 862 // filters in "filter". 863 static bool MatchesFilter(const String& name, const char* filter); 864}; 865 866// Returns the current application's name, removing directory path if that 867// is present. Used by UnitTestOptions::GetOutputFile. 868GTEST_API_ FilePath GetCurrentExecutableName(); 869 870// The role interface for getting the OS stack trace as a string. 871class OsStackTraceGetterInterface { 872 public: 873 OsStackTraceGetterInterface() {} 874 virtual ~OsStackTraceGetterInterface() {} 875 876 // Returns the current OS stack trace as a String. Parameters: 877 // 878 // max_depth - the maximum number of stack frames to be included 879 // in the trace. 880 // skip_count - the number of top frames to be skipped; doesn't count 881 // against max_depth. 882 virtual String CurrentStackTrace(int max_depth, int skip_count) = 0; 883 884 // UponLeavingGTest() should be called immediately before Google Test calls 885 // user code. It saves some information about the current stack that 886 // CurrentStackTrace() will use to find and hide Google Test stack frames. 887 virtual void UponLeavingGTest() = 0; 888 889 private: 890 GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface); 891}; 892 893// A working implementation of the OsStackTraceGetterInterface interface. 894class OsStackTraceGetter : public OsStackTraceGetterInterface { 895 public: 896 OsStackTraceGetter() : caller_frame_(NULL) {} 897 virtual String CurrentStackTrace(int max_depth, int skip_count); 898 virtual void UponLeavingGTest(); 899 900 // This string is inserted in place of stack frames that are part of 901 // Google Test's implementation. 902 static const char* const kElidedFramesMarker; 903 904 private: 905 Mutex mutex_; // protects all internal state 906 907 // We save the stack frame below the frame that calls user code. 908 // We do this because the address of the frame immediately below 909 // the user code changes between the call to UponLeavingGTest() 910 // and any calls to CurrentStackTrace() from within the user code. 911 void* caller_frame_; 912 913 GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter); 914}; 915 916// Information about a Google Test trace point. 917struct TraceInfo { 918 const char* file; 919 int line; 920 String message; 921}; 922 923// This is the default global test part result reporter used in UnitTestImpl. 924// This class should only be used by UnitTestImpl. 925class DefaultGlobalTestPartResultReporter 926 : public TestPartResultReporterInterface { 927 public: 928 explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test); 929 // Implements the TestPartResultReporterInterface. Reports the test part 930 // result in the current test. 931 virtual void ReportTestPartResult(const TestPartResult& result); 932 933 private: 934 UnitTestImpl* const unit_test_; 935 936 GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter); 937}; 938 939// This is the default per thread test part result reporter used in 940// UnitTestImpl. This class should only be used by UnitTestImpl. 941class DefaultPerThreadTestPartResultReporter 942 : public TestPartResultReporterInterface { 943 public: 944 explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test); 945 // Implements the TestPartResultReporterInterface. The implementation just 946 // delegates to the current global test part result reporter of *unit_test_. 947 virtual void ReportTestPartResult(const TestPartResult& result); 948 949 private: 950 UnitTestImpl* const unit_test_; 951 952 GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter); 953}; 954 955// The private implementation of the UnitTest class. We don't protect 956// the methods under a mutex, as this class is not accessible by a 957// user and the UnitTest class that delegates work to this class does 958// proper locking. 959class GTEST_API_ UnitTestImpl { 960 public: 961 explicit UnitTestImpl(UnitTest* parent); 962 virtual ~UnitTestImpl(); 963 964 // There are two different ways to register your own TestPartResultReporter. 965 // You can register your own repoter to listen either only for test results 966 // from the current thread or for results from all threads. 967 // By default, each per-thread test result repoter just passes a new 968 // TestPartResult to the global test result reporter, which registers the 969 // test part result for the currently running test. 970 971 // Returns the global test part result reporter. 972 TestPartResultReporterInterface* GetGlobalTestPartResultReporter(); 973 974 // Sets the global test part result reporter. 975 void SetGlobalTestPartResultReporter( 976 TestPartResultReporterInterface* reporter); 977 978 // Returns the test part result reporter for the current thread. 979 TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread(); 980 981 // Sets the test part result reporter for the current thread. 982 void SetTestPartResultReporterForCurrentThread( 983 TestPartResultReporterInterface* reporter); 984 985 // Gets the number of successful test cases. 986 int successful_test_case_count() const; 987 988 // Gets the number of failed test cases. 989 int failed_test_case_count() const; 990 991 // Gets the number of all test cases. 992 int total_test_case_count() const; 993 994 // Gets the number of all test cases that contain at least one test 995 // that should run. 996 int test_case_to_run_count() const; 997 998 // Gets the number of successful tests. 999 int successful_test_count() const; 1000 1001 // Gets the number of failed tests. 1002 int failed_test_count() const; 1003 1004 // Gets the number of disabled tests. 1005 int disabled_test_count() const; 1006 1007 // Gets the number of all tests. 1008 int total_test_count() const; 1009 1010 // Gets the number of tests that should run. 1011 int test_to_run_count() const; 1012 1013 // Gets the elapsed time, in milliseconds. 1014 TimeInMillis elapsed_time() const { return elapsed_time_; } 1015 1016 // Returns true iff the unit test passed (i.e. all test cases passed). 1017 bool Passed() const { return !Failed(); } 1018 1019 // Returns true iff the unit test failed (i.e. some test case failed 1020 // or something outside of all tests failed). 1021 bool Failed() const { 1022 return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed(); 1023 } 1024 1025 // Gets the i-th test case among all the test cases. i can range from 0 to 1026 // total_test_case_count() - 1. If i is not in that range, returns NULL. 1027 const TestCase* GetTestCase(int i) const { 1028 const int index = GetElementOr(test_case_indices_, i, -1); 1029 return index < 0 ? NULL : test_cases_[i]; 1030 } 1031 1032 // Gets the i-th test case among all the test cases. i can range from 0 to 1033 // total_test_case_count() - 1. If i is not in that range, returns NULL. 1034 TestCase* GetMutableTestCase(int i) { 1035 const int index = GetElementOr(test_case_indices_, i, -1); 1036 return index < 0 ? NULL : test_cases_[index]; 1037 } 1038 1039 // Provides access to the event listener list. 1040 TestEventListeners* listeners() { return &listeners_; } 1041 1042 // Returns the TestResult for the test that's currently running, or 1043 // the TestResult for the ad hoc test if no test is running. 1044 TestResult* current_test_result(); 1045 1046 // Returns the TestResult for the ad hoc test. 1047 const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; } 1048 1049 // Sets the OS stack trace getter. 1050 // 1051 // Does nothing if the input and the current OS stack trace getter 1052 // are the same; otherwise, deletes the old getter and makes the 1053 // input the current getter. 1054 void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter); 1055 1056 // Returns the current OS stack trace getter if it is not NULL; 1057 // otherwise, creates an OsStackTraceGetter, makes it the current 1058 // getter, and returns it. 1059 OsStackTraceGetterInterface* os_stack_trace_getter(); 1060 1061 // Returns the current OS stack trace as a String. 1062 // 1063 // The maximum number of stack frames to be included is specified by 1064 // the gtest_stack_trace_depth flag. The skip_count parameter 1065 // specifies the number of top frames to be skipped, which doesn't 1066 // count against the number of frames to be included. 1067 // 1068 // For example, if Foo() calls Bar(), which in turn calls 1069 // CurrentOsStackTraceExceptTop(1), Foo() will be included in the 1070 // trace but Bar() and CurrentOsStackTraceExceptTop() won't. 1071 String CurrentOsStackTraceExceptTop(int skip_count); 1072 1073 // Finds and returns a TestCase with the given name. If one doesn't 1074 // exist, creates one and returns it. 1075 // 1076 // Arguments: 1077 // 1078 // test_case_name: name of the test case 1079 // set_up_tc: pointer to the function that sets up the test case 1080 // tear_down_tc: pointer to the function that tears down the test case 1081 TestCase* GetTestCase(const char* test_case_name, 1082 const char* comment, 1083 Test::SetUpTestCaseFunc set_up_tc, 1084 Test::TearDownTestCaseFunc tear_down_tc); 1085 1086 // Adds a TestInfo to the unit test. 1087 // 1088 // Arguments: 1089 // 1090 // set_up_tc: pointer to the function that sets up the test case 1091 // tear_down_tc: pointer to the function that tears down the test case 1092 // test_info: the TestInfo object 1093 void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc, 1094 Test::TearDownTestCaseFunc tear_down_tc, 1095 TestInfo * test_info) { 1096 // In order to support thread-safe death tests, we need to 1097 // remember the original working directory when the test program 1098 // was first invoked. We cannot do this in RUN_ALL_TESTS(), as 1099 // the user may have changed the current directory before calling 1100 // RUN_ALL_TESTS(). Therefore we capture the current directory in 1101 // AddTestInfo(), which is called to register a TEST or TEST_F 1102 // before main() is reached. 1103 if (original_working_dir_.IsEmpty()) { 1104 original_working_dir_.Set(FilePath::GetCurrentDir()); 1105 GTEST_CHECK_(!original_working_dir_.IsEmpty()) 1106 << "Failed to get the current working directory."; 1107 } 1108 1109 GetTestCase(test_info->test_case_name(), 1110 test_info->test_case_comment(), 1111 set_up_tc, 1112 tear_down_tc)->AddTestInfo(test_info); 1113 } 1114 1115#if GTEST_HAS_PARAM_TEST 1116 // Returns ParameterizedTestCaseRegistry object used to keep track of 1117 // value-parameterized tests and instantiate and register them. 1118 internal::ParameterizedTestCaseRegistry& parameterized_test_registry() { 1119 return parameterized_test_registry_; 1120 } 1121#endif // GTEST_HAS_PARAM_TEST 1122 1123 // Sets the TestCase object for the test that's currently running. 1124 void set_current_test_case(TestCase* a_current_test_case) { 1125 current_test_case_ = a_current_test_case; 1126 } 1127 1128 // Sets the TestInfo object for the test that's currently running. If 1129 // current_test_info is NULL, the assertion results will be stored in 1130 // ad_hoc_test_result_. 1131 void set_current_test_info(TestInfo* a_current_test_info) { 1132 current_test_info_ = a_current_test_info; 1133 } 1134 1135 // Registers all parameterized tests defined using TEST_P and 1136 // INSTANTIATE_TEST_P, creating regular tests for each test/parameter 1137 // combination. This method can be called more then once; it has 1138 // guards protecting from registering the tests more then once. 1139 // If value-parameterized tests are disabled, RegisterParameterizedTests 1140 // is present but does nothing. 1141 void RegisterParameterizedTests(); 1142 1143 // Runs all tests in this UnitTest object, prints the result, and 1144 // returns 0 if all tests are successful, or 1 otherwise. If any 1145 // exception is thrown during a test on Windows, this test is 1146 // considered to be failed, but the rest of the tests will still be 1147 // run. (We disable exceptions on Linux and Mac OS X, so the issue 1148 // doesn't apply there.) 1149 int RunAllTests(); 1150 1151 // Clears the results of all tests, including the ad hoc test. 1152 void ClearResult() { 1153 ForEach(test_cases_, TestCase::ClearTestCaseResult); 1154 ad_hoc_test_result_.Clear(); 1155 } 1156 1157 enum ReactionToSharding { 1158 HONOR_SHARDING_PROTOCOL, 1159 IGNORE_SHARDING_PROTOCOL 1160 }; 1161 1162 // Matches the full name of each test against the user-specified 1163 // filter to decide whether the test should run, then records the 1164 // result in each TestCase and TestInfo object. 1165 // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests 1166 // based on sharding variables in the environment. 1167 // Returns the number of tests that should run. 1168 int FilterTests(ReactionToSharding shard_tests); 1169 1170 // Prints the names of the tests matching the user-specified filter flag. 1171 void ListTestsMatchingFilter(); 1172 1173 const TestCase* current_test_case() const { return current_test_case_; } 1174 TestInfo* current_test_info() { return current_test_info_; } 1175 const TestInfo* current_test_info() const { return current_test_info_; } 1176 1177 // Returns the vector of environments that need to be set-up/torn-down 1178 // before/after the tests are run. 1179 std::vector<Environment*>& environments() { return environments_; } 1180 1181 // Getters for the per-thread Google Test trace stack. 1182 std::vector<TraceInfo>& gtest_trace_stack() { 1183 return *(gtest_trace_stack_.pointer()); 1184 } 1185 const std::vector<TraceInfo>& gtest_trace_stack() const { 1186 return gtest_trace_stack_.get(); 1187 } 1188 1189#if GTEST_HAS_DEATH_TEST 1190 void InitDeathTestSubprocessControlInfo() { 1191 internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag()); 1192 } 1193 // Returns a pointer to the parsed --gtest_internal_run_death_test 1194 // flag, or NULL if that flag was not specified. 1195 // This information is useful only in a death test child process. 1196 // Must not be called before a call to InitGoogleTest. 1197 const InternalRunDeathTestFlag* internal_run_death_test_flag() const { 1198 return internal_run_death_test_flag_.get(); 1199 } 1200 1201 // Returns a pointer to the current death test factory. 1202 internal::DeathTestFactory* death_test_factory() { 1203 return death_test_factory_.get(); 1204 } 1205 1206 void SuppressTestEventsIfInSubprocess(); 1207 1208 friend class ReplaceDeathTestFactory; 1209#endif // GTEST_HAS_DEATH_TEST 1210 1211 // Initializes the event listener performing XML output as specified by 1212 // UnitTestOptions. Must not be called before InitGoogleTest. 1213 void ConfigureXmlOutput(); 1214 1215 // Performs initialization dependent upon flag values obtained in 1216 // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to 1217 // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest 1218 // this function is also called from RunAllTests. Since this function can be 1219 // called more than once, it has to be idempotent. 1220 void PostFlagParsingInit(); 1221 1222 // Gets the random seed used at the start of the current test iteration. 1223 int random_seed() const { return random_seed_; } 1224 1225 // Gets the random number generator. 1226 internal::Random* random() { return &random_; } 1227 1228 // Shuffles all test cases, and the tests within each test case, 1229 // making sure that death tests are still run first. 1230 void ShuffleTests(); 1231 1232 // Restores the test cases and tests to their order before the first shuffle. 1233 void UnshuffleTests(); 1234 1235 private: 1236 friend class ::testing::UnitTest; 1237 1238 // The UnitTest object that owns this implementation object. 1239 UnitTest* const parent_; 1240 1241 // The working directory when the first TEST() or TEST_F() was 1242 // executed. 1243 internal::FilePath original_working_dir_; 1244 1245 // The default test part result reporters. 1246 DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_; 1247 DefaultPerThreadTestPartResultReporter 1248 default_per_thread_test_part_result_reporter_; 1249 1250 // Points to (but doesn't own) the global test part result reporter. 1251 TestPartResultReporterInterface* global_test_part_result_repoter_; 1252 1253 // Protects read and write access to global_test_part_result_reporter_. 1254 internal::Mutex global_test_part_result_reporter_mutex_; 1255 1256 // Points to (but doesn't own) the per-thread test part result reporter. 1257 internal::ThreadLocal<TestPartResultReporterInterface*> 1258 per_thread_test_part_result_reporter_; 1259 1260 // The vector of environments that need to be set-up/torn-down 1261 // before/after the tests are run. 1262 std::vector<Environment*> environments_; 1263 1264 // The vector of TestCases in their original order. It owns the 1265 // elements in the vector. 1266 std::vector<TestCase*> test_cases_; 1267 1268 // Provides a level of indirection for the test case list to allow 1269 // easy shuffling and restoring the test case order. The i-th 1270 // element of this vector is the index of the i-th test case in the 1271 // shuffled order. 1272 std::vector<int> test_case_indices_; 1273 1274#if GTEST_HAS_PARAM_TEST 1275 // ParameterizedTestRegistry object used to register value-parameterized 1276 // tests. 1277 internal::ParameterizedTestCaseRegistry parameterized_test_registry_; 1278 1279 // Indicates whether RegisterParameterizedTests() has been called already. 1280 bool parameterized_tests_registered_; 1281#endif // GTEST_HAS_PARAM_TEST 1282 1283 // Index of the last death test case registered. Initially -1. 1284 int last_death_test_case_; 1285 1286 // This points to the TestCase for the currently running test. It 1287 // changes as Google Test goes through one test case after another. 1288 // When no test is running, this is set to NULL and Google Test 1289 // stores assertion results in ad_hoc_test_result_. Initially NULL. 1290 TestCase* current_test_case_; 1291 1292 // This points to the TestInfo for the currently running test. It 1293 // changes as Google Test goes through one test after another. When 1294 // no test is running, this is set to NULL and Google Test stores 1295 // assertion results in ad_hoc_test_result_. Initially NULL. 1296 TestInfo* current_test_info_; 1297 1298 // Normally, a user only writes assertions inside a TEST or TEST_F, 1299 // or inside a function called by a TEST or TEST_F. Since Google 1300 // Test keeps track of which test is current running, it can 1301 // associate such an assertion with the test it belongs to. 1302 // 1303 // If an assertion is encountered when no TEST or TEST_F is running, 1304 // Google Test attributes the assertion result to an imaginary "ad hoc" 1305 // test, and records the result in ad_hoc_test_result_. 1306 TestResult ad_hoc_test_result_; 1307 1308 // The list of event listeners that can be used to track events inside 1309 // Google Test. 1310 TestEventListeners listeners_; 1311 1312 // The OS stack trace getter. Will be deleted when the UnitTest 1313 // object is destructed. By default, an OsStackTraceGetter is used, 1314 // but the user can set this field to use a custom getter if that is 1315 // desired. 1316 OsStackTraceGetterInterface* os_stack_trace_getter_; 1317 1318 // True iff PostFlagParsingInit() has been called. 1319 bool post_flag_parse_init_performed_; 1320 1321 // The random number seed used at the beginning of the test run. 1322 int random_seed_; 1323 1324 // Our random number generator. 1325 internal::Random random_; 1326 1327 // How long the test took to run, in milliseconds. 1328 TimeInMillis elapsed_time_; 1329 1330#if GTEST_HAS_DEATH_TEST 1331 // The decomposed components of the gtest_internal_run_death_test flag, 1332 // parsed when RUN_ALL_TESTS is called. 1333 internal::scoped_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_; 1334 internal::scoped_ptr<internal::DeathTestFactory> death_test_factory_; 1335#endif // GTEST_HAS_DEATH_TEST 1336 1337 // A per-thread stack of traces created by the SCOPED_TRACE() macro. 1338 internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_; 1339 1340 GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl); 1341}; // class UnitTestImpl 1342 1343// Convenience function for accessing the global UnitTest 1344// implementation object. 1345inline UnitTestImpl* GetUnitTestImpl() { 1346 return UnitTest::GetInstance()->impl(); 1347} 1348 1349// Internal helper functions for implementing the simple regular 1350// expression matcher. 1351GTEST_API_ bool IsInSet(char ch, const char* str); 1352GTEST_API_ bool IsDigit(char ch); 1353GTEST_API_ bool IsPunct(char ch); 1354GTEST_API_ bool IsRepeat(char ch); 1355GTEST_API_ bool IsWhiteSpace(char ch); 1356GTEST_API_ bool IsWordChar(char ch); 1357GTEST_API_ bool IsValidEscape(char ch); 1358GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch); 1359GTEST_API_ bool ValidateRegex(const char* regex); 1360GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str); 1361GTEST_API_ bool MatchRepetitionAndRegexAtHead( 1362 bool escaped, char ch, char repeat, const char* regex, const char* str); 1363GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str); 1364 1365// Parses the command line for Google Test flags, without initializing 1366// other parts of Google Test. 1367GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv); 1368GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv); 1369 1370#if GTEST_HAS_DEATH_TEST 1371 1372// Returns the message describing the last system error, regardless of the 1373// platform. 1374String GetLastErrnoDescription(); 1375 1376#if GTEST_OS_WINDOWS 1377// Provides leak-safe Windows kernel handle ownership. 1378class AutoHandle { 1379 public: 1380 AutoHandle() : handle_(INVALID_HANDLE_VALUE) {} 1381 explicit AutoHandle(HANDLE handle) : handle_(handle) {} 1382 1383 ~AutoHandle() { Reset(); } 1384 1385 HANDLE Get() const { return handle_; } 1386 void Reset() { Reset(INVALID_HANDLE_VALUE); } 1387 void Reset(HANDLE handle) { 1388 if (handle != handle_) { 1389 if (handle_ != INVALID_HANDLE_VALUE) 1390 ::CloseHandle(handle_); 1391 handle_ = handle; 1392 } 1393 } 1394 1395 private: 1396 HANDLE handle_; 1397 1398 GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle); 1399}; 1400#endif // GTEST_OS_WINDOWS 1401 1402// Attempts to parse a string into a positive integer pointed to by the 1403// number parameter. Returns true if that is possible. 1404// GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use 1405// it here. 1406template <typename Integer> 1407bool ParseNaturalNumber(const ::std::string& str, Integer* number) { 1408 // Fail fast if the given string does not begin with a digit; 1409 // this bypasses strtoXXX's "optional leading whitespace and plus 1410 // or minus sign" semantics, which are undesirable here. 1411 if (str.empty() || !isdigit(str[0])) { 1412 return false; 1413 } 1414 errno = 0; 1415 1416 char* end; 1417 // BiggestConvertible is the largest integer type that system-provided 1418 // string-to-number conversion routines can return. 1419#if GTEST_OS_WINDOWS && !defined(__GNUC__) 1420 // MSVC and C++ Builder define __int64 instead of the standard long long. 1421 typedef unsigned __int64 BiggestConvertible; 1422 const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10); 1423#else 1424 typedef unsigned long long BiggestConvertible; // NOLINT 1425 const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10); 1426#endif // GTEST_OS_WINDOWS && !defined(__GNUC__) 1427 const bool parse_success = *end == '\0' && errno == 0; 1428 1429 // TODO(vladl@google.com): Convert this to compile time assertion when it is 1430 // available. 1431 GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed)); 1432 1433 const Integer result = static_cast<Integer>(parsed); 1434 if (parse_success && static_cast<BiggestConvertible>(result) == parsed) { 1435 *number = result; 1436 return true; 1437 } 1438 return false; 1439} 1440#endif // GTEST_HAS_DEATH_TEST 1441 1442// TestResult contains some private methods that should be hidden from 1443// Google Test user but are required for testing. This class allow our tests 1444// to access them. 1445// 1446// This class is supplied only for the purpose of testing Google Test's own 1447// constructs. Do not use it in user tests, either directly or indirectly. 1448class TestResultAccessor { 1449 public: 1450 static void RecordProperty(TestResult* test_result, 1451 const TestProperty& property) { 1452 test_result->RecordProperty(property); 1453 } 1454 1455 static void ClearTestPartResults(TestResult* test_result) { 1456 test_result->ClearTestPartResults(); 1457 } 1458 1459 static const std::vector<testing::TestPartResult>& test_part_results( 1460 const TestResult& test_result) { 1461 return test_result.test_part_results(); 1462 } 1463}; 1464 1465} // namespace internal 1466} // namespace testing 1467 1468#endif // GTEST_SRC_GTEST_INTERNAL_INL_H_ 1469#undef GTEST_IMPLEMENTATION_ 1470 1471#if GTEST_OS_WINDOWS 1472#define vsnprintf _vsnprintf 1473#endif // GTEST_OS_WINDOWS 1474 1475namespace testing { 1476 1477using internal::CountIf; 1478using internal::ForEach; 1479using internal::GetElementOr; 1480using internal::Shuffle; 1481 1482// Constants. 1483 1484// A test whose test case name or test name matches this filter is 1485// disabled and not run. 1486static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*"; 1487 1488// A test case whose name matches this filter is considered a death 1489// test case and will be run before test cases whose name doesn't 1490// match this filter. 1491static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*"; 1492 1493// A test filter that matches everything. 1494static const char kUniversalFilter[] = "*"; 1495 1496// The default output file for XML output. 1497static const char kDefaultOutputFile[] = "test_detail.xml"; 1498 1499// The environment variable name for the test shard index. 1500static const char kTestShardIndex[] = "GTEST_SHARD_INDEX"; 1501// The environment variable name for the total number of test shards. 1502static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS"; 1503// The environment variable name for the test shard status file. 1504static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE"; 1505 1506namespace internal { 1507 1508// The text used in failure messages to indicate the start of the 1509// stack trace. 1510const char kStackTraceMarker[] = "\nStack trace:\n"; 1511 1512// g_help_flag is true iff the --help flag or an equivalent form is 1513// specified on the command line. 1514bool g_help_flag = false; 1515 1516} // namespace internal 1517 1518GTEST_DEFINE_bool_( 1519 also_run_disabled_tests, 1520 internal::BoolFromGTestEnv("also_run_disabled_tests", false), 1521 "Run disabled tests too, in addition to the tests normally being run."); 1522 1523GTEST_DEFINE_bool_( 1524 break_on_failure, 1525 internal::BoolFromGTestEnv("break_on_failure", false), 1526 "True iff a failed assertion should be a debugger break-point."); 1527 1528GTEST_DEFINE_bool_( 1529 catch_exceptions, 1530 internal::BoolFromGTestEnv("catch_exceptions", false), 1531 "True iff " GTEST_NAME_ 1532 " should catch exceptions and treat them as test failures."); 1533 1534GTEST_DEFINE_string_( 1535 color, 1536 internal::StringFromGTestEnv("color", "auto"), 1537 "Whether to use colors in the output. Valid values: yes, no, " 1538 "and auto. 'auto' means to use colors if the output is " 1539 "being sent to a terminal and the TERM environment variable " 1540 "is set to xterm, xterm-color, xterm-256color, linux or cygwin."); 1541 1542GTEST_DEFINE_string_( 1543 filter, 1544 internal::StringFromGTestEnv("filter", kUniversalFilter), 1545 "A colon-separated list of glob (not regex) patterns " 1546 "for filtering the tests to run, optionally followed by a " 1547 "'-' and a : separated list of negative patterns (tests to " 1548 "exclude). A test is run if it matches one of the positive " 1549 "patterns and does not match any of the negative patterns."); 1550 1551GTEST_DEFINE_bool_(list_tests, false, 1552 "List all tests without running them."); 1553 1554GTEST_DEFINE_string_( 1555 output, 1556 internal::StringFromGTestEnv("output", ""), 1557 "A format (currently must be \"xml\"), optionally followed " 1558 "by a colon and an output file name or directory. A directory " 1559 "is indicated by a trailing pathname separator. " 1560 "Examples: \"xml:filename.xml\", \"xml::directoryname/\". " 1561 "If a directory is specified, output files will be created " 1562 "within that directory, with file-names based on the test " 1563 "executable's name and, if necessary, made unique by adding " 1564 "digits."); 1565 1566GTEST_DEFINE_bool_( 1567 print_time, 1568 internal::BoolFromGTestEnv("print_time", true), 1569 "True iff " GTEST_NAME_ 1570 " should display elapsed time in text output."); 1571 1572GTEST_DEFINE_int32_( 1573 random_seed, 1574 internal::Int32FromGTestEnv("random_seed", 0), 1575 "Random number seed to use when shuffling test orders. Must be in range " 1576 "[1, 99999], or 0 to use a seed based on the current time."); 1577 1578GTEST_DEFINE_int32_( 1579 repeat, 1580 internal::Int32FromGTestEnv("repeat", 1), 1581 "How many times to repeat each test. Specify a negative number " 1582 "for repeating forever. Useful for shaking out flaky tests."); 1583 1584GTEST_DEFINE_bool_( 1585 show_internal_stack_frames, false, 1586 "True iff " GTEST_NAME_ " should include internal stack frames when " 1587 "printing test failure stack traces."); 1588 1589GTEST_DEFINE_bool_( 1590 shuffle, 1591 internal::BoolFromGTestEnv("shuffle", false), 1592 "True iff " GTEST_NAME_ 1593 " should randomize tests' order on every run."); 1594 1595GTEST_DEFINE_int32_( 1596 stack_trace_depth, 1597 internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth), 1598 "The maximum number of stack frames to print when an " 1599 "assertion fails. The valid range is 0 through 100, inclusive."); 1600 1601GTEST_DEFINE_bool_( 1602 throw_on_failure, 1603 internal::BoolFromGTestEnv("throw_on_failure", false), 1604 "When this flag is specified, a failed assertion will throw an exception " 1605 "if exceptions are enabled or exit the program with a non-zero code " 1606 "otherwise."); 1607 1608namespace internal { 1609 1610// Generates a random number from [0, range), using a Linear 1611// Congruential Generator (LCG). Crashes if 'range' is 0 or greater 1612// than kMaxRange. 1613UInt32 Random::Generate(UInt32 range) { 1614 // These constants are the same as are used in glibc's rand(3). 1615 state_ = (1103515245U*state_ + 12345U) % kMaxRange; 1616 1617 GTEST_CHECK_(range > 0) 1618 << "Cannot generate a number in the range [0, 0)."; 1619 GTEST_CHECK_(range <= kMaxRange) 1620 << "Generation of a number in [0, " << range << ") was requested, " 1621 << "but this can only generate numbers in [0, " << kMaxRange << ")."; 1622 1623 // Converting via modulus introduces a bit of downward bias, but 1624 // it's simple, and a linear congruential generator isn't too good 1625 // to begin with. 1626 return state_ % range; 1627} 1628 1629// GTestIsInitialized() returns true iff the user has initialized 1630// Google Test. Useful for catching the user mistake of not initializing 1631// Google Test before calling RUN_ALL_TESTS(). 1632// 1633// A user must call testing::InitGoogleTest() to initialize Google 1634// Test. g_init_gtest_count is set to the number of times 1635// InitGoogleTest() has been called. We don't protect this variable 1636// under a mutex as it is only accessed in the main thread. 1637int g_init_gtest_count = 0; 1638static bool GTestIsInitialized() { return g_init_gtest_count != 0; } 1639 1640// Iterates over a vector of TestCases, keeping a running sum of the 1641// results of calling a given int-returning method on each. 1642// Returns the sum. 1643static int SumOverTestCaseList(const std::vector<TestCase*>& case_list, 1644 int (TestCase::*method)() const) { 1645 int sum = 0; 1646 for (size_t i = 0; i < case_list.size(); i++) { 1647 sum += (case_list[i]->*method)(); 1648 } 1649 return sum; 1650} 1651 1652// Returns true iff the test case passed. 1653static bool TestCasePassed(const TestCase* test_case) { 1654 return test_case->should_run() && test_case->Passed(); 1655} 1656 1657// Returns true iff the test case failed. 1658static bool TestCaseFailed(const TestCase* test_case) { 1659 return test_case->should_run() && test_case->Failed(); 1660} 1661 1662// Returns true iff test_case contains at least one test that should 1663// run. 1664static bool ShouldRunTestCase(const TestCase* test_case) { 1665 return test_case->should_run(); 1666} 1667 1668// AssertHelper constructor. 1669AssertHelper::AssertHelper(TestPartResult::Type type, 1670 const char* file, 1671 int line, 1672 const char* message) 1673 : data_(new AssertHelperData(type, file, line, message)) { 1674} 1675 1676AssertHelper::~AssertHelper() { 1677 delete data_; 1678} 1679 1680// Message assignment, for assertion streaming support. 1681void AssertHelper::operator=(const Message& message) const { 1682 UnitTest::GetInstance()-> 1683 AddTestPartResult(data_->type, data_->file, data_->line, 1684 AppendUserMessage(data_->message, message), 1685 UnitTest::GetInstance()->impl() 1686 ->CurrentOsStackTraceExceptTop(1) 1687 // Skips the stack frame for this function itself. 1688 ); // NOLINT 1689} 1690 1691// Mutex for linked pointers. 1692GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex); 1693 1694// Application pathname gotten in InitGoogleTest. 1695String g_executable_path; 1696 1697// Returns the current application's name, removing directory path if that 1698// is present. 1699FilePath GetCurrentExecutableName() { 1700 FilePath result; 1701 1702#if GTEST_OS_WINDOWS 1703 result.Set(FilePath(g_executable_path).RemoveExtension("exe")); 1704#else 1705 result.Set(FilePath(g_executable_path)); 1706#endif // GTEST_OS_WINDOWS 1707 1708 return result.RemoveDirectoryName(); 1709} 1710 1711// Functions for processing the gtest_output flag. 1712 1713// Returns the output format, or "" for normal printed output. 1714String UnitTestOptions::GetOutputFormat() { 1715 const char* const gtest_output_flag = GTEST_FLAG(output).c_str(); 1716 if (gtest_output_flag == NULL) return String(""); 1717 1718 const char* const colon = strchr(gtest_output_flag, ':'); 1719 return (colon == NULL) ? 1720 String(gtest_output_flag) : 1721 String(gtest_output_flag, colon - gtest_output_flag); 1722} 1723 1724// Returns the name of the requested output file, or the default if none 1725// was explicitly specified. 1726String UnitTestOptions::GetAbsolutePathToOutputFile() { 1727 const char* const gtest_output_flag = GTEST_FLAG(output).c_str(); 1728 if (gtest_output_flag == NULL) 1729 return String(""); 1730 1731 const char* const colon = strchr(gtest_output_flag, ':'); 1732 if (colon == NULL) 1733 return String(internal::FilePath::ConcatPaths( 1734 internal::FilePath( 1735 UnitTest::GetInstance()->original_working_dir()), 1736 internal::FilePath(kDefaultOutputFile)).ToString() ); 1737 1738 internal::FilePath output_name(colon + 1); 1739 if (!output_name.IsAbsolutePath()) 1740 // TODO(wan@google.com): on Windows \some\path is not an absolute 1741 // path (as its meaning depends on the current drive), yet the 1742 // following logic for turning it into an absolute path is wrong. 1743 // Fix it. 1744 output_name = internal::FilePath::ConcatPaths( 1745 internal::FilePath(UnitTest::GetInstance()->original_working_dir()), 1746 internal::FilePath(colon + 1)); 1747 1748 if (!output_name.IsDirectory()) 1749 return output_name.ToString(); 1750 1751 internal::FilePath result(internal::FilePath::GenerateUniqueFileName( 1752 output_name, internal::GetCurrentExecutableName(), 1753 GetOutputFormat().c_str())); 1754 return result.ToString(); 1755} 1756 1757// Returns true iff the wildcard pattern matches the string. The 1758// first ':' or '\0' character in pattern marks the end of it. 1759// 1760// This recursive algorithm isn't very efficient, but is clear and 1761// works well enough for matching test names, which are short. 1762bool UnitTestOptions::PatternMatchesString(const char *pattern, 1763 const char *str) { 1764 switch (*pattern) { 1765 case '\0': 1766 case ':': // Either ':' or '\0' marks the end of the pattern. 1767 return *str == '\0'; 1768 case '?': // Matches any single character. 1769 return *str != '\0' && PatternMatchesString(pattern + 1, str + 1); 1770 case '*': // Matches any string (possibly empty) of characters. 1771 return (*str != '\0' && PatternMatchesString(pattern, str + 1)) || 1772 PatternMatchesString(pattern + 1, str); 1773 default: // Non-special character. Matches itself. 1774 return *pattern == *str && 1775 PatternMatchesString(pattern + 1, str + 1); 1776 } 1777} 1778 1779bool UnitTestOptions::MatchesFilter(const String& name, const char* filter) { 1780 const char *cur_pattern = filter; 1781 for (;;) { 1782 if (PatternMatchesString(cur_pattern, name.c_str())) { 1783 return true; 1784 } 1785 1786 // Finds the next pattern in the filter. 1787 cur_pattern = strchr(cur_pattern, ':'); 1788 1789 // Returns if no more pattern can be found. 1790 if (cur_pattern == NULL) { 1791 return false; 1792 } 1793 1794 // Skips the pattern separater (the ':' character). 1795 cur_pattern++; 1796 } 1797} 1798 1799// TODO(keithray): move String function implementations to gtest-string.cc. 1800 1801// Returns true iff the user-specified filter matches the test case 1802// name and the test name. 1803bool UnitTestOptions::FilterMatchesTest(const String &test_case_name, 1804 const String &test_name) { 1805 const String& full_name = String::Format("%s.%s", 1806 test_case_name.c_str(), 1807 test_name.c_str()); 1808 1809 // Split --gtest_filter at '-', if there is one, to separate into 1810 // positive filter and negative filter portions 1811 const char* const p = GTEST_FLAG(filter).c_str(); 1812 const char* const dash = strchr(p, '-'); 1813 String positive; 1814 String negative; 1815 if (dash == NULL) { 1816 positive = GTEST_FLAG(filter).c_str(); // Whole string is a positive filter 1817 negative = String(""); 1818 } else { 1819 positive = String(p, dash - p); // Everything up to the dash 1820 negative = String(dash+1); // Everything after the dash 1821 if (positive.empty()) { 1822 // Treat '-test1' as the same as '*-test1' 1823 positive = kUniversalFilter; 1824 } 1825 } 1826 1827 // A filter is a colon-separated list of patterns. It matches a 1828 // test if any pattern in it matches the test. 1829 return (MatchesFilter(full_name, positive.c_str()) && 1830 !MatchesFilter(full_name, negative.c_str())); 1831} 1832 1833#if GTEST_OS_WINDOWS 1834// Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the 1835// given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise. 1836// This function is useful as an __except condition. 1837int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) { 1838 // Google Test should handle an exception if: 1839 // 1. the user wants it to, AND 1840 // 2. this is not a breakpoint exception. 1841 return (GTEST_FLAG(catch_exceptions) && 1842 exception_code != EXCEPTION_BREAKPOINT) ? 1843 EXCEPTION_EXECUTE_HANDLER : 1844 EXCEPTION_CONTINUE_SEARCH; 1845} 1846#endif // GTEST_OS_WINDOWS 1847 1848} // namespace internal 1849 1850// The c'tor sets this object as the test part result reporter used by 1851// Google Test. The 'result' parameter specifies where to report the 1852// results. Intercepts only failures from the current thread. 1853ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter( 1854 TestPartResultArray* result) 1855 : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD), 1856 result_(result) { 1857 Init(); 1858} 1859 1860// The c'tor sets this object as the test part result reporter used by 1861// Google Test. The 'result' parameter specifies where to report the 1862// results. 1863ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter( 1864 InterceptMode intercept_mode, TestPartResultArray* result) 1865 : intercept_mode_(intercept_mode), 1866 result_(result) { 1867 Init(); 1868} 1869 1870void ScopedFakeTestPartResultReporter::Init() { 1871 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); 1872 if (intercept_mode_ == INTERCEPT_ALL_THREADS) { 1873 old_reporter_ = impl->GetGlobalTestPartResultReporter(); 1874 impl->SetGlobalTestPartResultReporter(this); 1875 } else { 1876 old_reporter_ = impl->GetTestPartResultReporterForCurrentThread(); 1877 impl->SetTestPartResultReporterForCurrentThread(this); 1878 } 1879} 1880 1881// The d'tor restores the test part result reporter used by Google Test 1882// before. 1883ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() { 1884 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); 1885 if (intercept_mode_ == INTERCEPT_ALL_THREADS) { 1886 impl->SetGlobalTestPartResultReporter(old_reporter_); 1887 } else { 1888 impl->SetTestPartResultReporterForCurrentThread(old_reporter_); 1889 } 1890} 1891 1892// Increments the test part result count and remembers the result. 1893// This method is from the TestPartResultReporterInterface interface. 1894void ScopedFakeTestPartResultReporter::ReportTestPartResult( 1895 const TestPartResult& result) { 1896 result_->Append(result); 1897} 1898 1899namespace internal { 1900 1901// Returns the type ID of ::testing::Test. We should always call this 1902// instead of GetTypeId< ::testing::Test>() to get the type ID of 1903// testing::Test. This is to work around a suspected linker bug when 1904// using Google Test as a framework on Mac OS X. The bug causes 1905// GetTypeId< ::testing::Test>() to return different values depending 1906// on whether the call is from the Google Test framework itself or 1907// from user test code. GetTestTypeId() is guaranteed to always 1908// return the same value, as it always calls GetTypeId<>() from the 1909// gtest.cc, which is within the Google Test framework. 1910TypeId GetTestTypeId() { 1911 return GetTypeId<Test>(); 1912} 1913 1914// The value of GetTestTypeId() as seen from within the Google Test 1915// library. This is solely for testing GetTestTypeId(). 1916extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId(); 1917 1918// This predicate-formatter checks that 'results' contains a test part 1919// failure of the given type and that the failure message contains the 1920// given substring. 1921AssertionResult HasOneFailure(const char* /* results_expr */, 1922 const char* /* type_expr */, 1923 const char* /* substr_expr */, 1924 const TestPartResultArray& results, 1925 TestPartResult::Type type, 1926 const char* substr) { 1927 const String expected(type == TestPartResult::kFatalFailure ? 1928 "1 fatal failure" : 1929 "1 non-fatal failure"); 1930 Message msg; 1931 if (results.size() != 1) { 1932 msg << "Expected: " << expected << "\n" 1933 << " Actual: " << results.size() << " failures"; 1934 for (int i = 0; i < results.size(); i++) { 1935 msg << "\n" << results.GetTestPartResult(i); 1936 } 1937 return AssertionFailure(msg); 1938 } 1939 1940 const TestPartResult& r = results.GetTestPartResult(0); 1941 if (r.type() != type) { 1942 msg << "Expected: " << expected << "\n" 1943 << " Actual:\n" 1944 << r; 1945 return AssertionFailure(msg); 1946 } 1947 1948 if (strstr(r.message(), substr) == NULL) { 1949 msg << "Expected: " << expected << " containing \"" 1950 << substr << "\"\n" 1951 << " Actual:\n" 1952 << r; 1953 return AssertionFailure(msg); 1954 } 1955 1956 return AssertionSuccess(); 1957} 1958 1959// The constructor of SingleFailureChecker remembers where to look up 1960// test part results, what type of failure we expect, and what 1961// substring the failure message should contain. 1962SingleFailureChecker:: SingleFailureChecker( 1963 const TestPartResultArray* results, 1964 TestPartResult::Type type, 1965 const char* substr) 1966 : results_(results), 1967 type_(type), 1968 substr_(substr) {} 1969 1970// The destructor of SingleFailureChecker verifies that the given 1971// TestPartResultArray contains exactly one failure that has the given 1972// type and contains the given substring. If that's not the case, a 1973// non-fatal failure will be generated. 1974SingleFailureChecker::~SingleFailureChecker() { 1975 EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_.c_str()); 1976} 1977 1978DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter( 1979 UnitTestImpl* unit_test) : unit_test_(unit_test) {} 1980 1981void DefaultGlobalTestPartResultReporter::ReportTestPartResult( 1982 const TestPartResult& result) { 1983 unit_test_->current_test_result()->AddTestPartResult(result); 1984 unit_test_->listeners()->repeater()->OnTestPartResult(result); 1985} 1986 1987DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter( 1988 UnitTestImpl* unit_test) : unit_test_(unit_test) {} 1989 1990void DefaultPerThreadTestPartResultReporter::ReportTestPartResult( 1991 const TestPartResult& result) { 1992 unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result); 1993} 1994 1995// Returns the global test part result reporter. 1996TestPartResultReporterInterface* 1997UnitTestImpl::GetGlobalTestPartResultReporter() { 1998 internal::MutexLock lock(&global_test_part_result_reporter_mutex_); 1999 return global_test_part_result_repoter_; 2000} 2001 2002// Sets the global test part result reporter. 2003void UnitTestImpl::SetGlobalTestPartResultReporter( 2004 TestPartResultReporterInterface* reporter) { 2005 internal::MutexLock lock(&global_test_part_result_reporter_mutex_); 2006 global_test_part_result_repoter_ = reporter; 2007} 2008 2009// Returns the test part result reporter for the current thread. 2010TestPartResultReporterInterface* 2011UnitTestImpl::GetTestPartResultReporterForCurrentThread() { 2012 return per_thread_test_part_result_reporter_.get(); 2013} 2014 2015// Sets the test part result reporter for the current thread. 2016void UnitTestImpl::SetTestPartResultReporterForCurrentThread( 2017 TestPartResultReporterInterface* reporter) { 2018 per_thread_test_part_result_reporter_.set(reporter); 2019} 2020 2021// Gets the number of successful test cases. 2022int UnitTestImpl::successful_test_case_count() const { 2023 return CountIf(test_cases_, TestCasePassed); 2024} 2025 2026// Gets the number of failed test cases. 2027int UnitTestImpl::failed_test_case_count() const { 2028 return CountIf(test_cases_, TestCaseFailed); 2029} 2030 2031// Gets the number of all test cases. 2032int UnitTestImpl::total_test_case_count() const { 2033 return static_cast<int>(test_cases_.size()); 2034} 2035 2036// Gets the number of all test cases that contain at least one test 2037// that should run. 2038int UnitTestImpl::test_case_to_run_count() const { 2039 return CountIf(test_cases_, ShouldRunTestCase); 2040} 2041 2042// Gets the number of successful tests. 2043int UnitTestImpl::successful_test_count() const { 2044 return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count); 2045} 2046 2047// Gets the number of failed tests. 2048int UnitTestImpl::failed_test_count() const { 2049 return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count); 2050} 2051 2052// Gets the number of disabled tests. 2053int UnitTestImpl::disabled_test_count() const { 2054 return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count); 2055} 2056 2057// Gets the number of all tests. 2058int UnitTestImpl::total_test_count() const { 2059 return SumOverTestCaseList(test_cases_, &TestCase::total_test_count); 2060} 2061 2062// Gets the number of tests that should run. 2063int UnitTestImpl::test_to_run_count() const { 2064 return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count); 2065} 2066 2067// Returns the current OS stack trace as a String. 2068// 2069// The maximum number of stack frames to be included is specified by 2070// the gtest_stack_trace_depth flag. The skip_count parameter 2071// specifies the number of top frames to be skipped, which doesn't 2072// count against the number of frames to be included. 2073// 2074// For example, if Foo() calls Bar(), which in turn calls 2075// CurrentOsStackTraceExceptTop(1), Foo() will be included in the 2076// trace but Bar() and CurrentOsStackTraceExceptTop() won't. 2077String UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) { 2078 (void)skip_count; 2079 return String(""); 2080} 2081 2082// Returns the current time in milliseconds. 2083TimeInMillis GetTimeInMillis() { 2084#if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__) 2085 // Difference between 1970-01-01 and 1601-01-01 in milliseconds. 2086 // http://analogous.blogspot.com/2005/04/epoch.html 2087 const TimeInMillis kJavaEpochToWinFileTimeDelta = 2088 static_cast<TimeInMillis>(116444736UL) * 100000UL; 2089 const DWORD kTenthMicrosInMilliSecond = 10000; 2090 2091 SYSTEMTIME now_systime; 2092 FILETIME now_filetime; 2093 ULARGE_INTEGER now_int64; 2094 // TODO(kenton@google.com): Shouldn't this just use 2095 // GetSystemTimeAsFileTime()? 2096 GetSystemTime(&now_systime); 2097 if (SystemTimeToFileTime(&now_systime, &now_filetime)) { 2098 now_int64.LowPart = now_filetime.dwLowDateTime; 2099 now_int64.HighPart = now_filetime.dwHighDateTime; 2100 now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) - 2101 kJavaEpochToWinFileTimeDelta; 2102 return now_int64.QuadPart; 2103 } 2104 return 0; 2105#elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_ 2106 __timeb64 now; 2107#ifdef _MSC_VER 2108 // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996 2109 // (deprecated function) there. 2110 // TODO(kenton@google.com): Use GetTickCount()? Or use 2111 // SystemTimeToFileTime() 2112#pragma warning(push) // Saves the current warning state. 2113#pragma warning(disable:4996) // Temporarily disables warning 4996. 2114 _ftime64(&now); 2115#pragma warning(pop) // Restores the warning state. 2116#else 2117 _ftime64(&now); 2118#endif // _MSC_VER 2119 return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm; 2120#elif GTEST_HAS_GETTIMEOFDAY_ 2121 struct timeval now; 2122 gettimeofday(&now, NULL); 2123 return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000; 2124#else 2125#error "Don't know how to get the current time on your system." 2126#endif 2127} 2128 2129// Utilities 2130 2131// class String 2132 2133// Returns the input enclosed in double quotes if it's not NULL; 2134// otherwise returns "(null)". For example, "\"Hello\"" is returned 2135// for input "Hello". 2136// 2137// This is useful for printing a C string in the syntax of a literal. 2138// 2139// Known issue: escape sequences are not handled yet. 2140String String::ShowCStringQuoted(const char* c_str) { 2141 return c_str ? String::Format("\"%s\"", c_str) : String("(null)"); 2142} 2143 2144// Copies at most length characters from str into a newly-allocated 2145// piece of memory of size length+1. The memory is allocated with new[]. 2146// A terminating null byte is written to the memory, and a pointer to it 2147// is returned. If str is NULL, NULL is returned. 2148static char* CloneString(const char* str, size_t length) { 2149 if (str == NULL) { 2150 return NULL; 2151 } else { 2152 char* const clone = new char[length + 1]; 2153 posix::StrNCpy(clone, str, length); 2154 clone[length] = '\0'; 2155 return clone; 2156 } 2157} 2158 2159// Clones a 0-terminated C string, allocating memory using new. The 2160// caller is responsible for deleting[] the return value. Returns the 2161// cloned string, or NULL if the input is NULL. 2162const char * String::CloneCString(const char* c_str) { 2163 return (c_str == NULL) ? 2164 NULL : CloneString(c_str, strlen(c_str)); 2165} 2166 2167#if GTEST_OS_WINDOWS_MOBILE 2168// Creates a UTF-16 wide string from the given ANSI string, allocating 2169// memory using new. The caller is responsible for deleting the return 2170// value using delete[]. Returns the wide string, or NULL if the 2171// input is NULL. 2172LPCWSTR String::AnsiToUtf16(const char* ansi) { 2173 if (!ansi) return NULL; 2174 const int length = strlen(ansi); 2175 const int unicode_length = 2176 MultiByteToWideChar(CP_ACP, 0, ansi, length, 2177 NULL, 0); 2178 WCHAR* unicode = new WCHAR[unicode_length + 1]; 2179 MultiByteToWideChar(CP_ACP, 0, ansi, length, 2180 unicode, unicode_length); 2181 unicode[unicode_length] = 0; 2182 return unicode; 2183} 2184 2185// Creates an ANSI string from the given wide string, allocating 2186// memory using new. The caller is responsible for deleting the return 2187// value using delete[]. Returns the ANSI string, or NULL if the 2188// input is NULL. 2189const char* String::Utf16ToAnsi(LPCWSTR utf16_str) { 2190 if (!utf16_str) return NULL; 2191 const int ansi_length = 2192 WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, 2193 NULL, 0, NULL, NULL); 2194 char* ansi = new char[ansi_length + 1]; 2195 WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, 2196 ansi, ansi_length, NULL, NULL); 2197 ansi[ansi_length] = 0; 2198 return ansi; 2199} 2200 2201#endif // GTEST_OS_WINDOWS_MOBILE 2202 2203// Compares two C strings. Returns true iff they have the same content. 2204// 2205// Unlike strcmp(), this function can handle NULL argument(s). A NULL 2206// C string is considered different to any non-NULL C string, 2207// including the empty string. 2208bool String::CStringEquals(const char * lhs, const char * rhs) { 2209 if ( lhs == NULL ) return rhs == NULL; 2210 2211 if ( rhs == NULL ) return false; 2212 2213 return strcmp(lhs, rhs) == 0; 2214} 2215 2216#if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING 2217 2218// Converts an array of wide chars to a narrow string using the UTF-8 2219// encoding, and streams the result to the given Message object. 2220static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length, 2221 Message* msg) { 2222 // TODO(wan): consider allowing a testing::String object to 2223 // contain '\0'. This will make it behave more like std::string, 2224 // and will allow ToUtf8String() to return the correct encoding 2225 // for '\0' s.t. we can get rid of the conditional here (and in 2226 // several other places). 2227 for (size_t i = 0; i != length; ) { // NOLINT 2228 if (wstr[i] != L'\0') { 2229 *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i)); 2230 while (i != length && wstr[i] != L'\0') 2231 i++; 2232 } else { 2233 *msg << '\0'; 2234 i++; 2235 } 2236 } 2237} 2238 2239#endif // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING 2240 2241} // namespace internal 2242 2243#if GTEST_HAS_STD_WSTRING 2244// Converts the given wide string to a narrow string using the UTF-8 2245// encoding, and streams the result to this Message object. 2246Message& Message::operator <<(const ::std::wstring& wstr) { 2247 internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this); 2248 return *this; 2249} 2250#endif // GTEST_HAS_STD_WSTRING 2251 2252#if GTEST_HAS_GLOBAL_WSTRING 2253// Converts the given wide string to a narrow string using the UTF-8 2254// encoding, and streams the result to this Message object. 2255Message& Message::operator <<(const ::wstring& wstr) { 2256 internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this); 2257 return *this; 2258} 2259#endif // GTEST_HAS_GLOBAL_WSTRING 2260 2261namespace internal { 2262 2263// Formats a value to be used in a failure message. 2264 2265// For a char value, we print it as a C++ char literal and as an 2266// unsigned integer (both in decimal and in hexadecimal). 2267String FormatForFailureMessage(char ch) { 2268 const unsigned int ch_as_uint = ch; 2269 // A String object cannot contain '\0', so we print "\\0" when ch is 2270 // '\0'. 2271 return String::Format("'%s' (%u, 0x%X)", 2272 ch ? String::Format("%c", ch).c_str() : "\\0", 2273 ch_as_uint, ch_as_uint); 2274} 2275 2276// For a wchar_t value, we print it as a C++ wchar_t literal and as an 2277// unsigned integer (both in decimal and in hexidecimal). 2278String FormatForFailureMessage(wchar_t wchar) { 2279 // The C++ standard doesn't specify the exact size of the wchar_t 2280 // type. It just says that it shall have the same size as another 2281 // integral type, called its underlying type. 2282 // 2283 // Therefore, in order to print a wchar_t value in the numeric form, 2284 // we first convert it to the largest integral type (UInt64) and 2285 // then print the converted value. 2286 // 2287 // We use streaming to print the value as "%llu" doesn't work 2288 // correctly with MSVC 7.1. 2289 const UInt64 wchar_as_uint64 = wchar; 2290 Message msg; 2291 // A String object cannot contain '\0', so we print "\\0" when wchar is 2292 // L'\0'. 2293 char buffer[32]; // CodePointToUtf8 requires a buffer that big. 2294 msg << "L'" 2295 << (wchar ? CodePointToUtf8(static_cast<UInt32>(wchar), buffer) : "\\0") 2296 << "' (" << wchar_as_uint64 << ", 0x" << ::std::setbase(16) 2297 << wchar_as_uint64 << ")"; 2298 return msg.GetString(); 2299} 2300 2301} // namespace internal 2302 2303// AssertionResult constructors. 2304// Used in EXPECT_TRUE/FALSE(assertion_result). 2305AssertionResult::AssertionResult(const AssertionResult& other) 2306 : success_(other.success_), 2307 message_(other.message_.get() != NULL ? 2308 new internal::String(*other.message_) : 2309 static_cast<internal::String*>(NULL)) { 2310} 2311 2312// Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE. 2313AssertionResult AssertionResult::operator!() const { 2314 AssertionResult negation(!success_); 2315 if (message_.get() != NULL) 2316 negation << *message_; 2317 return negation; 2318} 2319 2320// Makes a successful assertion result. 2321AssertionResult AssertionSuccess() { 2322 return AssertionResult(true); 2323} 2324 2325// Makes a failed assertion result. 2326AssertionResult AssertionFailure() { 2327 return AssertionResult(false); 2328} 2329 2330// Makes a failed assertion result with the given failure message. 2331// Deprecated; use AssertionFailure() << message. 2332AssertionResult AssertionFailure(const Message& message) { 2333 return AssertionFailure() << message; 2334} 2335 2336namespace internal { 2337 2338// Constructs and returns the message for an equality assertion 2339// (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure. 2340// 2341// The first four parameters are the expressions used in the assertion 2342// and their values, as strings. For example, for ASSERT_EQ(foo, bar) 2343// where foo is 5 and bar is 6, we have: 2344// 2345// expected_expression: "foo" 2346// actual_expression: "bar" 2347// expected_value: "5" 2348// actual_value: "6" 2349// 2350// The ignoring_case parameter is true iff the assertion is a 2351// *_STRCASEEQ*. When it's true, the string " (ignoring case)" will 2352// be inserted into the message. 2353AssertionResult EqFailure(const char* expected_expression, 2354 const char* actual_expression, 2355 const String& expected_value, 2356 const String& actual_value, 2357 bool ignoring_case) { 2358 Message msg; 2359 msg << "Value of: " << actual_expression; 2360 if (actual_value != actual_expression) { 2361 msg << "\n Actual: " << actual_value; 2362 } 2363 2364 msg << "\nExpected: " << expected_expression; 2365 if (ignoring_case) { 2366 msg << " (ignoring case)"; 2367 } 2368 if (expected_value != expected_expression) { 2369 msg << "\nWhich is: " << expected_value; 2370 } 2371 2372 return AssertionFailure(msg); 2373} 2374 2375// Constructs a failure message for Boolean assertions such as EXPECT_TRUE. 2376String GetBoolAssertionFailureMessage(const AssertionResult& assertion_result, 2377 const char* expression_text, 2378 const char* actual_predicate_value, 2379 const char* expected_predicate_value) { 2380 const char* actual_message = assertion_result.message(); 2381 Message msg; 2382 msg << "Value of: " << expression_text 2383 << "\n Actual: " << actual_predicate_value; 2384 if (actual_message[0] != '\0') 2385 msg << " (" << actual_message << ")"; 2386 msg << "\nExpected: " << expected_predicate_value; 2387 return msg.GetString(); 2388} 2389 2390// Helper function for implementing ASSERT_NEAR. 2391AssertionResult DoubleNearPredFormat(const char* expr1, 2392 const char* expr2, 2393 const char* abs_error_expr, 2394 double val1, 2395 double val2, 2396 double abs_error) { 2397 const double diff = fabs(val1 - val2); 2398 if (diff <= abs_error) return AssertionSuccess(); 2399 2400 // TODO(wan): do not print the value of an expression if it's 2401 // already a literal. 2402 Message msg; 2403 msg << "The difference between " << expr1 << " and " << expr2 2404 << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n" 2405 << expr1 << " evaluates to " << val1 << ",\n" 2406 << expr2 << " evaluates to " << val2 << ", and\n" 2407 << abs_error_expr << " evaluates to " << abs_error << "."; 2408 return AssertionFailure(msg); 2409} 2410 2411 2412// Helper template for implementing FloatLE() and DoubleLE(). 2413template <typename RawType> 2414AssertionResult FloatingPointLE(const char* expr1, 2415 const char* expr2, 2416 RawType val1, 2417 RawType val2) { 2418 // Returns success if val1 is less than val2, 2419 if (val1 < val2) { 2420 return AssertionSuccess(); 2421 } 2422 2423 // or if val1 is almost equal to val2. 2424 const FloatingPoint<RawType> lhs(val1), rhs(val2); 2425 if (lhs.AlmostEquals(rhs)) { 2426 return AssertionSuccess(); 2427 } 2428 2429 // Note that the above two checks will both fail if either val1 or 2430 // val2 is NaN, as the IEEE floating-point standard requires that 2431 // any predicate involving a NaN must return false. 2432 2433 StrStream val1_ss; 2434 val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2) 2435 << val1; 2436 2437 StrStream val2_ss; 2438 val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2) 2439 << val2; 2440 2441 Message msg; 2442 msg << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n" 2443 << " Actual: " << StrStreamToString(&val1_ss) << " vs " 2444 << StrStreamToString(&val2_ss); 2445 2446 return AssertionFailure(msg); 2447} 2448 2449} // namespace internal 2450 2451// Asserts that val1 is less than, or almost equal to, val2. Fails 2452// otherwise. In particular, it fails if either val1 or val2 is NaN. 2453AssertionResult FloatLE(const char* expr1, const char* expr2, 2454 float val1, float val2) { 2455 return internal::FloatingPointLE<float>(expr1, expr2, val1, val2); 2456} 2457 2458// Asserts that val1 is less than, or almost equal to, val2. Fails 2459// otherwise. In particular, it fails if either val1 or val2 is NaN. 2460AssertionResult DoubleLE(const char* expr1, const char* expr2, 2461 double val1, double val2) { 2462 return internal::FloatingPointLE<double>(expr1, expr2, val1, val2); 2463} 2464 2465namespace internal { 2466 2467// The helper function for {ASSERT|EXPECT}_EQ with int or enum 2468// arguments. 2469AssertionResult CmpHelperEQ(const char* expected_expression, 2470 const char* actual_expression, 2471 BiggestInt expected, 2472 BiggestInt actual) { 2473 if (expected == actual) { 2474 return AssertionSuccess(); 2475 } 2476 2477 return EqFailure(expected_expression, 2478 actual_expression, 2479 FormatForComparisonFailureMessage(expected, actual), 2480 FormatForComparisonFailureMessage(actual, expected), 2481 false); 2482} 2483 2484// A macro for implementing the helper functions needed to implement 2485// ASSERT_?? and EXPECT_?? with integer or enum arguments. It is here 2486// just to avoid copy-and-paste of similar code. 2487#define GTEST_IMPL_CMP_HELPER_(op_name, op)\ 2488AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \ 2489 BiggestInt val1, BiggestInt val2) {\ 2490 if (val1 op val2) {\ 2491 return AssertionSuccess();\ 2492 } else {\ 2493 Message msg;\ 2494 msg << "Expected: (" << expr1 << ") " #op " (" << expr2\ 2495 << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\ 2496 << " vs " << FormatForComparisonFailureMessage(val2, val1);\ 2497 return AssertionFailure(msg);\ 2498 }\ 2499} 2500 2501// Implements the helper function for {ASSERT|EXPECT}_NE with int or 2502// enum arguments. 2503GTEST_IMPL_CMP_HELPER_(NE, !=) 2504// Implements the helper function for {ASSERT|EXPECT}_LE with int or 2505// enum arguments. 2506GTEST_IMPL_CMP_HELPER_(LE, <=) 2507// Implements the helper function for {ASSERT|EXPECT}_LT with int or 2508// enum arguments. 2509GTEST_IMPL_CMP_HELPER_(LT, < ) 2510// Implements the helper function for {ASSERT|EXPECT}_GE with int or 2511// enum arguments. 2512GTEST_IMPL_CMP_HELPER_(GE, >=) 2513// Implements the helper function for {ASSERT|EXPECT}_GT with int or 2514// enum arguments. 2515GTEST_IMPL_CMP_HELPER_(GT, > ) 2516 2517#undef GTEST_IMPL_CMP_HELPER_ 2518 2519// The helper function for {ASSERT|EXPECT}_STREQ. 2520AssertionResult CmpHelperSTREQ(const char* expected_expression, 2521 const char* actual_expression, 2522 const char* expected, 2523 const char* actual) { 2524 if (String::CStringEquals(expected, actual)) { 2525 return AssertionSuccess(); 2526 } 2527 2528 return EqFailure(expected_expression, 2529 actual_expression, 2530 String::ShowCStringQuoted(expected), 2531 String::ShowCStringQuoted(actual), 2532 false); 2533} 2534 2535// The helper function for {ASSERT|EXPECT}_STRCASEEQ. 2536AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression, 2537 const char* actual_expression, 2538 const char* expected, 2539 const char* actual) { 2540 if (String::CaseInsensitiveCStringEquals(expected, actual)) { 2541 return AssertionSuccess(); 2542 } 2543 2544 return EqFailure(expected_expression, 2545 actual_expression, 2546 String::ShowCStringQuoted(expected), 2547 String::ShowCStringQuoted(actual), 2548 true); 2549} 2550 2551// The helper function for {ASSERT|EXPECT}_STRNE. 2552AssertionResult CmpHelperSTRNE(const char* s1_expression, 2553 const char* s2_expression, 2554 const char* s1, 2555 const char* s2) { 2556 if (!String::CStringEquals(s1, s2)) { 2557 return AssertionSuccess(); 2558 } else { 2559 Message msg; 2560 msg << "Expected: (" << s1_expression << ") != (" 2561 << s2_expression << "), actual: \"" 2562 << s1 << "\" vs \"" << s2 << "\""; 2563 return AssertionFailure(msg); 2564 } 2565} 2566 2567// The helper function for {ASSERT|EXPECT}_STRCASENE. 2568AssertionResult CmpHelperSTRCASENE(const char* s1_expression, 2569 const char* s2_expression, 2570 const char* s1, 2571 const char* s2) { 2572 if (!String::CaseInsensitiveCStringEquals(s1, s2)) { 2573 return AssertionSuccess(); 2574 } else { 2575 Message msg; 2576 msg << "Expected: (" << s1_expression << ") != (" 2577 << s2_expression << ") (ignoring case), actual: \"" 2578 << s1 << "\" vs \"" << s2 << "\""; 2579 return AssertionFailure(msg); 2580 } 2581} 2582 2583} // namespace internal 2584 2585namespace { 2586 2587// Helper functions for implementing IsSubString() and IsNotSubstring(). 2588 2589// This group of overloaded functions return true iff needle is a 2590// substring of haystack. NULL is considered a substring of itself 2591// only. 2592 2593bool IsSubstringPred(const char* needle, const char* haystack) { 2594 if (needle == NULL || haystack == NULL) 2595 return needle == haystack; 2596 2597 return strstr(haystack, needle) != NULL; 2598} 2599 2600bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) { 2601 if (needle == NULL || haystack == NULL) 2602 return needle == haystack; 2603 2604 return wcsstr(haystack, needle) != NULL; 2605} 2606 2607// StringType here can be either ::std::string or ::std::wstring. 2608template <typename StringType> 2609bool IsSubstringPred(const StringType& needle, 2610 const StringType& haystack) { 2611 return haystack.find(needle) != StringType::npos; 2612} 2613 2614// This function implements either IsSubstring() or IsNotSubstring(), 2615// depending on the value of the expected_to_be_substring parameter. 2616// StringType here can be const char*, const wchar_t*, ::std::string, 2617// or ::std::wstring. 2618template <typename StringType> 2619AssertionResult IsSubstringImpl( 2620 bool expected_to_be_substring, 2621 const char* needle_expr, const char* haystack_expr, 2622 const StringType& needle, const StringType& haystack) { 2623 if (IsSubstringPred(needle, haystack) == expected_to_be_substring) 2624 return AssertionSuccess(); 2625 2626 const bool is_wide_string = sizeof(needle[0]) > 1; 2627 const char* const begin_string_quote = is_wide_string ? "L\"" : "\""; 2628 return AssertionFailure( 2629 Message() 2630 << "Value of: " << needle_expr << "\n" 2631 << " Actual: " << begin_string_quote << needle << "\"\n" 2632 << "Expected: " << (expected_to_be_substring ? "" : "not ") 2633 << "a substring of " << haystack_expr << "\n" 2634 << "Which is: " << begin_string_quote << haystack << "\""); 2635} 2636 2637} // namespace 2638 2639// IsSubstring() and IsNotSubstring() check whether needle is a 2640// substring of haystack (NULL is considered a substring of itself 2641// only), and return an appropriate error message when they fail. 2642 2643AssertionResult IsSubstring( 2644 const char* needle_expr, const char* haystack_expr, 2645 const char* needle, const char* haystack) { 2646 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); 2647} 2648 2649AssertionResult IsSubstring( 2650 const char* needle_expr, const char* haystack_expr, 2651 const wchar_t* needle, const wchar_t* haystack) { 2652 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); 2653} 2654 2655AssertionResult IsNotSubstring( 2656 const char* needle_expr, const char* haystack_expr, 2657 const char* needle, const char* haystack) { 2658 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); 2659} 2660 2661AssertionResult IsNotSubstring( 2662 const char* needle_expr, const char* haystack_expr, 2663 const wchar_t* needle, const wchar_t* haystack) { 2664 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); 2665} 2666 2667AssertionResult IsSubstring( 2668 const char* needle_expr, const char* haystack_expr, 2669 const ::std::string& needle, const ::std::string& haystack) { 2670 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); 2671} 2672 2673AssertionResult IsNotSubstring( 2674 const char* needle_expr, const char* haystack_expr, 2675 const ::std::string& needle, const ::std::string& haystack) { 2676 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); 2677} 2678 2679#if GTEST_HAS_STD_WSTRING 2680AssertionResult IsSubstring( 2681 const char* needle_expr, const char* haystack_expr, 2682 const ::std::wstring& needle, const ::std::wstring& haystack) { 2683 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); 2684} 2685 2686AssertionResult IsNotSubstring( 2687 const char* needle_expr, const char* haystack_expr, 2688 const ::std::wstring& needle, const ::std::wstring& haystack) { 2689 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); 2690} 2691#endif // GTEST_HAS_STD_WSTRING 2692 2693namespace internal { 2694 2695#if GTEST_OS_WINDOWS 2696 2697namespace { 2698 2699// Helper function for IsHRESULT{SuccessFailure} predicates 2700AssertionResult HRESULTFailureHelper(const char* expr, 2701 const char* expected, 2702 long hr) { // NOLINT 2703#if GTEST_OS_WINDOWS_MOBILE 2704 // Windows CE doesn't support FormatMessage. 2705 const char error_text[] = ""; 2706#else 2707 // Looks up the human-readable system message for the HRESULT code 2708 // and since we're not passing any params to FormatMessage, we don't 2709 // want inserts expanded. 2710 const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM | 2711 FORMAT_MESSAGE_IGNORE_INSERTS; 2712 const DWORD kBufSize = 4096; // String::Format can't exceed this length. 2713 // Gets the system's human readable message string for this HRESULT. 2714 char error_text[kBufSize] = { '\0' }; 2715 DWORD message_length = ::FormatMessageA(kFlags, 2716 0, // no source, we're asking system 2717 hr, // the error 2718 0, // no line width restrictions 2719 error_text, // output buffer 2720 kBufSize, // buf size 2721 NULL); // no arguments for inserts 2722 // Trims tailing white space (FormatMessage leaves a trailing cr-lf) 2723 for (; message_length && isspace(error_text[message_length - 1]); 2724 --message_length) { 2725 error_text[message_length - 1] = '\0'; 2726 } 2727#endif // GTEST_OS_WINDOWS_MOBILE 2728 2729 const String error_hex(String::Format("0x%08X ", hr)); 2730 Message msg; 2731 msg << "Expected: " << expr << " " << expected << ".\n" 2732 << " Actual: " << error_hex << error_text << "\n"; 2733 2734 return ::testing::AssertionFailure(msg); 2735} 2736 2737} // namespace 2738 2739AssertionResult IsHRESULTSuccess(const char* expr, long hr) { // NOLINT 2740 if (SUCCEEDED(hr)) { 2741 return AssertionSuccess(); 2742 } 2743 return HRESULTFailureHelper(expr, "succeeds", hr); 2744} 2745 2746AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT 2747 if (FAILED(hr)) { 2748 return AssertionSuccess(); 2749 } 2750 return HRESULTFailureHelper(expr, "fails", hr); 2751} 2752 2753#endif // GTEST_OS_WINDOWS 2754 2755// Utility functions for encoding Unicode text (wide strings) in 2756// UTF-8. 2757 2758// A Unicode code-point can have upto 21 bits, and is encoded in UTF-8 2759// like this: 2760// 2761// Code-point length Encoding 2762// 0 - 7 bits 0xxxxxxx 2763// 8 - 11 bits 110xxxxx 10xxxxxx 2764// 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx 2765// 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx 2766 2767// The maximum code-point a one-byte UTF-8 sequence can represent. 2768const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) << 7) - 1; 2769 2770// The maximum code-point a two-byte UTF-8 sequence can represent. 2771const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1; 2772 2773// The maximum code-point a three-byte UTF-8 sequence can represent. 2774const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2*6)) - 1; 2775 2776// The maximum code-point a four-byte UTF-8 sequence can represent. 2777const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3*6)) - 1; 2778 2779// Chops off the n lowest bits from a bit pattern. Returns the n 2780// lowest bits. As a side effect, the original bit pattern will be 2781// shifted to the right by n bits. 2782inline UInt32 ChopLowBits(UInt32* bits, int n) { 2783 const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1); 2784 *bits >>= n; 2785 return low_bits; 2786} 2787 2788// Converts a Unicode code point to a narrow string in UTF-8 encoding. 2789// code_point parameter is of type UInt32 because wchar_t may not be 2790// wide enough to contain a code point. 2791// The output buffer str must containt at least 32 characters. 2792// The function returns the address of the output buffer. 2793// If the code_point is not a valid Unicode code point 2794// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be output 2795// as '(Invalid Unicode 0xXXXXXXXX)'. 2796char* CodePointToUtf8(UInt32 code_point, char* str) { 2797 if (code_point <= kMaxCodePoint1) { 2798 str[1] = '\0'; 2799 str[0] = static_cast<char>(code_point); // 0xxxxxxx 2800 } else if (code_point <= kMaxCodePoint2) { 2801 str[2] = '\0'; 2802 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx 2803 str[0] = static_cast<char>(0xC0 | code_point); // 110xxxxx 2804 } else if (code_point <= kMaxCodePoint3) { 2805 str[3] = '\0'; 2806 str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx 2807 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx 2808 str[0] = static_cast<char>(0xE0 | code_point); // 1110xxxx 2809 } else if (code_point <= kMaxCodePoint4) { 2810 str[4] = '\0'; 2811 str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx 2812 str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx 2813 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx 2814 str[0] = static_cast<char>(0xF0 | code_point); // 11110xxx 2815 } else { 2816 // The longest string String::Format can produce when invoked 2817 // with these parameters is 28 character long (not including 2818 // the terminating nul character). We are asking for 32 character 2819 // buffer just in case. This is also enough for strncpy to 2820 // null-terminate the destination string. 2821 posix::StrNCpy( 2822 str, String::Format("(Invalid Unicode 0x%X)", code_point).c_str(), 32); 2823 str[31] = '\0'; // Makes sure no change in the format to strncpy leaves 2824 // the result unterminated. 2825 } 2826 return str; 2827} 2828 2829// The following two functions only make sense if the the system 2830// uses UTF-16 for wide string encoding. All supported systems 2831// with 16 bit wchar_t (Windows, Cygwin, Symbian OS) do use UTF-16. 2832 2833// Determines if the arguments constitute UTF-16 surrogate pair 2834// and thus should be combined into a single Unicode code point 2835// using CreateCodePointFromUtf16SurrogatePair. 2836inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) { 2837 return sizeof(wchar_t) == 2 && 2838 (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00; 2839} 2840 2841// Creates a Unicode code point from UTF16 surrogate pair. 2842inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first, 2843 wchar_t second) { 2844 const UInt32 mask = (1 << 10) - 1; 2845 return (sizeof(wchar_t) == 2) ? 2846 (((first & mask) << 10) | (second & mask)) + 0x10000 : 2847 // This function should not be called when the condition is 2848 // false, but we provide a sensible default in case it is. 2849 static_cast<UInt32>(first); 2850} 2851 2852// Converts a wide string to a narrow string in UTF-8 encoding. 2853// The wide string is assumed to have the following encoding: 2854// UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS) 2855// UTF-32 if sizeof(wchar_t) == 4 (on Linux) 2856// Parameter str points to a null-terminated wide string. 2857// Parameter num_chars may additionally limit the number 2858// of wchar_t characters processed. -1 is used when the entire string 2859// should be processed. 2860// If the string contains code points that are not valid Unicode code points 2861// (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output 2862// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding 2863// and contains invalid UTF-16 surrogate pairs, values in those pairs 2864// will be encoded as individual Unicode characters from Basic Normal Plane. 2865String WideStringToUtf8(const wchar_t* str, int num_chars) { 2866 if (num_chars == -1) 2867 num_chars = static_cast<int>(wcslen(str)); 2868 2869 StrStream stream; 2870 for (int i = 0; i < num_chars; ++i) { 2871 UInt32 unicode_code_point; 2872 2873 if (str[i] == L'\0') { 2874 break; 2875 } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) { 2876 unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i], 2877 str[i + 1]); 2878 i++; 2879 } else { 2880 unicode_code_point = static_cast<UInt32>(str[i]); 2881 } 2882 2883 char buffer[32]; // CodePointToUtf8 requires a buffer this big. 2884 stream << CodePointToUtf8(unicode_code_point, buffer); 2885 } 2886 return StrStreamToString(&stream); 2887} 2888 2889// Converts a wide C string to a String using the UTF-8 encoding. 2890// NULL will be converted to "(null)". 2891String String::ShowWideCString(const wchar_t * wide_c_str) { 2892 if (wide_c_str == NULL) return String("(null)"); 2893 2894 return String(internal::WideStringToUtf8(wide_c_str, -1).c_str()); 2895} 2896 2897// Similar to ShowWideCString(), except that this function encloses 2898// the converted string in double quotes. 2899String String::ShowWideCStringQuoted(const wchar_t* wide_c_str) { 2900 if (wide_c_str == NULL) return String("(null)"); 2901 2902 return String::Format("L\"%s\"", 2903 String::ShowWideCString(wide_c_str).c_str()); 2904} 2905 2906// Compares two wide C strings. Returns true iff they have the same 2907// content. 2908// 2909// Unlike wcscmp(), this function can handle NULL argument(s). A NULL 2910// C string is considered different to any non-NULL C string, 2911// including the empty string. 2912bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) { 2913 if (lhs == NULL) return rhs == NULL; 2914 2915 if (rhs == NULL) return false; 2916 2917 return wcscmp(lhs, rhs) == 0; 2918} 2919 2920// Helper function for *_STREQ on wide strings. 2921AssertionResult CmpHelperSTREQ(const char* expected_expression, 2922 const char* actual_expression, 2923 const wchar_t* expected, 2924 const wchar_t* actual) { 2925 if (String::WideCStringEquals(expected, actual)) { 2926 return AssertionSuccess(); 2927 } 2928 2929 return EqFailure(expected_expression, 2930 actual_expression, 2931 String::ShowWideCStringQuoted(expected), 2932 String::ShowWideCStringQuoted(actual), 2933 false); 2934} 2935 2936// Helper function for *_STRNE on wide strings. 2937AssertionResult CmpHelperSTRNE(const char* s1_expression, 2938 const char* s2_expression, 2939 const wchar_t* s1, 2940 const wchar_t* s2) { 2941 if (!String::WideCStringEquals(s1, s2)) { 2942 return AssertionSuccess(); 2943 } 2944 2945 Message msg; 2946 msg << "Expected: (" << s1_expression << ") != (" 2947 << s2_expression << "), actual: " 2948 << String::ShowWideCStringQuoted(s1) 2949 << " vs " << String::ShowWideCStringQuoted(s2); 2950 return AssertionFailure(msg); 2951} 2952 2953// Compares two C strings, ignoring case. Returns true iff they have 2954// the same content. 2955// 2956// Unlike strcasecmp(), this function can handle NULL argument(s). A 2957// NULL C string is considered different to any non-NULL C string, 2958// including the empty string. 2959bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) { 2960 if (lhs == NULL) 2961 return rhs == NULL; 2962 if (rhs == NULL) 2963 return false; 2964 return posix::StrCaseCmp(lhs, rhs) == 0; 2965} 2966 2967 // Compares two wide C strings, ignoring case. Returns true iff they 2968 // have the same content. 2969 // 2970 // Unlike wcscasecmp(), this function can handle NULL argument(s). 2971 // A NULL C string is considered different to any non-NULL wide C string, 2972 // including the empty string. 2973 // NB: The implementations on different platforms slightly differ. 2974 // On windows, this method uses _wcsicmp which compares according to LC_CTYPE 2975 // environment variable. On GNU platform this method uses wcscasecmp 2976 // which compares according to LC_CTYPE category of the current locale. 2977 // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the 2978 // current locale. 2979bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs, 2980 const wchar_t* rhs) { 2981 if ( lhs == NULL ) return rhs == NULL; 2982 2983 if ( rhs == NULL ) return false; 2984 2985#if GTEST_OS_WINDOWS 2986 return _wcsicmp(lhs, rhs) == 0; 2987#elif GTEST_OS_LINUX 2988 return wcscasecmp(lhs, rhs) == 0; 2989#else 2990 // Mac OS X and Cygwin don't define wcscasecmp. Other unknown OSes 2991 // may not define it either. 2992 wint_t left, right; 2993 do { 2994 left = towlower(*lhs++); 2995 right = towlower(*rhs++); 2996 } while (left && left == right); 2997 return left == right; 2998#endif // OS selector 2999} 3000 3001// Compares this with another String. 3002// Returns < 0 if this is less than rhs, 0 if this is equal to rhs, or > 0 3003// if this is greater than rhs. 3004int String::Compare(const String & rhs) const { 3005 const char* const lhs_c_str = c_str(); 3006 const char* const rhs_c_str = rhs.c_str(); 3007 3008 if (lhs_c_str == NULL) { 3009 return rhs_c_str == NULL ? 0 : -1; // NULL < anything except NULL 3010 } else if (rhs_c_str == NULL) { 3011 return 1; 3012 } 3013 3014 const size_t shorter_str_len = 3015 length() <= rhs.length() ? length() : rhs.length(); 3016 for (size_t i = 0; i != shorter_str_len; i++) { 3017 if (lhs_c_str[i] < rhs_c_str[i]) { 3018 return -1; 3019 } else if (lhs_c_str[i] > rhs_c_str[i]) { 3020 return 1; 3021 } 3022 } 3023 return (length() < rhs.length()) ? -1 : 3024 (length() > rhs.length()) ? 1 : 0; 3025} 3026 3027// Returns true iff this String ends with the given suffix. *Any* 3028// String is considered to end with a NULL or empty suffix. 3029bool String::EndsWith(const char* suffix) const { 3030 if (suffix == NULL || CStringEquals(suffix, "")) return true; 3031 3032 if (c_str() == NULL) return false; 3033 3034 const size_t this_len = strlen(c_str()); 3035 const size_t suffix_len = strlen(suffix); 3036 return (this_len >= suffix_len) && 3037 CStringEquals(c_str() + this_len - suffix_len, suffix); 3038} 3039 3040// Returns true iff this String ends with the given suffix, ignoring case. 3041// Any String is considered to end with a NULL or empty suffix. 3042bool String::EndsWithCaseInsensitive(const char* suffix) const { 3043 if (suffix == NULL || CStringEquals(suffix, "")) return true; 3044 3045 if (c_str() == NULL) return false; 3046 3047 const size_t this_len = strlen(c_str()); 3048 const size_t suffix_len = strlen(suffix); 3049 return (this_len >= suffix_len) && 3050 CaseInsensitiveCStringEquals(c_str() + this_len - suffix_len, suffix); 3051} 3052 3053// Formats a list of arguments to a String, using the same format 3054// spec string as for printf. 3055// 3056// We do not use the StringPrintf class as it is not universally 3057// available. 3058// 3059// The result is limited to 4096 characters (including the tailing 0). 3060// If 4096 characters are not enough to format the input, or if 3061// there's an error, "<formatting error or buffer exceeded>" is 3062// returned. 3063String String::Format(const char * format, ...) { 3064 va_list args; 3065 va_start(args, format); 3066 3067 char buffer[4096]; 3068 const int kBufferSize = sizeof(buffer)/sizeof(buffer[0]); 3069 3070 // MSVC 8 deprecates vsnprintf(), so we want to suppress warning 3071 // 4996 (deprecated function) there. 3072#ifdef _MSC_VER // We are using MSVC. 3073#pragma warning(push) // Saves the current warning state. 3074#pragma warning(disable:4996) // Temporarily disables warning 4996. 3075 const int size = vsnprintf(buffer, kBufferSize, format, args); 3076#pragma warning(pop) // Restores the warning state. 3077#else // We are not using MSVC. 3078 const int size = vsnprintf(buffer, kBufferSize, format, args); 3079#endif // _MSC_VER 3080 va_end(args); 3081 3082 // vsnprintf()'s behavior is not portable. When the buffer is not 3083 // big enough, it returns a negative value in MSVC, and returns the 3084 // needed buffer size on Linux. When there is an output error, it 3085 // always returns a negative value. For simplicity, we lump the two 3086 // error cases together. 3087 if (size < 0 || size >= kBufferSize) { 3088 return String("<formatting error or buffer exceeded>"); 3089 } else { 3090 return String(buffer, size); 3091 } 3092} 3093 3094// Converts the buffer in a StrStream to a String, converting NUL 3095// bytes to "\\0" along the way. 3096String StrStreamToString(StrStream* ss) { 3097 const ::std::string& str = ss->str(); 3098 const char* const start = str.c_str(); 3099 const char* const end = start + str.length(); 3100 3101 // We need to use a helper StrStream to do this transformation 3102 // because String doesn't support push_back(). 3103 StrStream helper; 3104 for (const char* ch = start; ch != end; ++ch) { 3105 if (*ch == '\0') { 3106 helper << "\\0"; // Replaces NUL with "\\0"; 3107 } else { 3108 helper.put(*ch); 3109 } 3110 } 3111 3112 return String(helper.str().c_str()); 3113} 3114 3115// Appends the user-supplied message to the Google-Test-generated message. 3116String AppendUserMessage(const String& gtest_msg, 3117 const Message& user_msg) { 3118 // Appends the user message if it's non-empty. 3119 const String user_msg_string = user_msg.GetString(); 3120 if (user_msg_string.empty()) { 3121 return gtest_msg; 3122 } 3123 3124 Message msg; 3125 msg << gtest_msg << "\n" << user_msg_string; 3126 3127 return msg.GetString(); 3128} 3129 3130} // namespace internal 3131 3132// class TestResult 3133 3134// Creates an empty TestResult. 3135TestResult::TestResult() 3136 : death_test_count_(0), 3137 elapsed_time_(0) { 3138} 3139 3140// D'tor. 3141TestResult::~TestResult() { 3142} 3143 3144// Returns the i-th test part result among all the results. i can 3145// range from 0 to total_part_count() - 1. If i is not in that range, 3146// aborts the program. 3147const TestPartResult& TestResult::GetTestPartResult(int i) const { 3148 if (i < 0 || i >= total_part_count()) 3149 internal::posix::Abort(); 3150 return test_part_results_.at(i); 3151} 3152 3153// Returns the i-th test property. i can range from 0 to 3154// test_property_count() - 1. If i is not in that range, aborts the 3155// program. 3156const TestProperty& TestResult::GetTestProperty(int i) const { 3157 if (i < 0 || i >= test_property_count()) 3158 internal::posix::Abort(); 3159 return test_properties_.at(i); 3160} 3161 3162// Clears the test part results. 3163void TestResult::ClearTestPartResults() { 3164 test_part_results_.clear(); 3165} 3166 3167// Adds a test part result to the list. 3168void TestResult::AddTestPartResult(const TestPartResult& test_part_result) { 3169 test_part_results_.push_back(test_part_result); 3170} 3171 3172// Adds a test property to the list. If a property with the same key as the 3173// supplied property is already represented, the value of this test_property 3174// replaces the old value for that key. 3175void TestResult::RecordProperty(const TestProperty& test_property) { 3176 if (!ValidateTestProperty(test_property)) { 3177 return; 3178 } 3179 internal::MutexLock lock(&test_properites_mutex_); 3180 const std::vector<TestProperty>::iterator property_with_matching_key = 3181 std::find_if(test_properties_.begin(), test_properties_.end(), 3182 internal::TestPropertyKeyIs(test_property.key())); 3183 if (property_with_matching_key == test_properties_.end()) { 3184 test_properties_.push_back(test_property); 3185 return; 3186 } 3187 property_with_matching_key->SetValue(test_property.value()); 3188} 3189 3190// Adds a failure if the key is a reserved attribute of Google Test 3191// testcase tags. Returns true if the property is valid. 3192bool TestResult::ValidateTestProperty(const TestProperty& test_property) { 3193 internal::String key(test_property.key()); 3194 if (key == "name" || key == "status" || key == "time" || key == "classname") { 3195 ADD_FAILURE() 3196 << "Reserved key used in RecordProperty(): " 3197 << key 3198 << " ('name', 'status', 'time', and 'classname' are reserved by " 3199 << GTEST_NAME_ << ")"; 3200 return false; 3201 } 3202 return true; 3203} 3204 3205// Clears the object. 3206void TestResult::Clear() { 3207 test_part_results_.clear(); 3208 test_properties_.clear(); 3209 death_test_count_ = 0; 3210 elapsed_time_ = 0; 3211} 3212 3213// Returns true iff the test failed. 3214bool TestResult::Failed() const { 3215 for (int i = 0; i < total_part_count(); ++i) { 3216 if (GetTestPartResult(i).failed()) 3217 return true; 3218 } 3219 return false; 3220} 3221 3222// Returns true iff the test part fatally failed. 3223static bool TestPartFatallyFailed(const TestPartResult& result) { 3224 return result.fatally_failed(); 3225} 3226 3227// Returns true iff the test fatally failed. 3228bool TestResult::HasFatalFailure() const { 3229 return CountIf(test_part_results_, TestPartFatallyFailed) > 0; 3230} 3231 3232// Returns true iff the test part non-fatally failed. 3233static bool TestPartNonfatallyFailed(const TestPartResult& result) { 3234 return result.nonfatally_failed(); 3235} 3236 3237// Returns true iff the test has a non-fatal failure. 3238bool TestResult::HasNonfatalFailure() const { 3239 return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0; 3240} 3241 3242// Gets the number of all test parts. This is the sum of the number 3243// of successful test parts and the number of failed test parts. 3244int TestResult::total_part_count() const { 3245 return static_cast<int>(test_part_results_.size()); 3246} 3247 3248// Returns the number of the test properties. 3249int TestResult::test_property_count() const { 3250 return static_cast<int>(test_properties_.size()); 3251} 3252 3253// class Test 3254 3255// Creates a Test object. 3256 3257// The c'tor saves the values of all Google Test flags. 3258Test::Test() 3259 : gtest_flag_saver_(new internal::GTestFlagSaver) { 3260} 3261 3262// The d'tor restores the values of all Google Test flags. 3263Test::~Test() { 3264 delete gtest_flag_saver_; 3265} 3266 3267// Sets up the test fixture. 3268// 3269// A sub-class may override this. 3270void Test::SetUp() { 3271} 3272 3273// Tears down the test fixture. 3274// 3275// A sub-class may override this. 3276void Test::TearDown() { 3277} 3278 3279// Allows user supplied key value pairs to be recorded for later output. 3280void Test::RecordProperty(const char* key, const char* value) { 3281 UnitTest::GetInstance()->RecordPropertyForCurrentTest(key, value); 3282} 3283 3284// Allows user supplied key value pairs to be recorded for later output. 3285void Test::RecordProperty(const char* key, int value) { 3286 Message value_message; 3287 value_message << value; 3288 RecordProperty(key, value_message.GetString().c_str()); 3289} 3290 3291namespace internal { 3292 3293void ReportFailureInUnknownLocation(TestPartResult::Type result_type, 3294 const String& message) { 3295 // This function is a friend of UnitTest and as such has access to 3296 // AddTestPartResult. 3297 UnitTest::GetInstance()->AddTestPartResult( 3298 result_type, 3299 NULL, // No info about the source file where the exception occurred. 3300 -1, // We have no info on which line caused the exception. 3301 message, 3302 String()); // No stack trace, either. 3303} 3304 3305} // namespace internal 3306 3307#if GTEST_OS_WINDOWS 3308// We are on Windows. 3309 3310// Adds an "exception thrown" fatal failure to the current test. 3311static void AddExceptionThrownFailure(DWORD exception_code, 3312 const char* location) { 3313 Message message; 3314 message << "Exception thrown with code 0x" << std::setbase(16) << 3315 exception_code << std::setbase(10) << " in " << location << "."; 3316 3317 internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure, 3318 message.GetString()); 3319} 3320 3321#endif // GTEST_OS_WINDOWS 3322 3323// Google Test requires all tests in the same test case to use the same test 3324// fixture class. This function checks if the current test has the 3325// same fixture class as the first test in the current test case. If 3326// yes, it returns true; otherwise it generates a Google Test failure and 3327// returns false. 3328bool Test::HasSameFixtureClass() { 3329 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); 3330 const TestCase* const test_case = impl->current_test_case(); 3331 3332 // Info about the first test in the current test case. 3333 const internal::TestInfoImpl* const first_test_info = 3334 test_case->test_info_list()[0]->impl(); 3335 const internal::TypeId first_fixture_id = first_test_info->fixture_class_id(); 3336 const char* const first_test_name = first_test_info->name(); 3337 3338 // Info about the current test. 3339 const internal::TestInfoImpl* const this_test_info = 3340 impl->current_test_info()->impl(); 3341 const internal::TypeId this_fixture_id = this_test_info->fixture_class_id(); 3342 const char* const this_test_name = this_test_info->name(); 3343 3344 if (this_fixture_id != first_fixture_id) { 3345 // Is the first test defined using TEST? 3346 const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId(); 3347 // Is this test defined using TEST? 3348 const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId(); 3349 3350 if (first_is_TEST || this_is_TEST) { 3351 // The user mixed TEST and TEST_F in this test case - we'll tell 3352 // him/her how to fix it. 3353 3354 // Gets the name of the TEST and the name of the TEST_F. Note 3355 // that first_is_TEST and this_is_TEST cannot both be true, as 3356 // the fixture IDs are different for the two tests. 3357 const char* const TEST_name = 3358 first_is_TEST ? first_test_name : this_test_name; 3359 const char* const TEST_F_name = 3360 first_is_TEST ? this_test_name : first_test_name; 3361 3362 ADD_FAILURE() 3363 << "All tests in the same test case must use the same test fixture\n" 3364 << "class, so mixing TEST_F and TEST in the same test case is\n" 3365 << "illegal. In test case " << this_test_info->test_case_name() 3366 << ",\n" 3367 << "test " << TEST_F_name << " is defined using TEST_F but\n" 3368 << "test " << TEST_name << " is defined using TEST. You probably\n" 3369 << "want to change the TEST to TEST_F or move it to another test\n" 3370 << "case."; 3371 } else { 3372 // The user defined two fixture classes with the same name in 3373 // two namespaces - we'll tell him/her how to fix it. 3374 ADD_FAILURE() 3375 << "All tests in the same test case must use the same test fixture\n" 3376 << "class. However, in test case " 3377 << this_test_info->test_case_name() << ",\n" 3378 << "you defined test " << first_test_name 3379 << " and test " << this_test_name << "\n" 3380 << "using two different test fixture classes. This can happen if\n" 3381 << "the two classes are from different namespaces or translation\n" 3382 << "units and have the same name. You should probably rename one\n" 3383 << "of the classes to put the tests into different test cases."; 3384 } 3385 return false; 3386 } 3387 3388 return true; 3389} 3390 3391// Runs the test and updates the test result. 3392void Test::Run() { 3393 if (!HasSameFixtureClass()) return; 3394 3395 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); 3396#if GTEST_HAS_SEH 3397 // Catch SEH-style exceptions. 3398 impl->os_stack_trace_getter()->UponLeavingGTest(); 3399 __try { 3400 SetUp(); 3401 } __except(internal::UnitTestOptions::GTestShouldProcessSEH( 3402 GetExceptionCode())) { 3403 AddExceptionThrownFailure(GetExceptionCode(), "SetUp()"); 3404 } 3405 3406 // We will run the test only if SetUp() had no fatal failure. 3407 if (!HasFatalFailure()) { 3408 impl->os_stack_trace_getter()->UponLeavingGTest(); 3409 __try { 3410 TestBody(); 3411 } __except(internal::UnitTestOptions::GTestShouldProcessSEH( 3412 GetExceptionCode())) { 3413 AddExceptionThrownFailure(GetExceptionCode(), "the test body"); 3414 } 3415 } 3416 3417 // However, we want to clean up as much as possible. Hence we will 3418 // always call TearDown(), even if SetUp() or the test body has 3419 // failed. 3420 impl->os_stack_trace_getter()->UponLeavingGTest(); 3421 __try { 3422 TearDown(); 3423 } __except(internal::UnitTestOptions::GTestShouldProcessSEH( 3424 GetExceptionCode())) { 3425 AddExceptionThrownFailure(GetExceptionCode(), "TearDown()"); 3426 } 3427 3428#else // We are on a compiler or platform that doesn't support SEH. 3429 impl->os_stack_trace_getter()->UponLeavingGTest(); 3430 SetUp(); 3431 3432 // We will run the test only if SetUp() was successful. 3433 if (!HasFatalFailure()) { 3434 impl->os_stack_trace_getter()->UponLeavingGTest(); 3435 TestBody(); 3436 } 3437 3438 // However, we want to clean up as much as possible. Hence we will 3439 // always call TearDown(), even if SetUp() or the test body has 3440 // failed. 3441 impl->os_stack_trace_getter()->UponLeavingGTest(); 3442 TearDown(); 3443#endif // GTEST_HAS_SEH 3444} 3445 3446 3447// Returns true iff the current test has a fatal failure. 3448bool Test::HasFatalFailure() { 3449 return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure(); 3450} 3451 3452// Returns true iff the current test has a non-fatal failure. 3453bool Test::HasNonfatalFailure() { 3454 return internal::GetUnitTestImpl()->current_test_result()-> 3455 HasNonfatalFailure(); 3456} 3457 3458// class TestInfo 3459 3460// Constructs a TestInfo object. It assumes ownership of the test factory 3461// object via impl_. 3462TestInfo::TestInfo(const char* a_test_case_name, 3463 const char* a_name, 3464 const char* a_test_case_comment, 3465 const char* a_comment, 3466 internal::TypeId fixture_class_id, 3467 internal::TestFactoryBase* factory) { 3468 impl_ = new internal::TestInfoImpl(this, a_test_case_name, a_name, 3469 a_test_case_comment, a_comment, 3470 fixture_class_id, factory); 3471} 3472 3473// Destructs a TestInfo object. 3474TestInfo::~TestInfo() { 3475 delete impl_; 3476} 3477 3478namespace internal { 3479 3480// Creates a new TestInfo object and registers it with Google Test; 3481// returns the created object. 3482// 3483// Arguments: 3484// 3485// test_case_name: name of the test case 3486// name: name of the test 3487// test_case_comment: a comment on the test case that will be included in 3488// the test output 3489// comment: a comment on the test that will be included in the 3490// test output 3491// fixture_class_id: ID of the test fixture class 3492// set_up_tc: pointer to the function that sets up the test case 3493// tear_down_tc: pointer to the function that tears down the test case 3494// factory: pointer to the factory that creates a test object. 3495// The newly created TestInfo instance will assume 3496// ownership of the factory object. 3497TestInfo* MakeAndRegisterTestInfo( 3498 const char* test_case_name, const char* name, 3499 const char* test_case_comment, const char* comment, 3500 TypeId fixture_class_id, 3501 SetUpTestCaseFunc set_up_tc, 3502 TearDownTestCaseFunc tear_down_tc, 3503 TestFactoryBase* factory) { 3504 TestInfo* const test_info = 3505 new TestInfo(test_case_name, name, test_case_comment, comment, 3506 fixture_class_id, factory); 3507 GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info); 3508 return test_info; 3509} 3510 3511#if GTEST_HAS_PARAM_TEST 3512void ReportInvalidTestCaseType(const char* test_case_name, 3513 const char* file, int line) { 3514 Message errors; 3515 errors 3516 << "Attempted redefinition of test case " << test_case_name << ".\n" 3517 << "All tests in the same test case must use the same test fixture\n" 3518 << "class. However, in test case " << test_case_name << ", you tried\n" 3519 << "to define a test using a fixture class different from the one\n" 3520 << "used earlier. This can happen if the two fixture classes are\n" 3521 << "from different namespaces and have the same name. You should\n" 3522 << "probably rename one of the classes to put the tests into different\n" 3523 << "test cases."; 3524 3525 fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(), 3526 errors.GetString().c_str()); 3527} 3528#endif // GTEST_HAS_PARAM_TEST 3529 3530} // namespace internal 3531 3532// Returns the test case name. 3533const char* TestInfo::test_case_name() const { 3534 return impl_->test_case_name(); 3535} 3536 3537// Returns the test name. 3538const char* TestInfo::name() const { 3539 return impl_->name(); 3540} 3541 3542// Returns the test case comment. 3543const char* TestInfo::test_case_comment() const { 3544 return impl_->test_case_comment(); 3545} 3546 3547// Returns the test comment. 3548const char* TestInfo::comment() const { 3549 return impl_->comment(); 3550} 3551 3552// Returns true if this test should run. 3553bool TestInfo::should_run() const { return impl_->should_run(); } 3554 3555// Returns true if this test matches the user-specified filter. 3556bool TestInfo::matches_filter() const { return impl_->matches_filter(); } 3557 3558// Returns the result of the test. 3559const TestResult* TestInfo::result() const { return impl_->result(); } 3560 3561// Increments the number of death tests encountered in this test so 3562// far. 3563int TestInfo::increment_death_test_count() { 3564 return impl_->result()->increment_death_test_count(); 3565} 3566 3567namespace { 3568 3569// A predicate that checks the test name of a TestInfo against a known 3570// value. 3571// 3572// This is used for implementation of the TestCase class only. We put 3573// it in the anonymous namespace to prevent polluting the outer 3574// namespace. 3575// 3576// TestNameIs is copyable. 3577class TestNameIs { 3578 public: 3579 // Constructor. 3580 // 3581 // TestNameIs has NO default constructor. 3582 explicit TestNameIs(const char* name) 3583 : name_(name) {} 3584 3585 // Returns true iff the test name of test_info matches name_. 3586 bool operator()(const TestInfo * test_info) const { 3587 return test_info && internal::String(test_info->name()).Compare(name_) == 0; 3588 } 3589 3590 private: 3591 internal::String name_; 3592}; 3593 3594} // namespace 3595 3596namespace internal { 3597 3598// This method expands all parameterized tests registered with macros TEST_P 3599// and INSTANTIATE_TEST_CASE_P into regular tests and registers those. 3600// This will be done just once during the program runtime. 3601void UnitTestImpl::RegisterParameterizedTests() { 3602#if GTEST_HAS_PARAM_TEST 3603 if (!parameterized_tests_registered_) { 3604 parameterized_test_registry_.RegisterTests(); 3605 parameterized_tests_registered_ = true; 3606 } 3607#endif 3608} 3609 3610// Creates the test object, runs it, records its result, and then 3611// deletes it. 3612void TestInfoImpl::Run() { 3613 if (!should_run_) return; 3614 3615 // Tells UnitTest where to store test result. 3616 UnitTestImpl* const impl = internal::GetUnitTestImpl(); 3617 impl->set_current_test_info(parent_); 3618 3619 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater(); 3620 3621 // Notifies the unit test event listeners that a test is about to start. 3622 repeater->OnTestStart(*parent_); 3623 3624 const TimeInMillis start = GetTimeInMillis(); 3625 3626 impl->os_stack_trace_getter()->UponLeavingGTest(); 3627#if GTEST_HAS_SEH 3628 // Catch SEH-style exceptions. 3629 Test* test = NULL; 3630 3631 __try { 3632 // Creates the test object. 3633 test = factory_->CreateTest(); 3634 } __except(internal::UnitTestOptions::GTestShouldProcessSEH( 3635 GetExceptionCode())) { 3636 AddExceptionThrownFailure(GetExceptionCode(), 3637 "the test fixture's constructor"); 3638 return; 3639 } 3640#else // We are on a compiler or platform that doesn't support SEH. 3641 3642 // TODO(wan): If test->Run() throws, test won't be deleted. This is 3643 // not a problem now as we don't use exceptions. If we were to 3644 // enable exceptions, we should revise the following to be 3645 // exception-safe. 3646 3647 // Creates the test object. 3648 Test* test = factory_->CreateTest(); 3649#endif // GTEST_HAS_SEH 3650 3651 // Runs the test only if the constructor of the test fixture didn't 3652 // generate a fatal failure. 3653 if (!Test::HasFatalFailure()) { 3654 test->Run(); 3655 } 3656 3657 // Deletes the test object. 3658 impl->os_stack_trace_getter()->UponLeavingGTest(); 3659 delete test; 3660 test = NULL; 3661 3662 result_.set_elapsed_time(GetTimeInMillis() - start); 3663 3664 // Notifies the unit test event listener that a test has just finished. 3665 repeater->OnTestEnd(*parent_); 3666 3667 // Tells UnitTest to stop associating assertion results to this 3668 // test. 3669 impl->set_current_test_info(NULL); 3670} 3671 3672} // namespace internal 3673 3674// class TestCase 3675 3676// Gets the number of successful tests in this test case. 3677int TestCase::successful_test_count() const { 3678 return CountIf(test_info_list_, TestPassed); 3679} 3680 3681// Gets the number of failed tests in this test case. 3682int TestCase::failed_test_count() const { 3683 return CountIf(test_info_list_, TestFailed); 3684} 3685 3686int TestCase::disabled_test_count() const { 3687 return CountIf(test_info_list_, TestDisabled); 3688} 3689 3690// Get the number of tests in this test case that should run. 3691int TestCase::test_to_run_count() const { 3692 return CountIf(test_info_list_, ShouldRunTest); 3693} 3694 3695// Gets the number of all tests. 3696int TestCase::total_test_count() const { 3697 return static_cast<int>(test_info_list_.size()); 3698} 3699 3700// Creates a TestCase with the given name. 3701// 3702// Arguments: 3703// 3704// name: name of the test case 3705// set_up_tc: pointer to the function that sets up the test case 3706// tear_down_tc: pointer to the function that tears down the test case 3707TestCase::TestCase(const char* a_name, const char* a_comment, 3708 Test::SetUpTestCaseFunc set_up_tc, 3709 Test::TearDownTestCaseFunc tear_down_tc) 3710 : name_(a_name), 3711 comment_(a_comment), 3712 set_up_tc_(set_up_tc), 3713 tear_down_tc_(tear_down_tc), 3714 should_run_(false), 3715 elapsed_time_(0) { 3716} 3717 3718// Destructor of TestCase. 3719TestCase::~TestCase() { 3720 // Deletes every Test in the collection. 3721 ForEach(test_info_list_, internal::Delete<TestInfo>); 3722} 3723 3724// Returns the i-th test among all the tests. i can range from 0 to 3725// total_test_count() - 1. If i is not in that range, returns NULL. 3726const TestInfo* TestCase::GetTestInfo(int i) const { 3727 const int index = GetElementOr(test_indices_, i, -1); 3728 return index < 0 ? NULL : test_info_list_[index]; 3729} 3730 3731// Returns the i-th test among all the tests. i can range from 0 to 3732// total_test_count() - 1. If i is not in that range, returns NULL. 3733TestInfo* TestCase::GetMutableTestInfo(int i) { 3734 const int index = GetElementOr(test_indices_, i, -1); 3735 return index < 0 ? NULL : test_info_list_[index]; 3736} 3737 3738// Adds a test to this test case. Will delete the test upon 3739// destruction of the TestCase object. 3740void TestCase::AddTestInfo(TestInfo * test_info) { 3741 test_info_list_.push_back(test_info); 3742 test_indices_.push_back(static_cast<int>(test_indices_.size())); 3743} 3744 3745// Runs every test in this TestCase. 3746void TestCase::Run() { 3747 if (!should_run_) return; 3748 3749 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); 3750 impl->set_current_test_case(this); 3751 3752 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater(); 3753 3754 repeater->OnTestCaseStart(*this); 3755 impl->os_stack_trace_getter()->UponLeavingGTest(); 3756 set_up_tc_(); 3757 3758 const internal::TimeInMillis start = internal::GetTimeInMillis(); 3759 for (int i = 0; i < total_test_count(); i++) { 3760 GetMutableTestInfo(i)->impl()->Run(); 3761 } 3762 elapsed_time_ = internal::GetTimeInMillis() - start; 3763 3764 impl->os_stack_trace_getter()->UponLeavingGTest(); 3765 tear_down_tc_(); 3766 repeater->OnTestCaseEnd(*this); 3767 impl->set_current_test_case(NULL); 3768} 3769 3770// Clears the results of all tests in this test case. 3771void TestCase::ClearResult() { 3772 ForEach(test_info_list_, internal::TestInfoImpl::ClearTestResult); 3773} 3774 3775// Returns true iff test passed. 3776bool TestCase::TestPassed(const TestInfo * test_info) { 3777 const internal::TestInfoImpl* const impl = test_info->impl(); 3778 return impl->should_run() && impl->result()->Passed(); 3779} 3780 3781// Returns true iff test failed. 3782bool TestCase::TestFailed(const TestInfo * test_info) { 3783 const internal::TestInfoImpl* const impl = test_info->impl(); 3784 return impl->should_run() && impl->result()->Failed(); 3785} 3786 3787// Returns true iff test is disabled. 3788bool TestCase::TestDisabled(const TestInfo * test_info) { 3789 return test_info->impl()->is_disabled(); 3790} 3791 3792// Returns true if the given test should run. 3793bool TestCase::ShouldRunTest(const TestInfo *test_info) { 3794 return test_info->impl()->should_run(); 3795} 3796 3797// Shuffles the tests in this test case. 3798void TestCase::ShuffleTests(internal::Random* random) { 3799 Shuffle(random, &test_indices_); 3800} 3801 3802// Restores the test order to before the first shuffle. 3803void TestCase::UnshuffleTests() { 3804 for (size_t i = 0; i < test_indices_.size(); i++) { 3805 test_indices_[i] = static_cast<int>(i); 3806 } 3807} 3808 3809// Formats a countable noun. Depending on its quantity, either the 3810// singular form or the plural form is used. e.g. 3811// 3812// FormatCountableNoun(1, "formula", "formuli") returns "1 formula". 3813// FormatCountableNoun(5, "book", "books") returns "5 books". 3814static internal::String FormatCountableNoun(int count, 3815 const char * singular_form, 3816 const char * plural_form) { 3817 return internal::String::Format("%d %s", count, 3818 count == 1 ? singular_form : plural_form); 3819} 3820 3821// Formats the count of tests. 3822static internal::String FormatTestCount(int test_count) { 3823 return FormatCountableNoun(test_count, "test", "tests"); 3824} 3825 3826// Formats the count of test cases. 3827static internal::String FormatTestCaseCount(int test_case_count) { 3828 return FormatCountableNoun(test_case_count, "test case", "test cases"); 3829} 3830 3831// Converts a TestPartResult::Type enum to human-friendly string 3832// representation. Both kNonFatalFailure and kFatalFailure are translated 3833// to "Failure", as the user usually doesn't care about the difference 3834// between the two when viewing the test result. 3835static const char * TestPartResultTypeToString(TestPartResult::Type type) { 3836 switch (type) { 3837 case TestPartResult::kSuccess: 3838 return "Success"; 3839 3840 case TestPartResult::kNonFatalFailure: 3841 case TestPartResult::kFatalFailure: 3842#ifdef _MSC_VER 3843 return "error: "; 3844#else 3845 return "Failure\n"; 3846#endif 3847 } 3848 3849 return "Unknown result type"; 3850} 3851 3852// Prints a TestPartResult to a String. 3853static internal::String PrintTestPartResultToString( 3854 const TestPartResult& test_part_result) { 3855 return (Message() 3856 << internal::FormatFileLocation(test_part_result.file_name(), 3857 test_part_result.line_number()) 3858 << " " << TestPartResultTypeToString(test_part_result.type()) 3859 << test_part_result.message()).GetString(); 3860} 3861 3862// Prints a TestPartResult. 3863static void PrintTestPartResult(const TestPartResult& test_part_result) { 3864 const internal::String& result = 3865 PrintTestPartResultToString(test_part_result); 3866 printf("%s\n", result.c_str()); 3867 fflush(stdout); 3868 // If the test program runs in Visual Studio or a debugger, the 3869 // following statements add the test part result message to the Output 3870 // window such that the user can double-click on it to jump to the 3871 // corresponding source code location; otherwise they do nothing. 3872#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE 3873 // We don't call OutputDebugString*() on Windows Mobile, as printing 3874 // to stdout is done by OutputDebugString() there already - we don't 3875 // want the same message printed twice. 3876 ::OutputDebugStringA(result.c_str()); 3877 ::OutputDebugStringA("\n"); 3878#endif 3879} 3880 3881// class PrettyUnitTestResultPrinter 3882 3883namespace internal { 3884 3885enum GTestColor { 3886 COLOR_DEFAULT, 3887 COLOR_RED, 3888 COLOR_GREEN, 3889 COLOR_YELLOW 3890}; 3891 3892#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE 3893 3894// Returns the character attribute for the given color. 3895WORD GetColorAttribute(GTestColor color) { 3896 switch (color) { 3897 case COLOR_RED: return FOREGROUND_RED; 3898 case COLOR_GREEN: return FOREGROUND_GREEN; 3899 case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN; 3900 default: return 0; 3901 } 3902} 3903 3904#else 3905 3906// Returns the ANSI color code for the given color. COLOR_DEFAULT is 3907// an invalid input. 3908const char* GetAnsiColorCode(GTestColor color) { 3909 switch (color) { 3910 case COLOR_RED: return "1"; 3911 case COLOR_GREEN: return "2"; 3912 case COLOR_YELLOW: return "3"; 3913 default: return NULL; 3914 }; 3915} 3916 3917#endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE 3918 3919// Returns true iff Google Test should use colors in the output. 3920bool ShouldUseColor(bool stdout_is_tty) { 3921 const char* const gtest_color = GTEST_FLAG(color).c_str(); 3922 3923 if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) { 3924#if GTEST_OS_WINDOWS 3925 // On Windows the TERM variable is usually not set, but the 3926 // console there does support colors. 3927 return stdout_is_tty; 3928#else 3929 // On non-Windows platforms, we rely on the TERM variable. 3930 const char* const term = posix::GetEnv("TERM"); 3931 const bool term_supports_color = 3932 String::CStringEquals(term, "xterm") || 3933 String::CStringEquals(term, "xterm-color") || 3934 String::CStringEquals(term, "xterm-256color") || 3935 String::CStringEquals(term, "linux") || 3936 String::CStringEquals(term, "cygwin"); 3937 return stdout_is_tty && term_supports_color; 3938#endif // GTEST_OS_WINDOWS 3939 } 3940 3941 return String::CaseInsensitiveCStringEquals(gtest_color, "yes") || 3942 String::CaseInsensitiveCStringEquals(gtest_color, "true") || 3943 String::CaseInsensitiveCStringEquals(gtest_color, "t") || 3944 String::CStringEquals(gtest_color, "1"); 3945 // We take "yes", "true", "t", and "1" as meaning "yes". If the 3946 // value is neither one of these nor "auto", we treat it as "no" to 3947 // be conservative. 3948} 3949 3950// Helpers for printing colored strings to stdout. Note that on Windows, we 3951// cannot simply emit special characters and have the terminal change colors. 3952// This routine must actually emit the characters rather than return a string 3953// that would be colored when printed, as can be done on Linux. 3954void ColoredPrintf(GTestColor color, const char* fmt, ...) { 3955 va_list args; 3956 va_start(args, fmt); 3957 3958#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS 3959 const bool use_color = false; 3960#else 3961 static const bool in_color_mode = 3962 ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0); 3963 const bool use_color = in_color_mode && (color != COLOR_DEFAULT); 3964#endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS 3965 // The '!= 0' comparison is necessary to satisfy MSVC 7.1. 3966 3967 if (!use_color) { 3968 vprintf(fmt, args); 3969 va_end(args); 3970 return; 3971 } 3972 3973#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE 3974 const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE); 3975 3976 // Gets the current text color. 3977 CONSOLE_SCREEN_BUFFER_INFO buffer_info; 3978 GetConsoleScreenBufferInfo(stdout_handle, &buffer_info); 3979 const WORD old_color_attrs = buffer_info.wAttributes; 3980 3981 // We need to flush the stream buffers into the console before each 3982 // SetConsoleTextAttribute call lest it affect the text that is already 3983 // printed but has not yet reached the console. 3984 fflush(stdout); 3985 SetConsoleTextAttribute(stdout_handle, 3986 GetColorAttribute(color) | FOREGROUND_INTENSITY); 3987 vprintf(fmt, args); 3988 3989 fflush(stdout); 3990 // Restores the text color. 3991 SetConsoleTextAttribute(stdout_handle, old_color_attrs); 3992#else 3993 printf("\033[0;3%sm", GetAnsiColorCode(color)); 3994 vprintf(fmt, args); 3995 printf("\033[m"); // Resets the terminal to default. 3996#endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE 3997 va_end(args); 3998} 3999 4000// This class implements the TestEventListener interface. 4001// 4002// Class PrettyUnitTestResultPrinter is copyable. 4003class PrettyUnitTestResultPrinter : public TestEventListener { 4004 public: 4005 PrettyUnitTestResultPrinter() {} 4006 static void PrintTestName(const char * test_case, const char * test) { 4007 printf("%s.%s", test_case, test); 4008 } 4009 4010 // The following methods override what's in the TestEventListener class. 4011 virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {} 4012 virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration); 4013 virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test); 4014 virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {} 4015 virtual void OnTestCaseStart(const TestCase& test_case); 4016 virtual void OnTestStart(const TestInfo& test_info); 4017 virtual void OnTestPartResult(const TestPartResult& result); 4018 virtual void OnTestEnd(const TestInfo& test_info); 4019 virtual void OnTestCaseEnd(const TestCase& test_case); 4020 virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test); 4021 virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {} 4022 virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration); 4023 virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {} 4024 4025 private: 4026 static void PrintFailedTests(const UnitTest& unit_test); 4027 4028 internal::String test_case_name_; 4029}; 4030 4031 // Fired before each iteration of tests starts. 4032void PrettyUnitTestResultPrinter::OnTestIterationStart( 4033 const UnitTest& unit_test, int iteration) { 4034 if (GTEST_FLAG(repeat) != 1) 4035 printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1); 4036 4037 const char* const filter = GTEST_FLAG(filter).c_str(); 4038 4039 // Prints the filter if it's not *. This reminds the user that some 4040 // tests may be skipped. 4041 if (!internal::String::CStringEquals(filter, kUniversalFilter)) { 4042 ColoredPrintf(COLOR_YELLOW, 4043 "Note: %s filter = %s\n", GTEST_NAME_, filter); 4044 } 4045 4046 if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) { 4047 ColoredPrintf(COLOR_YELLOW, 4048 "Note: This is test shard %s of %s.\n", 4049 internal::posix::GetEnv(kTestShardIndex), 4050 internal::posix::GetEnv(kTestTotalShards)); 4051 } 4052 4053 if (GTEST_FLAG(shuffle)) { 4054 ColoredPrintf(COLOR_YELLOW, 4055 "Note: Randomizing tests' orders with a seed of %d .\n", 4056 unit_test.random_seed()); 4057 } 4058 4059 ColoredPrintf(COLOR_GREEN, "[==========] "); 4060 printf("Running %s from %s.\n", 4061 FormatTestCount(unit_test.test_to_run_count()).c_str(), 4062 FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str()); 4063 fflush(stdout); 4064} 4065 4066void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart( 4067 const UnitTest& /*unit_test*/) { 4068 ColoredPrintf(COLOR_GREEN, "[----------] "); 4069 printf("Global test environment set-up.\n"); 4070 fflush(stdout); 4071} 4072 4073void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) { 4074 test_case_name_ = test_case.name(); 4075 const internal::String counts = 4076 FormatCountableNoun(test_case.test_to_run_count(), "test", "tests"); 4077 ColoredPrintf(COLOR_GREEN, "[----------] "); 4078 printf("%s from %s", counts.c_str(), test_case_name_.c_str()); 4079 if (test_case.comment()[0] == '\0') { 4080 printf("\n"); 4081 } else { 4082 printf(", where %s\n", test_case.comment()); 4083 } 4084 fflush(stdout); 4085} 4086 4087void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) { 4088 ColoredPrintf(COLOR_GREEN, "[ RUN ] "); 4089 PrintTestName(test_case_name_.c_str(), test_info.name()); 4090 if (test_info.comment()[0] == '\0') { 4091 printf("\n"); 4092 } else { 4093 printf(", where %s\n", test_info.comment()); 4094 } 4095 fflush(stdout); 4096} 4097 4098// Called after an assertion failure. 4099void PrettyUnitTestResultPrinter::OnTestPartResult( 4100 const TestPartResult& result) { 4101 // If the test part succeeded, we don't need to do anything. 4102 if (result.type() == TestPartResult::kSuccess) 4103 return; 4104 4105 // Print failure message from the assertion (e.g. expected this and got that). 4106 PrintTestPartResult(result); 4107 fflush(stdout); 4108} 4109 4110void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) { 4111 if (test_info.result()->Passed()) { 4112 ColoredPrintf(COLOR_GREEN, "[ OK ] "); 4113 } else { 4114 ColoredPrintf(COLOR_RED, "[ FAILED ] "); 4115 } 4116 PrintTestName(test_case_name_.c_str(), test_info.name()); 4117 if (GTEST_FLAG(print_time)) { 4118 printf(" (%s ms)\n", internal::StreamableToString( 4119 test_info.result()->elapsed_time()).c_str()); 4120 } else { 4121 printf("\n"); 4122 } 4123 fflush(stdout); 4124} 4125 4126void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) { 4127 if (!GTEST_FLAG(print_time)) return; 4128 4129 test_case_name_ = test_case.name(); 4130 const internal::String counts = 4131 FormatCountableNoun(test_case.test_to_run_count(), "test", "tests"); 4132 ColoredPrintf(COLOR_GREEN, "[----------] "); 4133 printf("%s from %s (%s ms total)\n\n", 4134 counts.c_str(), test_case_name_.c_str(), 4135 internal::StreamableToString(test_case.elapsed_time()).c_str()); 4136 fflush(stdout); 4137} 4138 4139void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart( 4140 const UnitTest& /*unit_test*/) { 4141 ColoredPrintf(COLOR_GREEN, "[----------] "); 4142 printf("Global test environment tear-down\n"); 4143 fflush(stdout); 4144} 4145 4146// Internal helper for printing the list of failed tests. 4147void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) { 4148 const int failed_test_count = unit_test.failed_test_count(); 4149 if (failed_test_count == 0) { 4150 return; 4151 } 4152 4153 for (int i = 0; i < unit_test.total_test_case_count(); ++i) { 4154 const TestCase& test_case = *unit_test.GetTestCase(i); 4155 if (!test_case.should_run() || (test_case.failed_test_count() == 0)) { 4156 continue; 4157 } 4158 for (int j = 0; j < test_case.total_test_count(); ++j) { 4159 const TestInfo& test_info = *test_case.GetTestInfo(j); 4160 if (!test_info.should_run() || test_info.result()->Passed()) { 4161 continue; 4162 } 4163 ColoredPrintf(COLOR_RED, "[ FAILED ] "); 4164 printf("%s.%s", test_case.name(), test_info.name()); 4165 if (test_case.comment()[0] != '\0' || 4166 test_info.comment()[0] != '\0') { 4167 printf(", where %s", test_case.comment()); 4168 if (test_case.comment()[0] != '\0' && 4169 test_info.comment()[0] != '\0') { 4170 printf(" and "); 4171 } 4172 } 4173 printf("%s\n", test_info.comment()); 4174 } 4175 } 4176} 4177 4178 void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, 4179 int /*iteration*/) { 4180 ColoredPrintf(COLOR_GREEN, "[==========] "); 4181 printf("%s from %s ran.", 4182 FormatTestCount(unit_test.test_to_run_count()).c_str(), 4183 FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str()); 4184 if (GTEST_FLAG(print_time)) { 4185 printf(" (%s ms total)", 4186 internal::StreamableToString(unit_test.elapsed_time()).c_str()); 4187 } 4188 printf("\n"); 4189 ColoredPrintf(COLOR_GREEN, "[ PASSED ] "); 4190 printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str()); 4191 4192 int num_failures = unit_test.failed_test_count(); 4193 if (!unit_test.Passed()) { 4194 const int failed_test_count = unit_test.failed_test_count(); 4195 ColoredPrintf(COLOR_RED, "[ FAILED ] "); 4196 printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str()); 4197 PrintFailedTests(unit_test); 4198 printf("\n%2d FAILED %s\n", num_failures, 4199 num_failures == 1 ? "TEST" : "TESTS"); 4200 } 4201 4202 int num_disabled = unit_test.disabled_test_count(); 4203 if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) { 4204 if (!num_failures) { 4205 printf("\n"); // Add a spacer if no FAILURE banner is displayed. 4206 } 4207 ColoredPrintf(COLOR_YELLOW, 4208 " YOU HAVE %d DISABLED %s\n\n", 4209 num_disabled, 4210 num_disabled == 1 ? "TEST" : "TESTS"); 4211 } 4212 // Ensure that Google Test output is printed before, e.g., heapchecker output. 4213 fflush(stdout); 4214} 4215 4216// End PrettyUnitTestResultPrinter 4217 4218// class TestEventRepeater 4219// 4220// This class forwards events to other event listeners. 4221class TestEventRepeater : public TestEventListener { 4222 public: 4223 TestEventRepeater() : forwarding_enabled_(true) {} 4224 virtual ~TestEventRepeater(); 4225 void Append(TestEventListener *listener); 4226 TestEventListener* Release(TestEventListener* listener); 4227 4228 // Controls whether events will be forwarded to listeners_. Set to false 4229 // in death test child processes. 4230 bool forwarding_enabled() const { return forwarding_enabled_; } 4231 void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; } 4232 4233 virtual void OnTestProgramStart(const UnitTest& unit_test); 4234 virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration); 4235 virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test); 4236 virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test); 4237 virtual void OnTestCaseStart(const TestCase& test_case); 4238 virtual void OnTestStart(const TestInfo& test_info); 4239 virtual void OnTestPartResult(const TestPartResult& result); 4240 virtual void OnTestEnd(const TestInfo& test_info); 4241 virtual void OnTestCaseEnd(const TestCase& test_case); 4242 virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test); 4243 virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test); 4244 virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration); 4245 virtual void OnTestProgramEnd(const UnitTest& unit_test); 4246 4247 private: 4248 // Controls whether events will be forwarded to listeners_. Set to false 4249 // in death test child processes. 4250 bool forwarding_enabled_; 4251 // The list of listeners that receive events. 4252 std::vector<TestEventListener*> listeners_; 4253 4254 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater); 4255}; 4256 4257TestEventRepeater::~TestEventRepeater() { 4258 ForEach(listeners_, Delete<TestEventListener>); 4259} 4260 4261void TestEventRepeater::Append(TestEventListener *listener) { 4262 listeners_.push_back(listener); 4263} 4264 4265// TODO(vladl@google.com): Factor the search functionality into Vector::Find. 4266TestEventListener* TestEventRepeater::Release(TestEventListener *listener) { 4267 for (size_t i = 0; i < listeners_.size(); ++i) { 4268 if (listeners_[i] == listener) { 4269 listeners_.erase(listeners_.begin() + i); 4270 return listener; 4271 } 4272 } 4273 4274 return NULL; 4275} 4276 4277// Since most methods are very similar, use macros to reduce boilerplate. 4278// This defines a member that forwards the call to all listeners. 4279#define GTEST_REPEATER_METHOD_(Name, Type) \ 4280void TestEventRepeater::Name(const Type& parameter) { \ 4281 if (forwarding_enabled_) { \ 4282 for (size_t i = 0; i < listeners_.size(); i++) { \ 4283 listeners_[i]->Name(parameter); \ 4284 } \ 4285 } \ 4286} 4287// This defines a member that forwards the call to all listeners in reverse 4288// order. 4289#define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \ 4290void TestEventRepeater::Name(const Type& parameter) { \ 4291 if (forwarding_enabled_) { \ 4292 for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \ 4293 listeners_[i]->Name(parameter); \ 4294 } \ 4295 } \ 4296} 4297 4298GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest) 4299GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest) 4300GTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase) 4301GTEST_REPEATER_METHOD_(OnTestStart, TestInfo) 4302GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult) 4303GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest) 4304GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest) 4305GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest) 4306GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo) 4307GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestCase) 4308GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest) 4309 4310#undef GTEST_REPEATER_METHOD_ 4311#undef GTEST_REVERSE_REPEATER_METHOD_ 4312 4313void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test, 4314 int iteration) { 4315 if (forwarding_enabled_) { 4316 for (size_t i = 0; i < listeners_.size(); i++) { 4317 listeners_[i]->OnTestIterationStart(unit_test, iteration); 4318 } 4319 } 4320} 4321 4322void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test, 4323 int iteration) { 4324 if (forwarding_enabled_) { 4325 for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { 4326 listeners_[i]->OnTestIterationEnd(unit_test, iteration); 4327 } 4328 } 4329} 4330 4331// End TestEventRepeater 4332 4333// This class generates an XML output file. 4334class XmlUnitTestResultPrinter : public EmptyTestEventListener { 4335 public: 4336 explicit XmlUnitTestResultPrinter(const char* output_file); 4337 4338 virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration); 4339 4340 private: 4341 // Is c a whitespace character that is normalized to a space character 4342 // when it appears in an XML attribute value? 4343 static bool IsNormalizableWhitespace(char c) { 4344 return c == 0x9 || c == 0xA || c == 0xD; 4345 } 4346 4347 // May c appear in a well-formed XML document? 4348 static bool IsValidXmlCharacter(char c) { 4349 return IsNormalizableWhitespace(c) || c >= 0x20; 4350 } 4351 4352 // Returns an XML-escaped copy of the input string str. If 4353 // is_attribute is true, the text is meant to appear as an attribute 4354 // value, and normalizable whitespace is preserved by replacing it 4355 // with character references. 4356 static String EscapeXml(const char* str, bool is_attribute); 4357 4358 // Returns the given string with all characters invalid in XML removed. 4359 static String RemoveInvalidXmlCharacters(const char* str); 4360 4361 // Convenience wrapper around EscapeXml when str is an attribute value. 4362 static String EscapeXmlAttribute(const char* str) { 4363 return EscapeXml(str, true); 4364 } 4365 4366 // Convenience wrapper around EscapeXml when str is not an attribute value. 4367 static String EscapeXmlText(const char* str) { return EscapeXml(str, false); } 4368 4369 // Streams an XML CDATA section, escaping invalid CDATA sequences as needed. 4370 static void OutputXmlCDataSection(::std::ostream* stream, const char* data); 4371 4372 // Streams an XML representation of a TestInfo object. 4373 static void OutputXmlTestInfo(::std::ostream* stream, 4374 const char* test_case_name, 4375 const TestInfo& test_info); 4376 4377 // Prints an XML representation of a TestCase object 4378 static void PrintXmlTestCase(FILE* out, const TestCase& test_case); 4379 4380 // Prints an XML summary of unit_test to output stream out. 4381 static void PrintXmlUnitTest(FILE* out, const UnitTest& unit_test); 4382 4383 // Produces a string representing the test properties in a result as space 4384 // delimited XML attributes based on the property key="value" pairs. 4385 // When the String is not empty, it includes a space at the beginning, 4386 // to delimit this attribute from prior attributes. 4387 static String TestPropertiesAsXmlAttributes(const TestResult& result); 4388 4389 // The output file. 4390 const String output_file_; 4391 4392 GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter); 4393}; 4394 4395// Creates a new XmlUnitTestResultPrinter. 4396XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file) 4397 : output_file_(output_file) { 4398 if (output_file_.c_str() == NULL || output_file_.empty()) { 4399 fprintf(stderr, "XML output file may not be null\n"); 4400 fflush(stderr); 4401 exit(EXIT_FAILURE); 4402 } 4403} 4404 4405// Called after the unit test ends. 4406void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, 4407 int /*iteration*/) { 4408 FILE* xmlout = NULL; 4409 FilePath output_file(output_file_); 4410 FilePath output_dir(output_file.RemoveFileName()); 4411 4412 if (output_dir.CreateDirectoriesRecursively()) { 4413 xmlout = posix::FOpen(output_file_.c_str(), "w"); 4414 } 4415 if (xmlout == NULL) { 4416 // TODO(wan): report the reason of the failure. 4417 // 4418 // We don't do it for now as: 4419 // 4420 // 1. There is no urgent need for it. 4421 // 2. It's a bit involved to make the errno variable thread-safe on 4422 // all three operating systems (Linux, Windows, and Mac OS). 4423 // 3. To interpret the meaning of errno in a thread-safe way, 4424 // we need the strerror_r() function, which is not available on 4425 // Windows. 4426 fprintf(stderr, 4427 "Unable to open file \"%s\"\n", 4428 output_file_.c_str()); 4429 fflush(stderr); 4430 exit(EXIT_FAILURE); 4431 } 4432 PrintXmlUnitTest(xmlout, unit_test); 4433 fclose(xmlout); 4434} 4435 4436// Returns an XML-escaped copy of the input string str. If is_attribute 4437// is true, the text is meant to appear as an attribute value, and 4438// normalizable whitespace is preserved by replacing it with character 4439// references. 4440// 4441// Invalid XML characters in str, if any, are stripped from the output. 4442// It is expected that most, if not all, of the text processed by this 4443// module will consist of ordinary English text. 4444// If this module is ever modified to produce version 1.1 XML output, 4445// most invalid characters can be retained using character references. 4446// TODO(wan): It might be nice to have a minimally invasive, human-readable 4447// escaping scheme for invalid characters, rather than dropping them. 4448String XmlUnitTestResultPrinter::EscapeXml(const char* str, bool is_attribute) { 4449 Message m; 4450 4451 if (str != NULL) { 4452 for (const char* src = str; *src; ++src) { 4453 switch (*src) { 4454 case '<': 4455 m << "<"; 4456 break; 4457 case '>': 4458 m << ">"; 4459 break; 4460 case '&': 4461 m << "&"; 4462 break; 4463 case '\'': 4464 if (is_attribute) 4465 m << "'"; 4466 else 4467 m << '\''; 4468 break; 4469 case '"': 4470 if (is_attribute) 4471 m << """; 4472 else 4473 m << '"'; 4474 break; 4475 default: 4476 if (IsValidXmlCharacter(*src)) { 4477 if (is_attribute && IsNormalizableWhitespace(*src)) 4478 m << String::Format("&#x%02X;", unsigned(*src)); 4479 else 4480 m << *src; 4481 } 4482 break; 4483 } 4484 } 4485 } 4486 4487 return m.GetString(); 4488} 4489 4490// Returns the given string with all characters invalid in XML removed. 4491// Currently invalid characters are dropped from the string. An 4492// alternative is to replace them with certain characters such as . or ?. 4493String XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(const char* str) { 4494 char* const output = new char[strlen(str) + 1]; 4495 char* appender = output; 4496 for (char ch = *str; ch != '\0'; ch = *++str) 4497 if (IsValidXmlCharacter(ch)) 4498 *appender++ = ch; 4499 *appender = '\0'; 4500 4501 String ret_value(output); 4502 delete[] output; 4503 return ret_value; 4504} 4505 4506// The following routines generate an XML representation of a UnitTest 4507// object. 4508// 4509// This is how Google Test concepts map to the DTD: 4510// 4511// <testsuites name="AllTests"> <-- corresponds to a UnitTest object 4512// <testsuite name="testcase-name"> <-- corresponds to a TestCase object 4513// <testcase name="test-name"> <-- corresponds to a TestInfo object 4514// <failure message="...">...</failure> 4515// <failure message="...">...</failure> 4516// <failure message="...">...</failure> 4517// <-- individual assertion failures 4518// </testcase> 4519// </testsuite> 4520// </testsuites> 4521 4522// Formats the given time in milliseconds as seconds. 4523std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) { 4524 ::std::stringstream ss; 4525 ss << ms/1000.0; 4526 return ss.str(); 4527} 4528 4529// Streams an XML CDATA section, escaping invalid CDATA sequences as needed. 4530void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream, 4531 const char* data) { 4532 const char* segment = data; 4533 *stream << "<![CDATA["; 4534 for (;;) { 4535 const char* const next_segment = strstr(segment, "]]>"); 4536 if (next_segment != NULL) { 4537 stream->write( 4538 segment, static_cast<std::streamsize>(next_segment - segment)); 4539 *stream << "]]>]]><![CDATA["; 4540 segment = next_segment + strlen("]]>"); 4541 } else { 4542 *stream << segment; 4543 break; 4544 } 4545 } 4546 *stream << "]]>"; 4547} 4548 4549// Prints an XML representation of a TestInfo object. 4550// TODO(wan): There is also value in printing properties with the plain printer. 4551void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream, 4552 const char* test_case_name, 4553 const TestInfo& test_info) { 4554 const TestResult& result = *test_info.result(); 4555 *stream << " <testcase name=\"" 4556 << EscapeXmlAttribute(test_info.name()).c_str() 4557 << "\" status=\"" 4558 << (test_info.should_run() ? "run" : "notrun") 4559 << "\" time=\"" 4560 << FormatTimeInMillisAsSeconds(result.elapsed_time()) 4561 << "\" classname=\"" << EscapeXmlAttribute(test_case_name).c_str() 4562 << "\"" << TestPropertiesAsXmlAttributes(result).c_str(); 4563 4564 int failures = 0; 4565 for (int i = 0; i < result.total_part_count(); ++i) { 4566 const TestPartResult& part = result.GetTestPartResult(i); 4567 if (part.failed()) { 4568 if (++failures == 1) 4569 *stream << ">\n"; 4570 *stream << " <failure message=\"" 4571 << EscapeXmlAttribute(part.summary()).c_str() 4572 << "\" type=\"\">"; 4573 const String message = RemoveInvalidXmlCharacters(String::Format( 4574 "%s:%d\n%s", 4575 part.file_name(), part.line_number(), 4576 part.message()).c_str()); 4577 OutputXmlCDataSection(stream, message.c_str()); 4578 *stream << "</failure>\n"; 4579 } 4580 } 4581 4582 if (failures == 0) 4583 *stream << " />\n"; 4584 else 4585 *stream << " </testcase>\n"; 4586} 4587 4588// Prints an XML representation of a TestCase object 4589void XmlUnitTestResultPrinter::PrintXmlTestCase(FILE* out, 4590 const TestCase& test_case) { 4591 fprintf(out, 4592 " <testsuite name=\"%s\" tests=\"%d\" failures=\"%d\" " 4593 "disabled=\"%d\" ", 4594 EscapeXmlAttribute(test_case.name()).c_str(), 4595 test_case.total_test_count(), 4596 test_case.failed_test_count(), 4597 test_case.disabled_test_count()); 4598 fprintf(out, 4599 "errors=\"0\" time=\"%s\">\n", 4600 FormatTimeInMillisAsSeconds(test_case.elapsed_time()).c_str()); 4601 for (int i = 0; i < test_case.total_test_count(); ++i) { 4602 StrStream stream; 4603 OutputXmlTestInfo(&stream, test_case.name(), *test_case.GetTestInfo(i)); 4604 fprintf(out, "%s", StrStreamToString(&stream).c_str()); 4605 } 4606 fprintf(out, " </testsuite>\n"); 4607} 4608 4609// Prints an XML summary of unit_test to output stream out. 4610void XmlUnitTestResultPrinter::PrintXmlUnitTest(FILE* out, 4611 const UnitTest& unit_test) { 4612 fprintf(out, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); 4613 fprintf(out, 4614 "<testsuites tests=\"%d\" failures=\"%d\" disabled=\"%d\" " 4615 "errors=\"0\" time=\"%s\" ", 4616 unit_test.total_test_count(), 4617 unit_test.failed_test_count(), 4618 unit_test.disabled_test_count(), 4619 FormatTimeInMillisAsSeconds(unit_test.elapsed_time()).c_str()); 4620 if (GTEST_FLAG(shuffle)) { 4621 fprintf(out, "random_seed=\"%d\" ", unit_test.random_seed()); 4622 } 4623 fprintf(out, "name=\"AllTests\">\n"); 4624 for (int i = 0; i < unit_test.total_test_case_count(); ++i) 4625 PrintXmlTestCase(out, *unit_test.GetTestCase(i)); 4626 fprintf(out, "</testsuites>\n"); 4627} 4628 4629// Produces a string representing the test properties in a result as space 4630// delimited XML attributes based on the property key="value" pairs. 4631String XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes( 4632 const TestResult& result) { 4633 Message attributes; 4634 for (int i = 0; i < result.test_property_count(); ++i) { 4635 const TestProperty& property = result.GetTestProperty(i); 4636 attributes << " " << property.key() << "=" 4637 << "\"" << EscapeXmlAttribute(property.value()) << "\""; 4638 } 4639 return attributes.GetString(); 4640} 4641 4642// End XmlUnitTestResultPrinter 4643 4644// Class ScopedTrace 4645 4646// Pushes the given source file location and message onto a per-thread 4647// trace stack maintained by Google Test. 4648// L < UnitTest::mutex_ 4649ScopedTrace::ScopedTrace(const char* file, int line, const Message& message) { 4650 TraceInfo trace; 4651 trace.file = file; 4652 trace.line = line; 4653 trace.message = message.GetString(); 4654 4655 UnitTest::GetInstance()->PushGTestTrace(trace); 4656} 4657 4658// Pops the info pushed by the c'tor. 4659// L < UnitTest::mutex_ 4660ScopedTrace::~ScopedTrace() { 4661 UnitTest::GetInstance()->PopGTestTrace(); 4662} 4663 4664 4665// class OsStackTraceGetter 4666 4667// Returns the current OS stack trace as a String. Parameters: 4668// 4669// max_depth - the maximum number of stack frames to be included 4670// in the trace. 4671// skip_count - the number of top frames to be skipped; doesn't count 4672// against max_depth. 4673// 4674// L < mutex_ 4675// We use "L < mutex_" to denote that the function may acquire mutex_. 4676String OsStackTraceGetter::CurrentStackTrace(int, int) { 4677 return String(""); 4678} 4679 4680// L < mutex_ 4681void OsStackTraceGetter::UponLeavingGTest() { 4682} 4683 4684const char* const 4685OsStackTraceGetter::kElidedFramesMarker = 4686 "... " GTEST_NAME_ " internal frames ..."; 4687 4688} // namespace internal 4689 4690// class TestEventListeners 4691 4692TestEventListeners::TestEventListeners() 4693 : repeater_(new internal::TestEventRepeater()), 4694 default_result_printer_(NULL), 4695 default_xml_generator_(NULL) { 4696} 4697 4698TestEventListeners::~TestEventListeners() { delete repeater_; } 4699 4700// Returns the standard listener responsible for the default console 4701// output. Can be removed from the listeners list to shut down default 4702// console output. Note that removing this object from the listener list 4703// with Release transfers its ownership to the user. 4704void TestEventListeners::Append(TestEventListener* listener) { 4705 repeater_->Append(listener); 4706} 4707 4708// Removes the given event listener from the list and returns it. It then 4709// becomes the caller's responsibility to delete the listener. Returns 4710// NULL if the listener is not found in the list. 4711TestEventListener* TestEventListeners::Release(TestEventListener* listener) { 4712 if (listener == default_result_printer_) 4713 default_result_printer_ = NULL; 4714 else if (listener == default_xml_generator_) 4715 default_xml_generator_ = NULL; 4716 return repeater_->Release(listener); 4717} 4718 4719// Returns repeater that broadcasts the TestEventListener events to all 4720// subscribers. 4721TestEventListener* TestEventListeners::repeater() { return repeater_; } 4722 4723// Sets the default_result_printer attribute to the provided listener. 4724// The listener is also added to the listener list and previous 4725// default_result_printer is removed from it and deleted. The listener can 4726// also be NULL in which case it will not be added to the list. Does 4727// nothing if the previous and the current listener objects are the same. 4728void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) { 4729 if (default_result_printer_ != listener) { 4730 // It is an error to pass this method a listener that is already in the 4731 // list. 4732 delete Release(default_result_printer_); 4733 default_result_printer_ = listener; 4734 if (listener != NULL) 4735 Append(listener); 4736 } 4737} 4738 4739// Sets the default_xml_generator attribute to the provided listener. The 4740// listener is also added to the listener list and previous 4741// default_xml_generator is removed from it and deleted. The listener can 4742// also be NULL in which case it will not be added to the list. Does 4743// nothing if the previous and the current listener objects are the same. 4744void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) { 4745 if (default_xml_generator_ != listener) { 4746 // It is an error to pass this method a listener that is already in the 4747 // list. 4748 delete Release(default_xml_generator_); 4749 default_xml_generator_ = listener; 4750 if (listener != NULL) 4751 Append(listener); 4752 } 4753} 4754 4755// Controls whether events will be forwarded by the repeater to the 4756// listeners in the list. 4757bool TestEventListeners::EventForwardingEnabled() const { 4758 return repeater_->forwarding_enabled(); 4759} 4760 4761void TestEventListeners::SuppressEventForwarding() { 4762 repeater_->set_forwarding_enabled(false); 4763} 4764 4765// class UnitTest 4766 4767// Gets the singleton UnitTest object. The first time this method is 4768// called, a UnitTest object is constructed and returned. Consecutive 4769// calls will return the same object. 4770// 4771// We don't protect this under mutex_ as a user is not supposed to 4772// call this before main() starts, from which point on the return 4773// value will never change. 4774UnitTest * UnitTest::GetInstance() { 4775 // When compiled with MSVC 7.1 in optimized mode, destroying the 4776 // UnitTest object upon exiting the program messes up the exit code, 4777 // causing successful tests to appear failed. We have to use a 4778 // different implementation in this case to bypass the compiler bug. 4779 // This implementation makes the compiler happy, at the cost of 4780 // leaking the UnitTest object. 4781 4782 // CodeGear C++Builder insists on a public destructor for the 4783 // default implementation. Use this implementation to keep good OO 4784 // design with private destructor. 4785 4786#if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__) 4787 static UnitTest* const instance = new UnitTest; 4788 return instance; 4789#else 4790 static UnitTest instance; 4791 return &instance; 4792#endif // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__) 4793} 4794 4795// Gets the number of successful test cases. 4796int UnitTest::successful_test_case_count() const { 4797 return impl()->successful_test_case_count(); 4798} 4799 4800// Gets the number of failed test cases. 4801int UnitTest::failed_test_case_count() const { 4802 return impl()->failed_test_case_count(); 4803} 4804 4805// Gets the number of all test cases. 4806int UnitTest::total_test_case_count() const { 4807 return impl()->total_test_case_count(); 4808} 4809 4810// Gets the number of all test cases that contain at least one test 4811// that should run. 4812int UnitTest::test_case_to_run_count() const { 4813 return impl()->test_case_to_run_count(); 4814} 4815 4816// Gets the number of successful tests. 4817int UnitTest::successful_test_count() const { 4818 return impl()->successful_test_count(); 4819} 4820 4821// Gets the number of failed tests. 4822int UnitTest::failed_test_count() const { return impl()->failed_test_count(); } 4823 4824// Gets the number of disabled tests. 4825int UnitTest::disabled_test_count() const { 4826 return impl()->disabled_test_count(); 4827} 4828 4829// Gets the number of all tests. 4830int UnitTest::total_test_count() const { return impl()->total_test_count(); } 4831 4832// Gets the number of tests that should run. 4833int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); } 4834 4835// Gets the elapsed time, in milliseconds. 4836internal::TimeInMillis UnitTest::elapsed_time() const { 4837 return impl()->elapsed_time(); 4838} 4839 4840// Returns true iff the unit test passed (i.e. all test cases passed). 4841bool UnitTest::Passed() const { return impl()->Passed(); } 4842 4843// Returns true iff the unit test failed (i.e. some test case failed 4844// or something outside of all tests failed). 4845bool UnitTest::Failed() const { return impl()->Failed(); } 4846 4847// Gets the i-th test case among all the test cases. i can range from 0 to 4848// total_test_case_count() - 1. If i is not in that range, returns NULL. 4849const TestCase* UnitTest::GetTestCase(int i) const { 4850 return impl()->GetTestCase(i); 4851} 4852 4853// Gets the i-th test case among all the test cases. i can range from 0 to 4854// total_test_case_count() - 1. If i is not in that range, returns NULL. 4855TestCase* UnitTest::GetMutableTestCase(int i) { 4856 return impl()->GetMutableTestCase(i); 4857} 4858 4859// Returns the list of event listeners that can be used to track events 4860// inside Google Test. 4861TestEventListeners& UnitTest::listeners() { 4862 return *impl()->listeners(); 4863} 4864 4865// Registers and returns a global test environment. When a test 4866// program is run, all global test environments will be set-up in the 4867// order they were registered. After all tests in the program have 4868// finished, all global test environments will be torn-down in the 4869// *reverse* order they were registered. 4870// 4871// The UnitTest object takes ownership of the given environment. 4872// 4873// We don't protect this under mutex_, as we only support calling it 4874// from the main thread. 4875Environment* UnitTest::AddEnvironment(Environment* env) { 4876 if (env == NULL) { 4877 return NULL; 4878 } 4879 4880 impl_->environments().push_back(env); 4881 return env; 4882} 4883 4884#if GTEST_HAS_EXCEPTIONS 4885// A failed Google Test assertion will throw an exception of this type 4886// when exceptions are enabled. We derive it from std::runtime_error, 4887// which is for errors presumably detectable only at run time. Since 4888// std::runtime_error inherits from std::exception, many testing 4889// frameworks know how to extract and print the message inside it. 4890class GoogleTestFailureException : public ::std::runtime_error { 4891 public: 4892 explicit GoogleTestFailureException(const TestPartResult& failure) 4893 : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {} 4894}; 4895#endif 4896 4897// Adds a TestPartResult to the current TestResult object. All Google Test 4898// assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call 4899// this to report their results. The user code should use the 4900// assertion macros instead of calling this directly. 4901// L < mutex_ 4902void UnitTest::AddTestPartResult(TestPartResult::Type result_type, 4903 const char* file_name, 4904 int line_number, 4905 const internal::String& message, 4906 const internal::String& os_stack_trace) { 4907 Message msg; 4908 msg << message; 4909 4910 internal::MutexLock lock(&mutex_); 4911 if (impl_->gtest_trace_stack().size() > 0) { 4912 msg << "\n" << GTEST_NAME_ << " trace:"; 4913 4914 for (int i = static_cast<int>(impl_->gtest_trace_stack().size()); 4915 i > 0; --i) { 4916 const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1]; 4917 msg << "\n" << internal::FormatFileLocation(trace.file, trace.line) 4918 << " " << trace.message; 4919 } 4920 } 4921 4922 if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) { 4923 msg << internal::kStackTraceMarker << os_stack_trace; 4924 } 4925 4926 const TestPartResult result = 4927 TestPartResult(result_type, file_name, line_number, 4928 msg.GetString().c_str()); 4929 impl_->GetTestPartResultReporterForCurrentThread()-> 4930 ReportTestPartResult(result); 4931 4932 if (result_type != TestPartResult::kSuccess) { 4933 // gtest_break_on_failure takes precedence over 4934 // gtest_throw_on_failure. This allows a user to set the latter 4935 // in the code (perhaps in order to use Google Test assertions 4936 // with another testing framework) and specify the former on the 4937 // command line for debugging. 4938 if (GTEST_FLAG(break_on_failure)) { 4939#if GTEST_OS_WINDOWS 4940 // Using DebugBreak on Windows allows gtest to still break into a debugger 4941 // when a failure happens and both the --gtest_break_on_failure and 4942 // the --gtest_catch_exceptions flags are specified. 4943 DebugBreak(); 4944#else 4945 *static_cast<int*>(NULL) = 1; 4946#endif // GTEST_OS_WINDOWS 4947 } else if (GTEST_FLAG(throw_on_failure)) { 4948#if GTEST_HAS_EXCEPTIONS 4949 throw GoogleTestFailureException(result); 4950#else 4951 // We cannot call abort() as it generates a pop-up in debug mode 4952 // that cannot be suppressed in VC 7.1 or below. 4953 exit(1); 4954#endif 4955 } 4956 } 4957} 4958 4959// Creates and adds a property to the current TestResult. If a property matching 4960// the supplied value already exists, updates its value instead. 4961void UnitTest::RecordPropertyForCurrentTest(const char* key, 4962 const char* value) { 4963 const TestProperty test_property(key, value); 4964 impl_->current_test_result()->RecordProperty(test_property); 4965} 4966 4967// Runs all tests in this UnitTest object and prints the result. 4968// Returns 0 if successful, or 1 otherwise. 4969// 4970// We don't protect this under mutex_, as we only support calling it 4971// from the main thread. 4972int UnitTest::Run() { 4973#if GTEST_HAS_SEH 4974 // Catch SEH-style exceptions. 4975 4976 const bool in_death_test_child_process = 4977 internal::GTEST_FLAG(internal_run_death_test).length() > 0; 4978 4979 // Either the user wants Google Test to catch exceptions thrown by the 4980 // tests or this is executing in the context of death test child 4981 // process. In either case the user does not want to see pop-up dialogs 4982 // about crashes - they are expected.. 4983 if (GTEST_FLAG(catch_exceptions) || in_death_test_child_process) { 4984#if !GTEST_OS_WINDOWS_MOBILE 4985 // SetErrorMode doesn't exist on CE. 4986 SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT | 4987 SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX); 4988#endif // !GTEST_OS_WINDOWS_MOBILE 4989 4990#if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE 4991 // Death test children can be terminated with _abort(). On Windows, 4992 // _abort() can show a dialog with a warning message. This forces the 4993 // abort message to go to stderr instead. 4994 _set_error_mode(_OUT_TO_STDERR); 4995#endif 4996 4997#if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE 4998 // In the debug version, Visual Studio pops up a separate dialog 4999 // offering a choice to debug the aborted program. We need to suppress 5000 // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement 5001 // executed. Google Test will notify the user of any unexpected 5002 // failure via stderr. 5003 // 5004 // VC++ doesn't define _set_abort_behavior() prior to the version 8.0. 5005 // Users of prior VC versions shall suffer the agony and pain of 5006 // clicking through the countless debug dialogs. 5007 // TODO(vladl@google.com): find a way to suppress the abort dialog() in the 5008 // debug mode when compiled with VC 7.1 or lower. 5009 if (!GTEST_FLAG(break_on_failure)) 5010 _set_abort_behavior( 5011 0x0, // Clear the following flags: 5012 _WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump. 5013#endif 5014 } 5015 5016 __try { 5017 return impl_->RunAllTests(); 5018 } __except(internal::UnitTestOptions::GTestShouldProcessSEH( 5019 GetExceptionCode())) { 5020 printf("Exception thrown with code 0x%x.\nFAIL\n", GetExceptionCode()); 5021 fflush(stdout); 5022 return 1; 5023 } 5024 5025#else // We are on a compiler or platform that doesn't support SEH. 5026 5027 return impl_->RunAllTests(); 5028#endif // GTEST_HAS_SEH 5029} 5030 5031// Returns the working directory when the first TEST() or TEST_F() was 5032// executed. 5033const char* UnitTest::original_working_dir() const { 5034 return impl_->original_working_dir_.c_str(); 5035} 5036 5037// Returns the TestCase object for the test that's currently running, 5038// or NULL if no test is running. 5039// L < mutex_ 5040const TestCase* UnitTest::current_test_case() const { 5041 internal::MutexLock lock(&mutex_); 5042 return impl_->current_test_case(); 5043} 5044 5045// Returns the TestInfo object for the test that's currently running, 5046// or NULL if no test is running. 5047// L < mutex_ 5048const TestInfo* UnitTest::current_test_info() const { 5049 internal::MutexLock lock(&mutex_); 5050 return impl_->current_test_info(); 5051} 5052 5053// Returns the random seed used at the start of the current test run. 5054int UnitTest::random_seed() const { return impl_->random_seed(); } 5055 5056#if GTEST_HAS_PARAM_TEST 5057// Returns ParameterizedTestCaseRegistry object used to keep track of 5058// value-parameterized tests and instantiate and register them. 5059// L < mutex_ 5060internal::ParameterizedTestCaseRegistry& 5061 UnitTest::parameterized_test_registry() { 5062 return impl_->parameterized_test_registry(); 5063} 5064#endif // GTEST_HAS_PARAM_TEST 5065 5066// Creates an empty UnitTest. 5067UnitTest::UnitTest() { 5068 impl_ = new internal::UnitTestImpl(this); 5069} 5070 5071// Destructor of UnitTest. 5072UnitTest::~UnitTest() { 5073 delete impl_; 5074} 5075 5076// Pushes a trace defined by SCOPED_TRACE() on to the per-thread 5077// Google Test trace stack. 5078// L < mutex_ 5079void UnitTest::PushGTestTrace(const internal::TraceInfo& trace) { 5080 internal::MutexLock lock(&mutex_); 5081 impl_->gtest_trace_stack().push_back(trace); 5082} 5083 5084// Pops a trace from the per-thread Google Test trace stack. 5085// L < mutex_ 5086void UnitTest::PopGTestTrace() { 5087 internal::MutexLock lock(&mutex_); 5088 impl_->gtest_trace_stack().pop_back(); 5089} 5090 5091namespace internal { 5092 5093UnitTestImpl::UnitTestImpl(UnitTest* parent) 5094 : parent_(parent), 5095#ifdef _MSC_VER 5096#pragma warning(push) // Saves the current warning state. 5097#pragma warning(disable:4355) // Temporarily disables warning 4355 5098 // (using this in initializer). 5099 default_global_test_part_result_reporter_(this), 5100 default_per_thread_test_part_result_reporter_(this), 5101#pragma warning(pop) // Restores the warning state again. 5102#else 5103 default_global_test_part_result_reporter_(this), 5104 default_per_thread_test_part_result_reporter_(this), 5105#endif // _MSC_VER 5106 global_test_part_result_repoter_( 5107 &default_global_test_part_result_reporter_), 5108 per_thread_test_part_result_reporter_( 5109 &default_per_thread_test_part_result_reporter_), 5110#if GTEST_HAS_PARAM_TEST 5111 parameterized_test_registry_(), 5112 parameterized_tests_registered_(false), 5113#endif // GTEST_HAS_PARAM_TEST 5114 last_death_test_case_(-1), 5115 current_test_case_(NULL), 5116 current_test_info_(NULL), 5117 ad_hoc_test_result_(), 5118 os_stack_trace_getter_(NULL), 5119 post_flag_parse_init_performed_(false), 5120 random_seed_(0), // Will be overridden by the flag before first use. 5121 random_(0), // Will be reseeded before first use. 5122#if GTEST_HAS_DEATH_TEST 5123 elapsed_time_(0), 5124 internal_run_death_test_flag_(NULL), 5125 death_test_factory_(new DefaultDeathTestFactory) { 5126#else 5127 elapsed_time_(0) { 5128#endif // GTEST_HAS_DEATH_TEST 5129 listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter); 5130} 5131 5132UnitTestImpl::~UnitTestImpl() { 5133 // Deletes every TestCase. 5134 ForEach(test_cases_, internal::Delete<TestCase>); 5135 5136 // Deletes every Environment. 5137 ForEach(environments_, internal::Delete<Environment>); 5138 5139 delete os_stack_trace_getter_; 5140} 5141 5142#if GTEST_HAS_DEATH_TEST 5143// Disables event forwarding if the control is currently in a death test 5144// subprocess. Must not be called before InitGoogleTest. 5145void UnitTestImpl::SuppressTestEventsIfInSubprocess() { 5146 if (internal_run_death_test_flag_.get() != NULL) 5147 listeners()->SuppressEventForwarding(); 5148} 5149#endif // GTEST_HAS_DEATH_TEST 5150 5151// Initializes event listeners performing XML output as specified by 5152// UnitTestOptions. Must not be called before InitGoogleTest. 5153void UnitTestImpl::ConfigureXmlOutput() { 5154 const String& output_format = UnitTestOptions::GetOutputFormat(); 5155 if (output_format == "xml") { 5156 listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter( 5157 UnitTestOptions::GetAbsolutePathToOutputFile().c_str())); 5158 } else if (output_format != "") { 5159 printf("WARNING: unrecognized output format \"%s\" ignored.\n", 5160 output_format.c_str()); 5161 fflush(stdout); 5162 } 5163} 5164 5165// Performs initialization dependent upon flag values obtained in 5166// ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to 5167// ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest 5168// this function is also called from RunAllTests. Since this function can be 5169// called more than once, it has to be idempotent. 5170void UnitTestImpl::PostFlagParsingInit() { 5171 // Ensures that this function does not execute more than once. 5172 if (!post_flag_parse_init_performed_) { 5173 post_flag_parse_init_performed_ = true; 5174 5175#if GTEST_HAS_DEATH_TEST 5176 InitDeathTestSubprocessControlInfo(); 5177 SuppressTestEventsIfInSubprocess(); 5178#endif // GTEST_HAS_DEATH_TEST 5179 5180 // Registers parameterized tests. This makes parameterized tests 5181 // available to the UnitTest reflection API without running 5182 // RUN_ALL_TESTS. 5183 RegisterParameterizedTests(); 5184 5185 // Configures listeners for XML output. This makes it possible for users 5186 // to shut down the default XML output before invoking RUN_ALL_TESTS. 5187 ConfigureXmlOutput(); 5188 } 5189} 5190 5191// A predicate that checks the name of a TestCase against a known 5192// value. 5193// 5194// This is used for implementation of the UnitTest class only. We put 5195// it in the anonymous namespace to prevent polluting the outer 5196// namespace. 5197// 5198// TestCaseNameIs is copyable. 5199class TestCaseNameIs { 5200 public: 5201 // Constructor. 5202 explicit TestCaseNameIs(const String& name) 5203 : name_(name) {} 5204 5205 // Returns true iff the name of test_case matches name_. 5206 bool operator()(const TestCase* test_case) const { 5207 return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0; 5208 } 5209 5210 private: 5211 String name_; 5212}; 5213 5214// Finds and returns a TestCase with the given name. If one doesn't 5215// exist, creates one and returns it. It's the CALLER'S 5216// RESPONSIBILITY to ensure that this function is only called WHEN THE 5217// TESTS ARE NOT SHUFFLED. 5218// 5219// Arguments: 5220// 5221// test_case_name: name of the test case 5222// set_up_tc: pointer to the function that sets up the test case 5223// tear_down_tc: pointer to the function that tears down the test case 5224TestCase* UnitTestImpl::GetTestCase(const char* test_case_name, 5225 const char* comment, 5226 Test::SetUpTestCaseFunc set_up_tc, 5227 Test::TearDownTestCaseFunc tear_down_tc) { 5228 // Can we find a TestCase with the given name? 5229 const std::vector<TestCase*>::const_iterator test_case = 5230 std::find_if(test_cases_.begin(), test_cases_.end(), 5231 TestCaseNameIs(test_case_name)); 5232 5233 if (test_case != test_cases_.end()) 5234 return *test_case; 5235 5236 // No. Let's create one. 5237 TestCase* const new_test_case = 5238 new TestCase(test_case_name, comment, set_up_tc, tear_down_tc); 5239 5240 // Is this a death test case? 5241 if (internal::UnitTestOptions::MatchesFilter(String(test_case_name), 5242 kDeathTestCaseFilter)) { 5243 // Yes. Inserts the test case after the last death test case 5244 // defined so far. This only works when the test cases haven't 5245 // been shuffled. Otherwise we may end up running a death test 5246 // after a non-death test. 5247 ++last_death_test_case_; 5248 test_cases_.insert(test_cases_.begin() + last_death_test_case_, 5249 new_test_case); 5250 } else { 5251 // No. Appends to the end of the list. 5252 test_cases_.push_back(new_test_case); 5253 } 5254 5255 test_case_indices_.push_back(static_cast<int>(test_case_indices_.size())); 5256 return new_test_case; 5257} 5258 5259// Helpers for setting up / tearing down the given environment. They 5260// are for use in the ForEach() function. 5261static void SetUpEnvironment(Environment* env) { env->SetUp(); } 5262static void TearDownEnvironment(Environment* env) { env->TearDown(); } 5263 5264// Runs all tests in this UnitTest object, prints the result, and 5265// returns 0 if all tests are successful, or 1 otherwise. If any 5266// exception is thrown during a test on Windows, this test is 5267// considered to be failed, but the rest of the tests will still be 5268// run. (We disable exceptions on Linux and Mac OS X, so the issue 5269// doesn't apply there.) 5270// When parameterized tests are enabled, it expands and registers 5271// parameterized tests first in RegisterParameterizedTests(). 5272// All other functions called from RunAllTests() may safely assume that 5273// parameterized tests are ready to be counted and run. 5274int UnitTestImpl::RunAllTests() { 5275 // Makes sure InitGoogleTest() was called. 5276 if (!GTestIsInitialized()) { 5277 printf("%s", 5278 "\nThis test program did NOT call ::testing::InitGoogleTest " 5279 "before calling RUN_ALL_TESTS(). Please fix it.\n"); 5280 return 1; 5281 } 5282 5283 // Do not run any test if the --help flag was specified. 5284 if (g_help_flag) 5285 return 0; 5286 5287 // Repeats the call to the post-flag parsing initialization in case the 5288 // user didn't call InitGoogleTest. 5289 PostFlagParsingInit(); 5290 5291 // Even if sharding is not on, test runners may want to use the 5292 // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding 5293 // protocol. 5294 internal::WriteToShardStatusFileIfNeeded(); 5295 5296 // True iff we are in a subprocess for running a thread-safe-style 5297 // death test. 5298 bool in_subprocess_for_death_test = false; 5299 5300#if GTEST_HAS_DEATH_TEST 5301 in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL); 5302#endif // GTEST_HAS_DEATH_TEST 5303 5304 const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex, 5305 in_subprocess_for_death_test); 5306 5307 // Compares the full test names with the filter to decide which 5308 // tests to run. 5309 const bool has_tests_to_run = FilterTests(should_shard 5310 ? HONOR_SHARDING_PROTOCOL 5311 : IGNORE_SHARDING_PROTOCOL) > 0; 5312 5313 // Lists the tests and exits if the --gtest_list_tests flag was specified. 5314 if (GTEST_FLAG(list_tests)) { 5315 // This must be called *after* FilterTests() has been called. 5316 ListTestsMatchingFilter(); 5317 return 0; 5318 } 5319 5320 random_seed_ = GTEST_FLAG(shuffle) ? 5321 GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0; 5322 5323 // True iff at least one test has failed. 5324 bool failed = false; 5325 5326 TestEventListener* repeater = listeners()->repeater(); 5327 5328 repeater->OnTestProgramStart(*parent_); 5329 5330 // How many times to repeat the tests? We don't want to repeat them 5331 // when we are inside the subprocess of a death test. 5332 const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat); 5333 // Repeats forever if the repeat count is negative. 5334 const bool forever = repeat < 0; 5335 for (int i = 0; forever || i != repeat; i++) { 5336 ClearResult(); 5337 5338 const TimeInMillis start = GetTimeInMillis(); 5339 5340 // Shuffles test cases and tests if requested. 5341 if (has_tests_to_run && GTEST_FLAG(shuffle)) { 5342 random()->Reseed(random_seed_); 5343 // This should be done before calling OnTestIterationStart(), 5344 // such that a test event listener can see the actual test order 5345 // in the event. 5346 ShuffleTests(); 5347 } 5348 5349 // Tells the unit test event listeners that the tests are about to start. 5350 repeater->OnTestIterationStart(*parent_, i); 5351 5352 // Runs each test case if there is at least one test to run. 5353 if (has_tests_to_run) { 5354 // Sets up all environments beforehand. 5355 repeater->OnEnvironmentsSetUpStart(*parent_); 5356 ForEach(environments_, SetUpEnvironment); 5357 repeater->OnEnvironmentsSetUpEnd(*parent_); 5358 5359 // Runs the tests only if there was no fatal failure during global 5360 // set-up. 5361 if (!Test::HasFatalFailure()) { 5362 for (int test_index = 0; test_index < total_test_case_count(); 5363 test_index++) { 5364 GetMutableTestCase(test_index)->Run(); 5365 } 5366 } 5367 5368 // Tears down all environments in reverse order afterwards. 5369 repeater->OnEnvironmentsTearDownStart(*parent_); 5370 std::for_each(environments_.rbegin(), environments_.rend(), 5371 TearDownEnvironment); 5372 repeater->OnEnvironmentsTearDownEnd(*parent_); 5373 } 5374 5375 elapsed_time_ = GetTimeInMillis() - start; 5376 5377 // Tells the unit test event listener that the tests have just finished. 5378 repeater->OnTestIterationEnd(*parent_, i); 5379 5380 // Gets the result and clears it. 5381 if (!Passed()) { 5382 failed = true; 5383 } 5384 5385 // Restores the original test order after the iteration. This 5386 // allows the user to quickly repro a failure that happens in the 5387 // N-th iteration without repeating the first (N - 1) iterations. 5388 // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in 5389 // case the user somehow changes the value of the flag somewhere 5390 // (it's always safe to unshuffle the tests). 5391 UnshuffleTests(); 5392 5393 if (GTEST_FLAG(shuffle)) { 5394 // Picks a new random seed for each iteration. 5395 random_seed_ = GetNextRandomSeed(random_seed_); 5396 } 5397 } 5398 5399 repeater->OnTestProgramEnd(*parent_); 5400 5401 // Returns 0 if all tests passed, or 1 other wise. 5402 return failed ? 1 : 0; 5403} 5404 5405// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file 5406// if the variable is present. If a file already exists at this location, this 5407// function will write over it. If the variable is present, but the file cannot 5408// be created, prints an error and exits. 5409void WriteToShardStatusFileIfNeeded() { 5410 const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile); 5411 if (test_shard_file != NULL) { 5412 FILE* const file = posix::FOpen(test_shard_file, "w"); 5413 if (file == NULL) { 5414 ColoredPrintf(COLOR_RED, 5415 "Could not write to the test shard status file \"%s\" " 5416 "specified by the %s environment variable.\n", 5417 test_shard_file, kTestShardStatusFile); 5418 fflush(stdout); 5419 exit(EXIT_FAILURE); 5420 } 5421 fclose(file); 5422 } 5423} 5424 5425// Checks whether sharding is enabled by examining the relevant 5426// environment variable values. If the variables are present, 5427// but inconsistent (i.e., shard_index >= total_shards), prints 5428// an error and exits. If in_subprocess_for_death_test, sharding is 5429// disabled because it must only be applied to the original test 5430// process. Otherwise, we could filter out death tests we intended to execute. 5431bool ShouldShard(const char* total_shards_env, 5432 const char* shard_index_env, 5433 bool in_subprocess_for_death_test) { 5434 if (in_subprocess_for_death_test) { 5435 return false; 5436 } 5437 5438 const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1); 5439 const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1); 5440 5441 if (total_shards == -1 && shard_index == -1) { 5442 return false; 5443 } else if (total_shards == -1 && shard_index != -1) { 5444 const Message msg = Message() 5445 << "Invalid environment variables: you have " 5446 << kTestShardIndex << " = " << shard_index 5447 << ", but have left " << kTestTotalShards << " unset.\n"; 5448 ColoredPrintf(COLOR_RED, msg.GetString().c_str()); 5449 fflush(stdout); 5450 exit(EXIT_FAILURE); 5451 } else if (total_shards != -1 && shard_index == -1) { 5452 const Message msg = Message() 5453 << "Invalid environment variables: you have " 5454 << kTestTotalShards << " = " << total_shards 5455 << ", but have left " << kTestShardIndex << " unset.\n"; 5456 ColoredPrintf(COLOR_RED, msg.GetString().c_str()); 5457 fflush(stdout); 5458 exit(EXIT_FAILURE); 5459 } else if (shard_index < 0 || shard_index >= total_shards) { 5460 const Message msg = Message() 5461 << "Invalid environment variables: we require 0 <= " 5462 << kTestShardIndex << " < " << kTestTotalShards 5463 << ", but you have " << kTestShardIndex << "=" << shard_index 5464 << ", " << kTestTotalShards << "=" << total_shards << ".\n"; 5465 ColoredPrintf(COLOR_RED, msg.GetString().c_str()); 5466 fflush(stdout); 5467 exit(EXIT_FAILURE); 5468 } 5469 5470 return total_shards > 1; 5471} 5472 5473// Parses the environment variable var as an Int32. If it is unset, 5474// returns default_val. If it is not an Int32, prints an error 5475// and aborts. 5476Int32 Int32FromEnvOrDie(const char* const var, Int32 default_val) { 5477 const char* str_val = posix::GetEnv(var); 5478 if (str_val == NULL) { 5479 return default_val; 5480 } 5481 5482 Int32 result; 5483 if (!ParseInt32(Message() << "The value of environment variable " << var, 5484 str_val, &result)) { 5485 exit(EXIT_FAILURE); 5486 } 5487 return result; 5488} 5489 5490// Given the total number of shards, the shard index, and the test id, 5491// returns true iff the test should be run on this shard. The test id is 5492// some arbitrary but unique non-negative integer assigned to each test 5493// method. Assumes that 0 <= shard_index < total_shards. 5494bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) { 5495 return (test_id % total_shards) == shard_index; 5496} 5497 5498// Compares the name of each test with the user-specified filter to 5499// decide whether the test should be run, then records the result in 5500// each TestCase and TestInfo object. 5501// If shard_tests == true, further filters tests based on sharding 5502// variables in the environment - see 5503// http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide. 5504// Returns the number of tests that should run. 5505int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) { 5506 const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ? 5507 Int32FromEnvOrDie(kTestTotalShards, -1) : -1; 5508 const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ? 5509 Int32FromEnvOrDie(kTestShardIndex, -1) : -1; 5510 5511 // num_runnable_tests are the number of tests that will 5512 // run across all shards (i.e., match filter and are not disabled). 5513 // num_selected_tests are the number of tests to be run on 5514 // this shard. 5515 int num_runnable_tests = 0; 5516 int num_selected_tests = 0; 5517 for (size_t i = 0; i < test_cases_.size(); i++) { 5518 TestCase* const test_case = test_cases_[i]; 5519 const String &test_case_name = test_case->name(); 5520 test_case->set_should_run(false); 5521 5522 for (size_t j = 0; j < test_case->test_info_list().size(); j++) { 5523 TestInfo* const test_info = test_case->test_info_list()[j]; 5524 const String test_name(test_info->name()); 5525 // A test is disabled if test case name or test name matches 5526 // kDisableTestFilter. 5527 const bool is_disabled = 5528 internal::UnitTestOptions::MatchesFilter(test_case_name, 5529 kDisableTestFilter) || 5530 internal::UnitTestOptions::MatchesFilter(test_name, 5531 kDisableTestFilter); 5532 test_info->impl()->set_is_disabled(is_disabled); 5533 5534 const bool matches_filter = 5535 internal::UnitTestOptions::FilterMatchesTest(test_case_name, 5536 test_name); 5537 test_info->impl()->set_matches_filter(matches_filter); 5538 5539 const bool is_runnable = 5540 (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) && 5541 matches_filter; 5542 5543 const bool is_selected = is_runnable && 5544 (shard_tests == IGNORE_SHARDING_PROTOCOL || 5545 ShouldRunTestOnShard(total_shards, shard_index, 5546 num_runnable_tests)); 5547 5548 num_runnable_tests += is_runnable; 5549 num_selected_tests += is_selected; 5550 5551 test_info->impl()->set_should_run(is_selected); 5552 test_case->set_should_run(test_case->should_run() || is_selected); 5553 } 5554 } 5555 return num_selected_tests; 5556} 5557 5558// Prints the names of the tests matching the user-specified filter flag. 5559void UnitTestImpl::ListTestsMatchingFilter() { 5560 for (size_t i = 0; i < test_cases_.size(); i++) { 5561 const TestCase* const test_case = test_cases_[i]; 5562 bool printed_test_case_name = false; 5563 5564 for (size_t j = 0; j < test_case->test_info_list().size(); j++) { 5565 const TestInfo* const test_info = 5566 test_case->test_info_list()[j]; 5567 if (test_info->matches_filter()) { 5568 if (!printed_test_case_name) { 5569 printed_test_case_name = true; 5570 printf("%s.\n", test_case->name()); 5571 } 5572 printf(" %s\n", test_info->name()); 5573 } 5574 } 5575 } 5576 fflush(stdout); 5577} 5578 5579// Sets the OS stack trace getter. 5580// 5581// Does nothing if the input and the current OS stack trace getter are 5582// the same; otherwise, deletes the old getter and makes the input the 5583// current getter. 5584void UnitTestImpl::set_os_stack_trace_getter( 5585 OsStackTraceGetterInterface* getter) { 5586 if (os_stack_trace_getter_ != getter) { 5587 delete os_stack_trace_getter_; 5588 os_stack_trace_getter_ = getter; 5589 } 5590} 5591 5592// Returns the current OS stack trace getter if it is not NULL; 5593// otherwise, creates an OsStackTraceGetter, makes it the current 5594// getter, and returns it. 5595OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() { 5596 if (os_stack_trace_getter_ == NULL) { 5597 os_stack_trace_getter_ = new OsStackTraceGetter; 5598 } 5599 5600 return os_stack_trace_getter_; 5601} 5602 5603// Returns the TestResult for the test that's currently running, or 5604// the TestResult for the ad hoc test if no test is running. 5605TestResult* UnitTestImpl::current_test_result() { 5606 return current_test_info_ ? 5607 current_test_info_->impl()->result() : &ad_hoc_test_result_; 5608} 5609 5610// Shuffles all test cases, and the tests within each test case, 5611// making sure that death tests are still run first. 5612void UnitTestImpl::ShuffleTests() { 5613 // Shuffles the death test cases. 5614 ShuffleRange(random(), 0, last_death_test_case_ + 1, &test_case_indices_); 5615 5616 // Shuffles the non-death test cases. 5617 ShuffleRange(random(), last_death_test_case_ + 1, 5618 static_cast<int>(test_cases_.size()), &test_case_indices_); 5619 5620 // Shuffles the tests inside each test case. 5621 for (size_t i = 0; i < test_cases_.size(); i++) { 5622 test_cases_[i]->ShuffleTests(random()); 5623 } 5624} 5625 5626// Restores the test cases and tests to their order before the first shuffle. 5627void UnitTestImpl::UnshuffleTests() { 5628 for (size_t i = 0; i < test_cases_.size(); i++) { 5629 // Unshuffles the tests in each test case. 5630 test_cases_[i]->UnshuffleTests(); 5631 // Resets the index of each test case. 5632 test_case_indices_[i] = static_cast<int>(i); 5633 } 5634} 5635 5636// TestInfoImpl constructor. The new instance assumes ownership of the test 5637// factory object. 5638TestInfoImpl::TestInfoImpl(TestInfo* parent, 5639 const char* a_test_case_name, 5640 const char* a_name, 5641 const char* a_test_case_comment, 5642 const char* a_comment, 5643 TypeId a_fixture_class_id, 5644 internal::TestFactoryBase* factory) : 5645 parent_(parent), 5646 test_case_name_(String(a_test_case_name)), 5647 name_(String(a_name)), 5648 test_case_comment_(String(a_test_case_comment)), 5649 comment_(String(a_comment)), 5650 fixture_class_id_(a_fixture_class_id), 5651 should_run_(false), 5652 is_disabled_(false), 5653 matches_filter_(false), 5654 factory_(factory) { 5655} 5656 5657// TestInfoImpl destructor. 5658TestInfoImpl::~TestInfoImpl() { 5659 delete factory_; 5660} 5661 5662// Returns the current OS stack trace as a String. 5663// 5664// The maximum number of stack frames to be included is specified by 5665// the gtest_stack_trace_depth flag. The skip_count parameter 5666// specifies the number of top frames to be skipped, which doesn't 5667// count against the number of frames to be included. 5668// 5669// For example, if Foo() calls Bar(), which in turn calls 5670// GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in 5671// the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't. 5672String GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/, 5673 int skip_count) { 5674 // We pass skip_count + 1 to skip this wrapper function in addition 5675 // to what the user really wants to skip. 5676 return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1); 5677} 5678 5679// Used by the GTEST_HIDE_UNREACHABLE_CODE_ macro to suppress unreachable 5680// code warnings. 5681namespace { 5682class ClassUniqueToAlwaysTrue {}; 5683} 5684 5685bool IsTrue(bool condition) { return condition; } 5686 5687bool AlwaysTrue() { 5688#if GTEST_HAS_EXCEPTIONS 5689 // This condition is always false so AlwaysTrue() never actually throws, 5690 // but it makes the compiler think that it may throw. 5691 if (IsTrue(false)) 5692 throw ClassUniqueToAlwaysTrue(); 5693#endif // GTEST_HAS_EXCEPTIONS 5694 return true; 5695} 5696 5697// If *pstr starts with the given prefix, modifies *pstr to be right 5698// past the prefix and returns true; otherwise leaves *pstr unchanged 5699// and returns false. None of pstr, *pstr, and prefix can be NULL. 5700bool SkipPrefix(const char* prefix, const char** pstr) { 5701 const size_t prefix_len = strlen(prefix); 5702 if (strncmp(*pstr, prefix, prefix_len) == 0) { 5703 *pstr += prefix_len; 5704 return true; 5705 } 5706 return false; 5707} 5708 5709// Parses a string as a command line flag. The string should have 5710// the format "--flag=value". When def_optional is true, the "=value" 5711// part can be omitted. 5712// 5713// Returns the value of the flag, or NULL if the parsing failed. 5714const char* ParseFlagValue(const char* str, 5715 const char* flag, 5716 bool def_optional) { 5717 // str and flag must not be NULL. 5718 if (str == NULL || flag == NULL) return NULL; 5719 5720 // The flag must start with "--" followed by GTEST_FLAG_PREFIX_. 5721 const String flag_str = String::Format("--%s%s", GTEST_FLAG_PREFIX_, flag); 5722 const size_t flag_len = flag_str.length(); 5723 if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL; 5724 5725 // Skips the flag name. 5726 const char* flag_end = str + flag_len; 5727 5728 // When def_optional is true, it's OK to not have a "=value" part. 5729 if (def_optional && (flag_end[0] == '\0')) { 5730 return flag_end; 5731 } 5732 5733 // If def_optional is true and there are more characters after the 5734 // flag name, or if def_optional is false, there must be a '=' after 5735 // the flag name. 5736 if (flag_end[0] != '=') return NULL; 5737 5738 // Returns the string after "=". 5739 return flag_end + 1; 5740} 5741 5742// Parses a string for a bool flag, in the form of either 5743// "--flag=value" or "--flag". 5744// 5745// In the former case, the value is taken as true as long as it does 5746// not start with '0', 'f', or 'F'. 5747// 5748// In the latter case, the value is taken as true. 5749// 5750// On success, stores the value of the flag in *value, and returns 5751// true. On failure, returns false without changing *value. 5752bool ParseBoolFlag(const char* str, const char* flag, bool* value) { 5753 // Gets the value of the flag as a string. 5754 const char* const value_str = ParseFlagValue(str, flag, true); 5755 5756 // Aborts if the parsing failed. 5757 if (value_str == NULL) return false; 5758 5759 // Converts the string value to a bool. 5760 *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F'); 5761 return true; 5762} 5763 5764// Parses a string for an Int32 flag, in the form of 5765// "--flag=value". 5766// 5767// On success, stores the value of the flag in *value, and returns 5768// true. On failure, returns false without changing *value. 5769bool ParseInt32Flag(const char* str, const char* flag, Int32* value) { 5770 // Gets the value of the flag as a string. 5771 const char* const value_str = ParseFlagValue(str, flag, false); 5772 5773 // Aborts if the parsing failed. 5774 if (value_str == NULL) return false; 5775 5776 // Sets *value to the value of the flag. 5777 return ParseInt32(Message() << "The value of flag --" << flag, 5778 value_str, value); 5779} 5780 5781// Parses a string for a string flag, in the form of 5782// "--flag=value". 5783// 5784// On success, stores the value of the flag in *value, and returns 5785// true. On failure, returns false without changing *value. 5786bool ParseStringFlag(const char* str, const char* flag, String* value) { 5787 // Gets the value of the flag as a string. 5788 const char* const value_str = ParseFlagValue(str, flag, false); 5789 5790 // Aborts if the parsing failed. 5791 if (value_str == NULL) return false; 5792 5793 // Sets *value to the value of the flag. 5794 *value = value_str; 5795 return true; 5796} 5797 5798// Determines whether a string has a prefix that Google Test uses for its 5799// flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_. 5800// If Google Test detects that a command line flag has its prefix but is not 5801// recognized, it will print its help message. Flags starting with 5802// GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test 5803// internal flags and do not trigger the help message. 5804static bool HasGoogleTestFlagPrefix(const char* str) { 5805 return (SkipPrefix("--", &str) || 5806 SkipPrefix("-", &str) || 5807 SkipPrefix("/", &str)) && 5808 !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) && 5809 (SkipPrefix(GTEST_FLAG_PREFIX_, &str) || 5810 SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str)); 5811} 5812 5813// Prints a string containing code-encoded text. The following escape 5814// sequences can be used in the string to control the text color: 5815// 5816// @@ prints a single '@' character. 5817// @R changes the color to red. 5818// @G changes the color to green. 5819// @Y changes the color to yellow. 5820// @D changes to the default terminal text color. 5821// 5822// TODO(wan@google.com): Write tests for this once we add stdout 5823// capturing to Google Test. 5824static void PrintColorEncoded(const char* str) { 5825 GTestColor color = COLOR_DEFAULT; // The current color. 5826 5827 // Conceptually, we split the string into segments divided by escape 5828 // sequences. Then we print one segment at a time. At the end of 5829 // each iteration, the str pointer advances to the beginning of the 5830 // next segment. 5831 for (;;) { 5832 const char* p = strchr(str, '@'); 5833 if (p == NULL) { 5834 ColoredPrintf(color, "%s", str); 5835 return; 5836 } 5837 5838 ColoredPrintf(color, "%s", String(str, p - str).c_str()); 5839 5840 const char ch = p[1]; 5841 str = p + 2; 5842 if (ch == '@') { 5843 ColoredPrintf(color, "@"); 5844 } else if (ch == 'D') { 5845 color = COLOR_DEFAULT; 5846 } else if (ch == 'R') { 5847 color = COLOR_RED; 5848 } else if (ch == 'G') { 5849 color = COLOR_GREEN; 5850 } else if (ch == 'Y') { 5851 color = COLOR_YELLOW; 5852 } else { 5853 --str; 5854 } 5855 } 5856} 5857 5858static const char kColorEncodedHelpMessage[] = 5859"This program contains tests written using " GTEST_NAME_ ". You can use the\n" 5860"following command line flags to control its behavior:\n" 5861"\n" 5862"Test Selection:\n" 5863" @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n" 5864" List the names of all tests instead of running them. The name of\n" 5865" TEST(Foo, Bar) is \"Foo.Bar\".\n" 5866" @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS" 5867 "[@G-@YNEGATIVE_PATTERNS]@D\n" 5868" Run only the tests whose name matches one of the positive patterns but\n" 5869" none of the negative patterns. '?' matches any single character; '*'\n" 5870" matches any substring; ':' separates two patterns.\n" 5871" @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n" 5872" Run all disabled tests too.\n" 5873"\n" 5874"Test Execution:\n" 5875" @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n" 5876" Run the tests repeatedly; use a negative count to repeat forever.\n" 5877" @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n" 5878" Randomize tests' orders on every iteration.\n" 5879" @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n" 5880" Random number seed to use for shuffling test orders (between 1 and\n" 5881" 99999, or 0 to use a seed based on the current time).\n" 5882"\n" 5883"Test Output:\n" 5884" @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n" 5885" Enable/disable colored output. The default is @Gauto@D.\n" 5886" -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n" 5887" Don't print the elapsed time of each test.\n" 5888" @G--" GTEST_FLAG_PREFIX_ "output=xml@Y[@G:@YDIRECTORY_PATH@G" 5889 GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n" 5890" Generate an XML report in the given directory or with the given file\n" 5891" name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n" 5892"\n" 5893"Assertion Behavior:\n" 5894#if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS 5895" @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n" 5896" Set the default death test style.\n" 5897#endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS 5898" @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n" 5899" Turn assertion failures into debugger break-points.\n" 5900" @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n" 5901" Turn assertion failures into C++ exceptions.\n" 5902#if GTEST_OS_WINDOWS 5903" @G--" GTEST_FLAG_PREFIX_ "catch_exceptions@D\n" 5904" Suppress pop-ups caused by exceptions.\n" 5905#endif // GTEST_OS_WINDOWS 5906"\n" 5907"Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set " 5908 "the corresponding\n" 5909"environment variable of a flag (all letters in upper-case). For example, to\n" 5910"disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_ 5911 "color=no@D or set\n" 5912"the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n" 5913"\n" 5914"For more information, please read the " GTEST_NAME_ " documentation at\n" 5915"@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n" 5916"(not one in your own code or tests), please report it to\n" 5917"@G<" GTEST_DEV_EMAIL_ ">@D.\n"; 5918 5919// Parses the command line for Google Test flags, without initializing 5920// other parts of Google Test. The type parameter CharType can be 5921// instantiated to either char or wchar_t. 5922template <typename CharType> 5923void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) { 5924 for (int i = 1; i < *argc; i++) { 5925 const String arg_string = StreamableToString(argv[i]); 5926 const char* const arg = arg_string.c_str(); 5927 5928 using internal::ParseBoolFlag; 5929 using internal::ParseInt32Flag; 5930 using internal::ParseStringFlag; 5931 5932 // Do we see a Google Test flag? 5933 if (ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag, 5934 >EST_FLAG(also_run_disabled_tests)) || 5935 ParseBoolFlag(arg, kBreakOnFailureFlag, 5936 >EST_FLAG(break_on_failure)) || 5937 ParseBoolFlag(arg, kCatchExceptionsFlag, 5938 >EST_FLAG(catch_exceptions)) || 5939 ParseStringFlag(arg, kColorFlag, >EST_FLAG(color)) || 5940 ParseStringFlag(arg, kDeathTestStyleFlag, 5941 >EST_FLAG(death_test_style)) || 5942 ParseBoolFlag(arg, kDeathTestUseFork, 5943 >EST_FLAG(death_test_use_fork)) || 5944 ParseStringFlag(arg, kFilterFlag, >EST_FLAG(filter)) || 5945 ParseStringFlag(arg, kInternalRunDeathTestFlag, 5946 >EST_FLAG(internal_run_death_test)) || 5947 ParseBoolFlag(arg, kListTestsFlag, >EST_FLAG(list_tests)) || 5948 ParseStringFlag(arg, kOutputFlag, >EST_FLAG(output)) || 5949 ParseBoolFlag(arg, kPrintTimeFlag, >EST_FLAG(print_time)) || 5950 ParseInt32Flag(arg, kRandomSeedFlag, >EST_FLAG(random_seed)) || 5951 ParseInt32Flag(arg, kRepeatFlag, >EST_FLAG(repeat)) || 5952 ParseBoolFlag(arg, kShuffleFlag, >EST_FLAG(shuffle)) || 5953 ParseInt32Flag(arg, kStackTraceDepthFlag, 5954 >EST_FLAG(stack_trace_depth)) || 5955 ParseBoolFlag(arg, kThrowOnFailureFlag, >EST_FLAG(throw_on_failure)) 5956 ) { 5957 // Yes. Shift the remainder of the argv list left by one. Note 5958 // that argv has (*argc + 1) elements, the last one always being 5959 // NULL. The following loop moves the trailing NULL element as 5960 // well. 5961 for (int j = i; j != *argc; j++) { 5962 argv[j] = argv[j + 1]; 5963 } 5964 5965 // Decrements the argument count. 5966 (*argc)--; 5967 5968 // We also need to decrement the iterator as we just removed 5969 // an element. 5970 i--; 5971 } else if (arg_string == "--help" || arg_string == "-h" || 5972 arg_string == "-?" || arg_string == "/?" || 5973 HasGoogleTestFlagPrefix(arg)) { 5974 // Both help flag and unrecognized Google Test flags (excluding 5975 // internal ones) trigger help display. 5976 g_help_flag = true; 5977 } 5978 } 5979 5980 if (g_help_flag) { 5981 // We print the help here instead of in RUN_ALL_TESTS(), as the 5982 // latter may not be called at all if the user is using Google 5983 // Test with another testing framework. 5984 PrintColorEncoded(kColorEncodedHelpMessage); 5985 } 5986} 5987 5988// Parses the command line for Google Test flags, without initializing 5989// other parts of Google Test. 5990void ParseGoogleTestFlagsOnly(int* argc, char** argv) { 5991 ParseGoogleTestFlagsOnlyImpl(argc, argv); 5992} 5993void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) { 5994 ParseGoogleTestFlagsOnlyImpl(argc, argv); 5995} 5996 5997// The internal implementation of InitGoogleTest(). 5998// 5999// The type parameter CharType can be instantiated to either char or 6000// wchar_t. 6001template <typename CharType> 6002void InitGoogleTestImpl(int* argc, CharType** argv) { 6003 g_init_gtest_count++; 6004 6005 // We don't want to run the initialization code twice. 6006 if (g_init_gtest_count != 1) return; 6007 6008 if (*argc <= 0) return; 6009 6010 internal::g_executable_path = internal::StreamableToString(argv[0]); 6011 6012#if GTEST_HAS_DEATH_TEST 6013 g_argvs.clear(); 6014 for (int i = 0; i != *argc; i++) { 6015 g_argvs.push_back(StreamableToString(argv[i])); 6016 } 6017#endif // GTEST_HAS_DEATH_TEST 6018 6019 ParseGoogleTestFlagsOnly(argc, argv); 6020 GetUnitTestImpl()->PostFlagParsingInit(); 6021} 6022 6023} // namespace internal 6024 6025// Initializes Google Test. This must be called before calling 6026// RUN_ALL_TESTS(). In particular, it parses a command line for the 6027// flags that Google Test recognizes. Whenever a Google Test flag is 6028// seen, it is removed from argv, and *argc is decremented. 6029// 6030// No value is returned. Instead, the Google Test flag variables are 6031// updated. 6032// 6033// Calling the function for the second time has no user-visible effect. 6034void InitGoogleTest(int* argc, char** argv) { 6035 internal::InitGoogleTestImpl(argc, argv); 6036} 6037 6038// This overloaded version can be used in Windows programs compiled in 6039// UNICODE mode. 6040void InitGoogleTest(int* argc, wchar_t** argv) { 6041 internal::InitGoogleTestImpl(argc, argv); 6042} 6043 6044} // namespace testing 6045// Copyright 2005, Google Inc. 6046// All rights reserved. 6047// 6048// Redistribution and use in source and binary forms, with or without 6049// modification, are permitted provided that the following conditions are 6050// met: 6051// 6052// * Redistributions of source code must retain the above copyright 6053// notice, this list of conditions and the following disclaimer. 6054// * Redistributions in binary form must reproduce the above 6055// copyright notice, this list of conditions and the following disclaimer 6056// in the documentation and/or other materials provided with the 6057// distribution. 6058// * Neither the name of Google Inc. nor the names of its 6059// contributors may be used to endorse or promote products derived from 6060// this software without specific prior written permission. 6061// 6062// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 6063// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 6064// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 6065// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 6066// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 6067// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 6068// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 6069// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 6070// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 6071// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 6072// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 6073// 6074// Author: wan@google.com (Zhanyong Wan), vladl@google.com (Vlad Losev) 6075// 6076// This file implements death tests. 6077 6078 6079#if GTEST_HAS_DEATH_TEST 6080 6081#if GTEST_OS_MAC 6082#include <crt_externs.h> 6083#endif // GTEST_OS_MAC 6084 6085#include <errno.h> 6086#include <fcntl.h> 6087#include <limits.h> 6088#include <stdarg.h> 6089 6090#if GTEST_OS_WINDOWS 6091#include <windows.h> 6092#else 6093#include <sys/mman.h> 6094#include <sys/wait.h> 6095#endif // GTEST_OS_WINDOWS 6096 6097#endif // GTEST_HAS_DEATH_TEST 6098 6099 6100// Indicates that this translation unit is part of Google Test's 6101// implementation. It must come before gtest-internal-inl.h is 6102// included, or there will be a compiler error. This trick is to 6103// prevent a user from accidentally including gtest-internal-inl.h in 6104// his code. 6105#define GTEST_IMPLEMENTATION_ 1 6106#undef GTEST_IMPLEMENTATION_ 6107 6108namespace testing { 6109 6110// Constants. 6111 6112// The default death test style. 6113static const char kDefaultDeathTestStyle[] = "fast"; 6114 6115GTEST_DEFINE_string_( 6116 death_test_style, 6117 internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle), 6118 "Indicates how to run a death test in a forked child process: " 6119 "\"threadsafe\" (child process re-executes the test binary " 6120 "from the beginning, running only the specific death test) or " 6121 "\"fast\" (child process runs the death test immediately " 6122 "after forking)."); 6123 6124GTEST_DEFINE_bool_( 6125 death_test_use_fork, 6126 internal::BoolFromGTestEnv("death_test_use_fork", false), 6127 "Instructs to use fork()/_exit() instead of clone() in death tests. " 6128 "Ignored and always uses fork() on POSIX systems where clone() is not " 6129 "implemented. Useful when running under valgrind or similar tools if " 6130 "those do not support clone(). Valgrind 3.3.1 will just fail if " 6131 "it sees an unsupported combination of clone() flags. " 6132 "It is not recommended to use this flag w/o valgrind though it will " 6133 "work in 99% of the cases. Once valgrind is fixed, this flag will " 6134 "most likely be removed."); 6135 6136namespace internal { 6137GTEST_DEFINE_string_( 6138 internal_run_death_test, "", 6139 "Indicates the file, line number, temporal index of " 6140 "the single death test to run, and a file descriptor to " 6141 "which a success code may be sent, all separated by " 6142 "colons. This flag is specified if and only if the current " 6143 "process is a sub-process launched for running a thread-safe " 6144 "death test. FOR INTERNAL USE ONLY."); 6145} // namespace internal 6146 6147#if GTEST_HAS_DEATH_TEST 6148 6149// ExitedWithCode constructor. 6150ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) { 6151} 6152 6153// ExitedWithCode function-call operator. 6154bool ExitedWithCode::operator()(int exit_status) const { 6155#if GTEST_OS_WINDOWS 6156 return exit_status == exit_code_; 6157#else 6158 return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_; 6159#endif // GTEST_OS_WINDOWS 6160} 6161 6162#if !GTEST_OS_WINDOWS 6163// KilledBySignal constructor. 6164KilledBySignal::KilledBySignal(int signum) : signum_(signum) { 6165} 6166 6167// KilledBySignal function-call operator. 6168bool KilledBySignal::operator()(int exit_status) const { 6169 return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_; 6170} 6171#endif // !GTEST_OS_WINDOWS 6172 6173namespace internal { 6174 6175// Utilities needed for death tests. 6176 6177// Generates a textual description of a given exit code, in the format 6178// specified by wait(2). 6179static String ExitSummary(int exit_code) { 6180 Message m; 6181#if GTEST_OS_WINDOWS 6182 m << "Exited with exit status " << exit_code; 6183#else 6184 if (WIFEXITED(exit_code)) { 6185 m << "Exited with exit status " << WEXITSTATUS(exit_code); 6186 } else if (WIFSIGNALED(exit_code)) { 6187 m << "Terminated by signal " << WTERMSIG(exit_code); 6188 } 6189#ifdef WCOREDUMP 6190 if (WCOREDUMP(exit_code)) { 6191 m << " (core dumped)"; 6192 } 6193#endif 6194#endif // GTEST_OS_WINDOWS 6195 return m.GetString(); 6196} 6197 6198// Returns true if exit_status describes a process that was terminated 6199// by a signal, or exited normally with a nonzero exit code. 6200bool ExitedUnsuccessfully(int exit_status) { 6201 return !ExitedWithCode(0)(exit_status); 6202} 6203 6204#if !GTEST_OS_WINDOWS 6205// Generates a textual failure message when a death test finds more than 6206// one thread running, or cannot determine the number of threads, prior 6207// to executing the given statement. It is the responsibility of the 6208// caller not to pass a thread_count of 1. 6209static String DeathTestThreadWarning(size_t thread_count) { 6210 Message msg; 6211 msg << "Death tests use fork(), which is unsafe particularly" 6212 << " in a threaded context. For this test, " << GTEST_NAME_ << " "; 6213 if (thread_count == 0) 6214 msg << "couldn't detect the number of threads."; 6215 else 6216 msg << "detected " << thread_count << " threads."; 6217 return msg.GetString(); 6218} 6219#endif // !GTEST_OS_WINDOWS 6220 6221// Flag characters for reporting a death test that did not die. 6222static const char kDeathTestLived = 'L'; 6223static const char kDeathTestReturned = 'R'; 6224static const char kDeathTestInternalError = 'I'; 6225 6226// An enumeration describing all of the possible ways that a death test 6227// can conclude. DIED means that the process died while executing the 6228// test code; LIVED means that process lived beyond the end of the test 6229// code; and RETURNED means that the test statement attempted a "return," 6230// which is not allowed. IN_PROGRESS means the test has not yet 6231// concluded. 6232enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED }; 6233 6234// Routine for aborting the program which is safe to call from an 6235// exec-style death test child process, in which case the error 6236// message is propagated back to the parent process. Otherwise, the 6237// message is simply printed to stderr. In either case, the program 6238// then exits with status 1. 6239void DeathTestAbort(const String& message) { 6240 // On a POSIX system, this function may be called from a threadsafe-style 6241 // death test child process, which operates on a very small stack. Use 6242 // the heap for any additional non-minuscule memory requirements. 6243 const InternalRunDeathTestFlag* const flag = 6244 GetUnitTestImpl()->internal_run_death_test_flag(); 6245 if (flag != NULL) { 6246 FILE* parent = posix::FDOpen(flag->write_fd(), "w"); 6247 fputc(kDeathTestInternalError, parent); 6248 fprintf(parent, "%s", message.c_str()); 6249 fflush(parent); 6250 _exit(1); 6251 } else { 6252 fprintf(stderr, "%s", message.c_str()); 6253 fflush(stderr); 6254 abort(); 6255 } 6256} 6257 6258// A replacement for CHECK that calls DeathTestAbort if the assertion 6259// fails. 6260#define GTEST_DEATH_TEST_CHECK_(expression) \ 6261 do { \ 6262 if (!::testing::internal::IsTrue(expression)) { \ 6263 DeathTestAbort(::testing::internal::String::Format( \ 6264 "CHECK failed: File %s, line %d: %s", \ 6265 __FILE__, __LINE__, #expression)); \ 6266 } \ 6267 } while (::testing::internal::AlwaysFalse()) 6268 6269// This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for 6270// evaluating any system call that fulfills two conditions: it must return 6271// -1 on failure, and set errno to EINTR when it is interrupted and 6272// should be tried again. The macro expands to a loop that repeatedly 6273// evaluates the expression as long as it evaluates to -1 and sets 6274// errno to EINTR. If the expression evaluates to -1 but errno is 6275// something other than EINTR, DeathTestAbort is called. 6276#define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \ 6277 do { \ 6278 int gtest_retval; \ 6279 do { \ 6280 gtest_retval = (expression); \ 6281 } while (gtest_retval == -1 && errno == EINTR); \ 6282 if (gtest_retval == -1) { \ 6283 DeathTestAbort(::testing::internal::String::Format( \ 6284 "CHECK failed: File %s, line %d: %s != -1", \ 6285 __FILE__, __LINE__, #expression)); \ 6286 } \ 6287 } while (::testing::internal::AlwaysFalse()) 6288 6289// Returns the message describing the last system error in errno. 6290String GetLastErrnoDescription() { 6291 return String(errno == 0 ? "" : posix::StrError(errno)); 6292} 6293 6294// This is called from a death test parent process to read a failure 6295// message from the death test child process and log it with the FATAL 6296// severity. On Windows, the message is read from a pipe handle. On other 6297// platforms, it is read from a file descriptor. 6298static void FailFromInternalError(int fd) { 6299 Message error; 6300 char buffer[256]; 6301 int num_read; 6302 6303 do { 6304 while ((num_read = posix::Read(fd, buffer, 255)) > 0) { 6305 buffer[num_read] = '\0'; 6306 error << buffer; 6307 } 6308 } while (num_read == -1 && errno == EINTR); 6309 6310 if (num_read == 0) { 6311 GTEST_LOG_(FATAL) << error.GetString(); 6312 } else { 6313 const int last_error = errno; 6314 GTEST_LOG_(FATAL) << "Error while reading death test internal: " 6315 << GetLastErrnoDescription() << " [" << last_error << "]"; 6316 } 6317} 6318 6319// Death test constructor. Increments the running death test count 6320// for the current test. 6321DeathTest::DeathTest() { 6322 TestInfo* const info = GetUnitTestImpl()->current_test_info(); 6323 if (info == NULL) { 6324 DeathTestAbort("Cannot run a death test outside of a TEST or " 6325 "TEST_F construct"); 6326 } 6327} 6328 6329// Creates and returns a death test by dispatching to the current 6330// death test factory. 6331bool DeathTest::Create(const char* statement, const RE* regex, 6332 const char* file, int line, DeathTest** test) { 6333 return GetUnitTestImpl()->death_test_factory()->Create( 6334 statement, regex, file, line, test); 6335} 6336 6337const char* DeathTest::LastMessage() { 6338 return last_death_test_message_.c_str(); 6339} 6340 6341void DeathTest::set_last_death_test_message(const String& message) { 6342 last_death_test_message_ = message; 6343} 6344 6345String DeathTest::last_death_test_message_; 6346 6347// Provides cross platform implementation for some death functionality. 6348class DeathTestImpl : public DeathTest { 6349 protected: 6350 DeathTestImpl(const char* a_statement, const RE* a_regex) 6351 : statement_(a_statement), 6352 regex_(a_regex), 6353 spawned_(false), 6354 status_(-1), 6355 outcome_(IN_PROGRESS), 6356 read_fd_(-1), 6357 write_fd_(-1) {} 6358 6359 // read_fd_ is expected to be closed and cleared by a derived class. 6360 ~DeathTestImpl() { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); } 6361 6362 void Abort(AbortReason reason); 6363 virtual bool Passed(bool status_ok); 6364 6365 const char* statement() const { return statement_; } 6366 const RE* regex() const { return regex_; } 6367 bool spawned() const { return spawned_; } 6368 void set_spawned(bool is_spawned) { spawned_ = is_spawned; } 6369 int status() const { return status_; } 6370 void set_status(int a_status) { status_ = a_status; } 6371 DeathTestOutcome outcome() const { return outcome_; } 6372 void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; } 6373 int read_fd() const { return read_fd_; } 6374 void set_read_fd(int fd) { read_fd_ = fd; } 6375 int write_fd() const { return write_fd_; } 6376 void set_write_fd(int fd) { write_fd_ = fd; } 6377 6378 // Called in the parent process only. Reads the result code of the death 6379 // test child process via a pipe, interprets it to set the outcome_ 6380 // member, and closes read_fd_. Outputs diagnostics and terminates in 6381 // case of unexpected codes. 6382 void ReadAndInterpretStatusByte(); 6383 6384 private: 6385 // The textual content of the code this object is testing. This class 6386 // doesn't own this string and should not attempt to delete it. 6387 const char* const statement_; 6388 // The regular expression which test output must match. DeathTestImpl 6389 // doesn't own this object and should not attempt to delete it. 6390 const RE* const regex_; 6391 // True if the death test child process has been successfully spawned. 6392 bool spawned_; 6393 // The exit status of the child process. 6394 int status_; 6395 // How the death test concluded. 6396 DeathTestOutcome outcome_; 6397 // Descriptor to the read end of the pipe to the child process. It is 6398 // always -1 in the child process. The child keeps its write end of the 6399 // pipe in write_fd_. 6400 int read_fd_; 6401 // Descriptor to the child's write end of the pipe to the parent process. 6402 // It is always -1 in the parent process. The parent keeps its end of the 6403 // pipe in read_fd_. 6404 int write_fd_; 6405}; 6406 6407// Called in the parent process only. Reads the result code of the death 6408// test child process via a pipe, interprets it to set the outcome_ 6409// member, and closes read_fd_. Outputs diagnostics and terminates in 6410// case of unexpected codes. 6411void DeathTestImpl::ReadAndInterpretStatusByte() { 6412 char flag; 6413 int bytes_read; 6414 6415 // The read() here blocks until data is available (signifying the 6416 // failure of the death test) or until the pipe is closed (signifying 6417 // its success), so it's okay to call this in the parent before 6418 // the child process has exited. 6419 do { 6420 bytes_read = posix::Read(read_fd(), &flag, 1); 6421 } while (bytes_read == -1 && errno == EINTR); 6422 6423 if (bytes_read == 0) { 6424 set_outcome(DIED); 6425 } else if (bytes_read == 1) { 6426 switch (flag) { 6427 case kDeathTestReturned: 6428 set_outcome(RETURNED); 6429 break; 6430 case kDeathTestLived: 6431 set_outcome(LIVED); 6432 break; 6433 case kDeathTestInternalError: 6434 FailFromInternalError(read_fd()); // Does not return. 6435 break; 6436 default: 6437 GTEST_LOG_(FATAL) << "Death test child process reported " 6438 << "unexpected status byte (" 6439 << static_cast<unsigned int>(flag) << ")"; 6440 } 6441 } else { 6442 GTEST_LOG_(FATAL) << "Read from death test child process failed: " 6443 << GetLastErrnoDescription(); 6444 } 6445 GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd())); 6446 set_read_fd(-1); 6447} 6448 6449// Signals that the death test code which should have exited, didn't. 6450// Should be called only in a death test child process. 6451// Writes a status byte to the child's status file descriptor, then 6452// calls _exit(1). 6453void DeathTestImpl::Abort(AbortReason reason) { 6454 // The parent process considers the death test to be a failure if 6455 // it finds any data in our pipe. So, here we write a single flag byte 6456 // to the pipe, then exit. 6457 const char status_ch = 6458 reason == TEST_DID_NOT_DIE ? kDeathTestLived : kDeathTestReturned; 6459 GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1)); 6460 GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(write_fd())); 6461 _exit(1); // Exits w/o any normal exit hooks (we were supposed to crash) 6462} 6463 6464// Assesses the success or failure of a death test, using both private 6465// members which have previously been set, and one argument: 6466// 6467// Private data members: 6468// outcome: An enumeration describing how the death test 6469// concluded: DIED, LIVED, or RETURNED. The death test fails 6470// in the latter two cases. 6471// status: The exit status of the child process. On *nix, it is in the 6472// in the format specified by wait(2). On Windows, this is the 6473// value supplied to the ExitProcess() API or a numeric code 6474// of the exception that terminated the program. 6475// regex: A regular expression object to be applied to 6476// the test's captured standard error output; the death test 6477// fails if it does not match. 6478// 6479// Argument: 6480// status_ok: true if exit_status is acceptable in the context of 6481// this particular death test, which fails if it is false 6482// 6483// Returns true iff all of the above conditions are met. Otherwise, the 6484// first failing condition, in the order given above, is the one that is 6485// reported. Also sets the last death test message string. 6486bool DeathTestImpl::Passed(bool status_ok) { 6487 if (!spawned()) 6488 return false; 6489 6490 const String error_message = GetCapturedStderr(); 6491 6492 bool success = false; 6493 Message buffer; 6494 6495 buffer << "Death test: " << statement() << "\n"; 6496 switch (outcome()) { 6497 case LIVED: 6498 buffer << " Result: failed to die.\n" 6499 << " Error msg: " << error_message; 6500 break; 6501 case RETURNED: 6502 buffer << " Result: illegal return in test statement.\n" 6503 << " Error msg: " << error_message; 6504 break; 6505 case DIED: 6506 if (status_ok) { 6507 const bool matched = RE::PartialMatch(error_message.c_str(), *regex()); 6508 if (matched) { 6509 success = true; 6510 } else { 6511 buffer << " Result: died but not with expected error.\n" 6512 << " Expected: " << regex()->pattern() << "\n" 6513 << "Actual msg: " << error_message; 6514 } 6515 } else { 6516 buffer << " Result: died but not with expected exit code:\n" 6517 << " " << ExitSummary(status()) << "\n"; 6518 } 6519 break; 6520 case IN_PROGRESS: 6521 default: 6522 GTEST_LOG_(FATAL) 6523 << "DeathTest::Passed somehow called before conclusion of test"; 6524 } 6525 6526 DeathTest::set_last_death_test_message(buffer.GetString()); 6527 return success; 6528} 6529 6530#if GTEST_OS_WINDOWS 6531// WindowsDeathTest implements death tests on Windows. Due to the 6532// specifics of starting new processes on Windows, death tests there are 6533// always threadsafe, and Google Test considers the 6534// --gtest_death_test_style=fast setting to be equivalent to 6535// --gtest_death_test_style=threadsafe there. 6536// 6537// A few implementation notes: Like the Linux version, the Windows 6538// implementation uses pipes for child-to-parent communication. But due to 6539// the specifics of pipes on Windows, some extra steps are required: 6540// 6541// 1. The parent creates a communication pipe and stores handles to both 6542// ends of it. 6543// 2. The parent starts the child and provides it with the information 6544// necessary to acquire the handle to the write end of the pipe. 6545// 3. The child acquires the write end of the pipe and signals the parent 6546// using a Windows event. 6547// 4. Now the parent can release the write end of the pipe on its side. If 6548// this is done before step 3, the object's reference count goes down to 6549// 0 and it is destroyed, preventing the child from acquiring it. The 6550// parent now has to release it, or read operations on the read end of 6551// the pipe will not return when the child terminates. 6552// 5. The parent reads child's output through the pipe (outcome code and 6553// any possible error messages) from the pipe, and its stderr and then 6554// determines whether to fail the test. 6555// 6556// Note: to distinguish Win32 API calls from the local method and function 6557// calls, the former are explicitly resolved in the global namespace. 6558// 6559class WindowsDeathTest : public DeathTestImpl { 6560 public: 6561 WindowsDeathTest(const char* statement, 6562 const RE* regex, 6563 const char* file, 6564 int line) 6565 : DeathTestImpl(statement, regex), file_(file), line_(line) {} 6566 6567 // All of these virtual functions are inherited from DeathTest. 6568 virtual int Wait(); 6569 virtual TestRole AssumeRole(); 6570 6571 private: 6572 // The name of the file in which the death test is located. 6573 const char* const file_; 6574 // The line number on which the death test is located. 6575 const int line_; 6576 // Handle to the write end of the pipe to the child process. 6577 AutoHandle write_handle_; 6578 // Child process handle. 6579 AutoHandle child_handle_; 6580 // Event the child process uses to signal the parent that it has 6581 // acquired the handle to the write end of the pipe. After seeing this 6582 // event the parent can release its own handles to make sure its 6583 // ReadFile() calls return when the child terminates. 6584 AutoHandle event_handle_; 6585}; 6586 6587// Waits for the child in a death test to exit, returning its exit 6588// status, or 0 if no child process exists. As a side effect, sets the 6589// outcome data member. 6590int WindowsDeathTest::Wait() { 6591 if (!spawned()) 6592 return 0; 6593 6594 // Wait until the child either signals that it has acquired the write end 6595 // of the pipe or it dies. 6596 const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() }; 6597 switch (::WaitForMultipleObjects(2, 6598 wait_handles, 6599 FALSE, // Waits for any of the handles. 6600 INFINITE)) { 6601 case WAIT_OBJECT_0: 6602 case WAIT_OBJECT_0 + 1: 6603 break; 6604 default: 6605 GTEST_DEATH_TEST_CHECK_(false); // Should not get here. 6606 } 6607 6608 // The child has acquired the write end of the pipe or exited. 6609 // We release the handle on our side and continue. 6610 write_handle_.Reset(); 6611 event_handle_.Reset(); 6612 6613 ReadAndInterpretStatusByte(); 6614 6615 // Waits for the child process to exit if it haven't already. This 6616 // returns immediately if the child has already exited, regardless of 6617 // whether previous calls to WaitForMultipleObjects synchronized on this 6618 // handle or not. 6619 GTEST_DEATH_TEST_CHECK_( 6620 WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(), 6621 INFINITE)); 6622 DWORD status; 6623 GTEST_DEATH_TEST_CHECK_(::GetExitCodeProcess(child_handle_.Get(), &status) 6624 != FALSE); 6625 child_handle_.Reset(); 6626 set_status(static_cast<int>(status)); 6627 return this->status(); 6628} 6629 6630// The AssumeRole process for a Windows death test. It creates a child 6631// process with the same executable as the current process to run the 6632// death test. The child process is given the --gtest_filter and 6633// --gtest_internal_run_death_test flags such that it knows to run the 6634// current death test only. 6635DeathTest::TestRole WindowsDeathTest::AssumeRole() { 6636 const UnitTestImpl* const impl = GetUnitTestImpl(); 6637 const InternalRunDeathTestFlag* const flag = 6638 impl->internal_run_death_test_flag(); 6639 const TestInfo* const info = impl->current_test_info(); 6640 const int death_test_index = info->result()->death_test_count(); 6641 6642 if (flag != NULL) { 6643 // ParseInternalRunDeathTestFlag() has performed all the necessary 6644 // processing. 6645 set_write_fd(flag->write_fd()); 6646 return EXECUTE_TEST; 6647 } 6648 6649 // WindowsDeathTest uses an anonymous pipe to communicate results of 6650 // a death test. 6651 SECURITY_ATTRIBUTES handles_are_inheritable = { 6652 sizeof(SECURITY_ATTRIBUTES), NULL, TRUE }; 6653 HANDLE read_handle, write_handle; 6654 GTEST_DEATH_TEST_CHECK_( 6655 ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable, 6656 0) // Default buffer size. 6657 != FALSE); 6658 set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle), 6659 O_RDONLY)); 6660 write_handle_.Reset(write_handle); 6661 event_handle_.Reset(::CreateEvent( 6662 &handles_are_inheritable, 6663 TRUE, // The event will automatically reset to non-signaled state. 6664 FALSE, // The initial state is non-signalled. 6665 NULL)); // The even is unnamed. 6666 GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL); 6667 const String filter_flag = String::Format("--%s%s=%s.%s", 6668 GTEST_FLAG_PREFIX_, kFilterFlag, 6669 info->test_case_name(), 6670 info->name()); 6671 const String internal_flag = String::Format( 6672 "--%s%s=%s|%d|%d|%u|%Iu|%Iu", 6673 GTEST_FLAG_PREFIX_, 6674 kInternalRunDeathTestFlag, 6675 file_, line_, 6676 death_test_index, 6677 static_cast<unsigned int>(::GetCurrentProcessId()), 6678 // size_t has the same with as pointers on both 32-bit and 64-bit 6679 // Windows platforms. 6680 // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx. 6681 reinterpret_cast<size_t>(write_handle), 6682 reinterpret_cast<size_t>(event_handle_.Get())); 6683 6684 char executable_path[_MAX_PATH + 1]; // NOLINT 6685 GTEST_DEATH_TEST_CHECK_( 6686 _MAX_PATH + 1 != ::GetModuleFileNameA(NULL, 6687 executable_path, 6688 _MAX_PATH)); 6689 6690 String command_line = String::Format("%s %s \"%s\"", 6691 ::GetCommandLineA(), 6692 filter_flag.c_str(), 6693 internal_flag.c_str()); 6694 6695 DeathTest::set_last_death_test_message(""); 6696 6697 CaptureStderr(); 6698 // Flush the log buffers since the log streams are shared with the child. 6699 FlushInfoLog(); 6700 6701 // The child process will share the standard handles with the parent. 6702 STARTUPINFOA startup_info; 6703 memset(&startup_info, 0, sizeof(STARTUPINFO)); 6704 startup_info.dwFlags = STARTF_USESTDHANDLES; 6705 startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE); 6706 startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE); 6707 startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE); 6708 6709 PROCESS_INFORMATION process_info; 6710 GTEST_DEATH_TEST_CHECK_(::CreateProcessA( 6711 executable_path, 6712 const_cast<char*>(command_line.c_str()), 6713 NULL, // Retuned process handle is not inheritable. 6714 NULL, // Retuned thread handle is not inheritable. 6715 TRUE, // Child inherits all inheritable handles (for write_handle_). 6716 0x0, // Default creation flags. 6717 NULL, // Inherit the parent's environment. 6718 UnitTest::GetInstance()->original_working_dir(), 6719 &startup_info, 6720 &process_info) != FALSE); 6721 child_handle_.Reset(process_info.hProcess); 6722 ::CloseHandle(process_info.hThread); 6723 set_spawned(true); 6724 return OVERSEE_TEST; 6725} 6726#else // We are not on Windows. 6727 6728// ForkingDeathTest provides implementations for most of the abstract 6729// methods of the DeathTest interface. Only the AssumeRole method is 6730// left undefined. 6731class ForkingDeathTest : public DeathTestImpl { 6732 public: 6733 ForkingDeathTest(const char* statement, const RE* regex); 6734 6735 // All of these virtual functions are inherited from DeathTest. 6736 virtual int Wait(); 6737 6738 protected: 6739 void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; } 6740 6741 private: 6742 // PID of child process during death test; 0 in the child process itself. 6743 pid_t child_pid_; 6744}; 6745 6746// Constructs a ForkingDeathTest. 6747ForkingDeathTest::ForkingDeathTest(const char* a_statement, const RE* a_regex) 6748 : DeathTestImpl(a_statement, a_regex), 6749 child_pid_(-1) {} 6750 6751// Waits for the child in a death test to exit, returning its exit 6752// status, or 0 if no child process exists. As a side effect, sets the 6753// outcome data member. 6754int ForkingDeathTest::Wait() { 6755 if (!spawned()) 6756 return 0; 6757 6758 ReadAndInterpretStatusByte(); 6759 6760 int status_value; 6761 GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0)); 6762 set_status(status_value); 6763 return status_value; 6764} 6765 6766// A concrete death test class that forks, then immediately runs the test 6767// in the child process. 6768class NoExecDeathTest : public ForkingDeathTest { 6769 public: 6770 NoExecDeathTest(const char* a_statement, const RE* a_regex) : 6771 ForkingDeathTest(a_statement, a_regex) { } 6772 virtual TestRole AssumeRole(); 6773}; 6774 6775// The AssumeRole process for a fork-and-run death test. It implements a 6776// straightforward fork, with a simple pipe to transmit the status byte. 6777DeathTest::TestRole NoExecDeathTest::AssumeRole() { 6778 const size_t thread_count = GetThreadCount(); 6779 if (thread_count != 1) { 6780 GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count); 6781 } 6782 6783 int pipe_fd[2]; 6784 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1); 6785 6786 DeathTest::set_last_death_test_message(""); 6787 CaptureStderr(); 6788 // When we fork the process below, the log file buffers are copied, but the 6789 // file descriptors are shared. We flush all log files here so that closing 6790 // the file descriptors in the child process doesn't throw off the 6791 // synchronization between descriptors and buffers in the parent process. 6792 // This is as close to the fork as possible to avoid a race condition in case 6793 // there are multiple threads running before the death test, and another 6794 // thread writes to the log file. 6795 FlushInfoLog(); 6796 6797 const pid_t child_pid = fork(); 6798 GTEST_DEATH_TEST_CHECK_(child_pid != -1); 6799 set_child_pid(child_pid); 6800 if (child_pid == 0) { 6801 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0])); 6802 set_write_fd(pipe_fd[1]); 6803 // Redirects all logging to stderr in the child process to prevent 6804 // concurrent writes to the log files. We capture stderr in the parent 6805 // process and append the child process' output to a log. 6806 LogToStderr(); 6807 // Event forwarding to the listeners of event listener API mush be shut 6808 // down in death test subprocesses. 6809 GetUnitTestImpl()->listeners()->SuppressEventForwarding(); 6810 return EXECUTE_TEST; 6811 } else { 6812 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1])); 6813 set_read_fd(pipe_fd[0]); 6814 set_spawned(true); 6815 return OVERSEE_TEST; 6816 } 6817} 6818 6819// A concrete death test class that forks and re-executes the main 6820// program from the beginning, with command-line flags set that cause 6821// only this specific death test to be run. 6822class ExecDeathTest : public ForkingDeathTest { 6823 public: 6824 ExecDeathTest(const char* a_statement, const RE* a_regex, 6825 const char* file, int line) : 6826 ForkingDeathTest(a_statement, a_regex), file_(file), line_(line) { } 6827 virtual TestRole AssumeRole(); 6828 private: 6829 // The name of the file in which the death test is located. 6830 const char* const file_; 6831 // The line number on which the death test is located. 6832 const int line_; 6833}; 6834 6835// Utility class for accumulating command-line arguments. 6836class Arguments { 6837 public: 6838 Arguments() { 6839 args_.push_back(NULL); 6840 } 6841 6842 ~Arguments() { 6843 for (std::vector<char*>::iterator i = args_.begin(); i != args_.end(); 6844 ++i) { 6845 free(*i); 6846 } 6847 } 6848 void AddArgument(const char* argument) { 6849 args_.insert(args_.end() - 1, posix::StrDup(argument)); 6850 } 6851 6852 template <typename Str> 6853 void AddArguments(const ::std::vector<Str>& arguments) { 6854 for (typename ::std::vector<Str>::const_iterator i = arguments.begin(); 6855 i != arguments.end(); 6856 ++i) { 6857 args_.insert(args_.end() - 1, posix::StrDup(i->c_str())); 6858 } 6859 } 6860 char* const* Argv() { 6861 return &args_[0]; 6862 } 6863 private: 6864 std::vector<char*> args_; 6865}; 6866 6867// A struct that encompasses the arguments to the child process of a 6868// threadsafe-style death test process. 6869struct ExecDeathTestArgs { 6870 char* const* argv; // Command-line arguments for the child's call to exec 6871 int close_fd; // File descriptor to close; the read end of a pipe 6872}; 6873 6874#if GTEST_OS_MAC 6875inline char** GetEnviron() { 6876 // When Google Test is built as a framework on MacOS X, the environ variable 6877 // is unavailable. Apple's documentation (man environ) recommends using 6878 // _NSGetEnviron() instead. 6879 return *_NSGetEnviron(); 6880} 6881#else 6882// Some POSIX platforms expect you to declare environ. extern "C" makes 6883// it reside in the global namespace. 6884extern "C" char** environ; 6885inline char** GetEnviron() { return environ; } 6886#endif // GTEST_OS_MAC 6887 6888// The main function for a threadsafe-style death test child process. 6889// This function is called in a clone()-ed process and thus must avoid 6890// any potentially unsafe operations like malloc or libc functions. 6891static int ExecDeathTestChildMain(void* child_arg) { 6892 ExecDeathTestArgs* const args = static_cast<ExecDeathTestArgs*>(child_arg); 6893 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd)); 6894 6895 // We need to execute the test program in the same environment where 6896 // it was originally invoked. Therefore we change to the original 6897 // working directory first. 6898 const char* const original_dir = 6899 UnitTest::GetInstance()->original_working_dir(); 6900 // We can safely call chdir() as it's a direct system call. 6901 if (chdir(original_dir) != 0) { 6902 DeathTestAbort(String::Format("chdir(\"%s\") failed: %s", 6903 original_dir, 6904 GetLastErrnoDescription().c_str())); 6905 return EXIT_FAILURE; 6906 } 6907 6908 // We can safely call execve() as it's a direct system call. We 6909 // cannot use execvp() as it's a libc function and thus potentially 6910 // unsafe. Since execve() doesn't search the PATH, the user must 6911 // invoke the test program via a valid path that contains at least 6912 // one path separator. 6913 execve(args->argv[0], args->argv, GetEnviron()); 6914 DeathTestAbort(String::Format("execve(%s, ...) in %s failed: %s", 6915 args->argv[0], 6916 original_dir, 6917 GetLastErrnoDescription().c_str())); 6918 return EXIT_FAILURE; 6919} 6920 6921// Two utility routines that together determine the direction the stack 6922// grows. 6923// This could be accomplished more elegantly by a single recursive 6924// function, but we want to guard against the unlikely possibility of 6925// a smart compiler optimizing the recursion away. 6926bool StackLowerThanAddress(const void* ptr) { 6927 int dummy; 6928 return &dummy < ptr; 6929} 6930 6931bool StackGrowsDown() { 6932 int dummy; 6933 return StackLowerThanAddress(&dummy); 6934} 6935 6936// A threadsafe implementation of fork(2) for threadsafe-style death tests 6937// that uses clone(2). It dies with an error message if anything goes 6938// wrong. 6939static pid_t ExecDeathTestFork(char* const* argv, int close_fd) { 6940 ExecDeathTestArgs args = { argv, close_fd }; 6941 pid_t child_pid = -1; 6942 6943#if GTEST_HAS_CLONE 6944 const bool use_fork = GTEST_FLAG(death_test_use_fork); 6945 6946 if (!use_fork) { 6947 static const bool stack_grows_down = StackGrowsDown(); 6948 const size_t stack_size = getpagesize(); 6949 // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead. 6950 void* const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE, 6951 MAP_ANON | MAP_PRIVATE, -1, 0); 6952 GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED); 6953 void* const stack_top = 6954 static_cast<char*>(stack) + (stack_grows_down ? stack_size : 0); 6955 6956 child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args); 6957 6958 GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1); 6959 } 6960#else 6961 const bool use_fork = true; 6962#endif // GTEST_HAS_CLONE 6963 6964 if (use_fork && (child_pid = fork()) == 0) { 6965 ExecDeathTestChildMain(&args); 6966 _exit(0); 6967 } 6968 6969 GTEST_DEATH_TEST_CHECK_(child_pid != -1); 6970 return child_pid; 6971} 6972 6973// The AssumeRole process for a fork-and-exec death test. It re-executes the 6974// main program from the beginning, setting the --gtest_filter 6975// and --gtest_internal_run_death_test flags to cause only the current 6976// death test to be re-run. 6977DeathTest::TestRole ExecDeathTest::AssumeRole() { 6978 const UnitTestImpl* const impl = GetUnitTestImpl(); 6979 const InternalRunDeathTestFlag* const flag = 6980 impl->internal_run_death_test_flag(); 6981 const TestInfo* const info = impl->current_test_info(); 6982 const int death_test_index = info->result()->death_test_count(); 6983 6984 if (flag != NULL) { 6985 set_write_fd(flag->write_fd()); 6986 return EXECUTE_TEST; 6987 } 6988 6989 int pipe_fd[2]; 6990 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1); 6991 // Clear the close-on-exec flag on the write end of the pipe, lest 6992 // it be closed when the child process does an exec: 6993 GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1); 6994 6995 const String filter_flag = 6996 String::Format("--%s%s=%s.%s", 6997 GTEST_FLAG_PREFIX_, kFilterFlag, 6998 info->test_case_name(), info->name()); 6999 const String internal_flag = 7000 String::Format("--%s%s=%s|%d|%d|%d", 7001 GTEST_FLAG_PREFIX_, kInternalRunDeathTestFlag, 7002 file_, line_, death_test_index, pipe_fd[1]); 7003 Arguments args; 7004 args.AddArguments(GetArgvs()); 7005 args.AddArgument(filter_flag.c_str()); 7006 args.AddArgument(internal_flag.c_str()); 7007 7008 DeathTest::set_last_death_test_message(""); 7009 7010 CaptureStderr(); 7011 // See the comment in NoExecDeathTest::AssumeRole for why the next line 7012 // is necessary. 7013 FlushInfoLog(); 7014 7015 const pid_t child_pid = ExecDeathTestFork(args.Argv(), pipe_fd[0]); 7016 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1])); 7017 set_child_pid(child_pid); 7018 set_read_fd(pipe_fd[0]); 7019 set_spawned(true); 7020 return OVERSEE_TEST; 7021} 7022 7023#endif // !GTEST_OS_WINDOWS 7024 7025// Creates a concrete DeathTest-derived class that depends on the 7026// --gtest_death_test_style flag, and sets the pointer pointed to 7027// by the "test" argument to its address. If the test should be 7028// skipped, sets that pointer to NULL. Returns true, unless the 7029// flag is set to an invalid value. 7030bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex, 7031 const char* file, int line, 7032 DeathTest** test) { 7033 UnitTestImpl* const impl = GetUnitTestImpl(); 7034 const InternalRunDeathTestFlag* const flag = 7035 impl->internal_run_death_test_flag(); 7036 const int death_test_index = impl->current_test_info() 7037 ->increment_death_test_count(); 7038 7039 if (flag != NULL) { 7040 if (death_test_index > flag->index()) { 7041 DeathTest::set_last_death_test_message(String::Format( 7042 "Death test count (%d) somehow exceeded expected maximum (%d)", 7043 death_test_index, flag->index())); 7044 return false; 7045 } 7046 7047 if (!(flag->file() == file && flag->line() == line && 7048 flag->index() == death_test_index)) { 7049 *test = NULL; 7050 return true; 7051 } 7052 } 7053 7054#if GTEST_OS_WINDOWS 7055 if (GTEST_FLAG(death_test_style) == "threadsafe" || 7056 GTEST_FLAG(death_test_style) == "fast") { 7057 *test = new WindowsDeathTest(statement, regex, file, line); 7058 } 7059#else 7060 if (GTEST_FLAG(death_test_style) == "threadsafe") { 7061 *test = new ExecDeathTest(statement, regex, file, line); 7062 } else if (GTEST_FLAG(death_test_style) == "fast") { 7063 *test = new NoExecDeathTest(statement, regex); 7064 } 7065#endif // GTEST_OS_WINDOWS 7066 else { // NOLINT - this is more readable than unbalanced brackets inside #if. 7067 DeathTest::set_last_death_test_message(String::Format( 7068 "Unknown death test style \"%s\" encountered", 7069 GTEST_FLAG(death_test_style).c_str())); 7070 return false; 7071 } 7072 7073 return true; 7074} 7075 7076// Splits a given string on a given delimiter, populating a given 7077// vector with the fields. GTEST_HAS_DEATH_TEST implies that we have 7078// ::std::string, so we can use it here. 7079static void SplitString(const ::std::string& str, char delimiter, 7080 ::std::vector< ::std::string>* dest) { 7081 ::std::vector< ::std::string> parsed; 7082 ::std::string::size_type pos = 0; 7083 while (::testing::internal::AlwaysTrue()) { 7084 const ::std::string::size_type colon = str.find(delimiter, pos); 7085 if (colon == ::std::string::npos) { 7086 parsed.push_back(str.substr(pos)); 7087 break; 7088 } else { 7089 parsed.push_back(str.substr(pos, colon - pos)); 7090 pos = colon + 1; 7091 } 7092 } 7093 dest->swap(parsed); 7094} 7095 7096#if GTEST_OS_WINDOWS 7097// Recreates the pipe and event handles from the provided parameters, 7098// signals the event, and returns a file descriptor wrapped around the pipe 7099// handle. This function is called in the child process only. 7100int GetStatusFileDescriptor(unsigned int parent_process_id, 7101 size_t write_handle_as_size_t, 7102 size_t event_handle_as_size_t) { 7103 AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE, 7104 FALSE, // Non-inheritable. 7105 parent_process_id)); 7106 if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) { 7107 DeathTestAbort(String::Format("Unable to open parent process %u", 7108 parent_process_id)); 7109 } 7110 7111 // TODO(vladl@google.com): Replace the following check with a 7112 // compile-time assertion when available. 7113 GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t)); 7114 7115 const HANDLE write_handle = 7116 reinterpret_cast<HANDLE>(write_handle_as_size_t); 7117 HANDLE dup_write_handle; 7118 7119 // The newly initialized handle is accessible only in in the parent 7120 // process. To obtain one accessible within the child, we need to use 7121 // DuplicateHandle. 7122 if (!::DuplicateHandle(parent_process_handle.Get(), write_handle, 7123 ::GetCurrentProcess(), &dup_write_handle, 7124 0x0, // Requested privileges ignored since 7125 // DUPLICATE_SAME_ACCESS is used. 7126 FALSE, // Request non-inheritable handler. 7127 DUPLICATE_SAME_ACCESS)) { 7128 DeathTestAbort(String::Format( 7129 "Unable to duplicate the pipe handle %Iu from the parent process %u", 7130 write_handle_as_size_t, parent_process_id)); 7131 } 7132 7133 const HANDLE event_handle = reinterpret_cast<HANDLE>(event_handle_as_size_t); 7134 HANDLE dup_event_handle; 7135 7136 if (!::DuplicateHandle(parent_process_handle.Get(), event_handle, 7137 ::GetCurrentProcess(), &dup_event_handle, 7138 0x0, 7139 FALSE, 7140 DUPLICATE_SAME_ACCESS)) { 7141 DeathTestAbort(String::Format( 7142 "Unable to duplicate the event handle %Iu from the parent process %u", 7143 event_handle_as_size_t, parent_process_id)); 7144 } 7145 7146 const int write_fd = 7147 ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND); 7148 if (write_fd == -1) { 7149 DeathTestAbort(String::Format( 7150 "Unable to convert pipe handle %Iu to a file descriptor", 7151 write_handle_as_size_t)); 7152 } 7153 7154 // Signals the parent that the write end of the pipe has been acquired 7155 // so the parent can release its own write end. 7156 ::SetEvent(dup_event_handle); 7157 7158 return write_fd; 7159} 7160#endif // GTEST_OS_WINDOWS 7161 7162// Returns a newly created InternalRunDeathTestFlag object with fields 7163// initialized from the GTEST_FLAG(internal_run_death_test) flag if 7164// the flag is specified; otherwise returns NULL. 7165InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() { 7166 if (GTEST_FLAG(internal_run_death_test) == "") return NULL; 7167 7168 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we 7169 // can use it here. 7170 int line = -1; 7171 int index = -1; 7172 ::std::vector< ::std::string> fields; 7173 SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields); 7174 int write_fd = -1; 7175 7176#if GTEST_OS_WINDOWS 7177 unsigned int parent_process_id = 0; 7178 size_t write_handle_as_size_t = 0; 7179 size_t event_handle_as_size_t = 0; 7180 7181 if (fields.size() != 6 7182 || !ParseNaturalNumber(fields[1], &line) 7183 || !ParseNaturalNumber(fields[2], &index) 7184 || !ParseNaturalNumber(fields[3], &parent_process_id) 7185 || !ParseNaturalNumber(fields[4], &write_handle_as_size_t) 7186 || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) { 7187 DeathTestAbort(String::Format( 7188 "Bad --gtest_internal_run_death_test flag: %s", 7189 GTEST_FLAG(internal_run_death_test).c_str())); 7190 } 7191 write_fd = GetStatusFileDescriptor(parent_process_id, 7192 write_handle_as_size_t, 7193 event_handle_as_size_t); 7194#else 7195 if (fields.size() != 4 7196 || !ParseNaturalNumber(fields[1], &line) 7197 || !ParseNaturalNumber(fields[2], &index) 7198 || !ParseNaturalNumber(fields[3], &write_fd)) { 7199 DeathTestAbort(String::Format( 7200 "Bad --gtest_internal_run_death_test flag: %s", 7201 GTEST_FLAG(internal_run_death_test).c_str())); 7202 } 7203#endif // GTEST_OS_WINDOWS 7204 return new InternalRunDeathTestFlag(fields[0], line, index, write_fd); 7205} 7206 7207} // namespace internal 7208 7209#endif // GTEST_HAS_DEATH_TEST 7210 7211} // namespace testing 7212// Copyright 2008, Google Inc. 7213// All rights reserved. 7214// 7215// Redistribution and use in source and binary forms, with or without 7216// modification, are permitted provided that the following conditions are 7217// met: 7218// 7219// * Redistributions of source code must retain the above copyright 7220// notice, this list of conditions and the following disclaimer. 7221// * Redistributions in binary form must reproduce the above 7222// copyright notice, this list of conditions and the following disclaimer 7223// in the documentation and/or other materials provided with the 7224// distribution. 7225// * Neither the name of Google Inc. nor the names of its 7226// contributors may be used to endorse or promote products derived from 7227// this software without specific prior written permission. 7228// 7229// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 7230// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 7231// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 7232// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 7233// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 7234// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 7235// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 7236// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 7237// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 7238// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 7239// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 7240// 7241// Authors: keith.ray@gmail.com (Keith Ray) 7242 7243 7244#include <stdlib.h> 7245 7246#if GTEST_OS_WINDOWS_MOBILE 7247#include <windows.h> 7248#elif GTEST_OS_WINDOWS 7249#include <direct.h> 7250#include <io.h> 7251#elif GTEST_OS_SYMBIAN 7252// Symbian OpenC has PATH_MAX in sys/syslimits.h 7253#include <sys/syslimits.h> 7254#else 7255#include <limits.h> 7256#include <climits> // Some Linux distributions define PATH_MAX here. 7257#endif // GTEST_OS_WINDOWS_MOBILE 7258 7259#if GTEST_OS_WINDOWS 7260#define GTEST_PATH_MAX_ _MAX_PATH 7261#elif defined(PATH_MAX) 7262#define GTEST_PATH_MAX_ PATH_MAX 7263#elif defined(_XOPEN_PATH_MAX) 7264#define GTEST_PATH_MAX_ _XOPEN_PATH_MAX 7265#else 7266#define GTEST_PATH_MAX_ _POSIX_PATH_MAX 7267#endif // GTEST_OS_WINDOWS 7268 7269 7270namespace testing { 7271namespace internal { 7272 7273#if GTEST_OS_WINDOWS 7274// On Windows, '\\' is the standard path separator, but many tools and the 7275// Windows API also accept '/' as an alternate path separator. Unless otherwise 7276// noted, a file path can contain either kind of path separators, or a mixture 7277// of them. 7278const char kPathSeparator = '\\'; 7279const char kAlternatePathSeparator = '/'; 7280const char kPathSeparatorString[] = "\\"; 7281const char kAlternatePathSeparatorString[] = "/"; 7282#if GTEST_OS_WINDOWS_MOBILE 7283// Windows CE doesn't have a current directory. You should not use 7284// the current directory in tests on Windows CE, but this at least 7285// provides a reasonable fallback. 7286const char kCurrentDirectoryString[] = "\\"; 7287// Windows CE doesn't define INVALID_FILE_ATTRIBUTES 7288const DWORD kInvalidFileAttributes = 0xffffffff; 7289#else 7290const char kCurrentDirectoryString[] = ".\\"; 7291#endif // GTEST_OS_WINDOWS_MOBILE 7292#else 7293const char kPathSeparator = '/'; 7294const char kPathSeparatorString[] = "/"; 7295const char kCurrentDirectoryString[] = "./"; 7296#endif // GTEST_OS_WINDOWS 7297 7298// Returns whether the given character is a valid path separator. 7299static bool IsPathSeparator(char c) { 7300#if GTEST_HAS_ALT_PATH_SEP_ 7301 return (c == kPathSeparator) || (c == kAlternatePathSeparator); 7302#else 7303 return c == kPathSeparator; 7304#endif 7305} 7306 7307// Returns the current working directory, or "" if unsuccessful. 7308FilePath FilePath::GetCurrentDir() { 7309#if GTEST_OS_WINDOWS_MOBILE 7310 // Windows CE doesn't have a current directory, so we just return 7311 // something reasonable. 7312 return FilePath(kCurrentDirectoryString); 7313#elif GTEST_OS_WINDOWS 7314 char cwd[GTEST_PATH_MAX_ + 1] = { '\0' }; 7315 return FilePath(_getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd); 7316#else 7317 char cwd[GTEST_PATH_MAX_ + 1] = { '\0' }; 7318 return FilePath(getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd); 7319#endif // GTEST_OS_WINDOWS_MOBILE 7320} 7321 7322// Returns a copy of the FilePath with the case-insensitive extension removed. 7323// Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns 7324// FilePath("dir/file"). If a case-insensitive extension is not 7325// found, returns a copy of the original FilePath. 7326FilePath FilePath::RemoveExtension(const char* extension) const { 7327 String dot_extension(String::Format(".%s", extension)); 7328 if (pathname_.EndsWithCaseInsensitive(dot_extension.c_str())) { 7329 return FilePath(String(pathname_.c_str(), pathname_.length() - 4)); 7330 } 7331 return *this; 7332} 7333 7334// Returns a pointer to the last occurence of a valid path separator in 7335// the FilePath. On Windows, for example, both '/' and '\' are valid path 7336// separators. Returns NULL if no path separator was found. 7337const char* FilePath::FindLastPathSeparator() const { 7338 const char* const last_sep = strrchr(c_str(), kPathSeparator); 7339#if GTEST_HAS_ALT_PATH_SEP_ 7340 const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator); 7341 // Comparing two pointers of which only one is NULL is undefined. 7342 if (last_alt_sep != NULL && 7343 (last_sep == NULL || last_alt_sep > last_sep)) { 7344 return last_alt_sep; 7345 } 7346#endif 7347 return last_sep; 7348} 7349 7350// Returns a copy of the FilePath with the directory part removed. 7351// Example: FilePath("path/to/file").RemoveDirectoryName() returns 7352// FilePath("file"). If there is no directory part ("just_a_file"), it returns 7353// the FilePath unmodified. If there is no file part ("just_a_dir/") it 7354// returns an empty FilePath (""). 7355// On Windows platform, '\' is the path separator, otherwise it is '/'. 7356FilePath FilePath::RemoveDirectoryName() const { 7357 const char* const last_sep = FindLastPathSeparator(); 7358 return last_sep ? FilePath(String(last_sep + 1)) : *this; 7359} 7360 7361// RemoveFileName returns the directory path with the filename removed. 7362// Example: FilePath("path/to/file").RemoveFileName() returns "path/to/". 7363// If the FilePath is "a_file" or "/a_file", RemoveFileName returns 7364// FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does 7365// not have a file, like "just/a/dir/", it returns the FilePath unmodified. 7366// On Windows platform, '\' is the path separator, otherwise it is '/'. 7367FilePath FilePath::RemoveFileName() const { 7368 const char* const last_sep = FindLastPathSeparator(); 7369 String dir; 7370 if (last_sep) { 7371 dir = String(c_str(), last_sep + 1 - c_str()); 7372 } else { 7373 dir = kCurrentDirectoryString; 7374 } 7375 return FilePath(dir); 7376} 7377 7378// Helper functions for naming files in a directory for xml output. 7379 7380// Given directory = "dir", base_name = "test", number = 0, 7381// extension = "xml", returns "dir/test.xml". If number is greater 7382// than zero (e.g., 12), returns "dir/test_12.xml". 7383// On Windows platform, uses \ as the separator rather than /. 7384FilePath FilePath::MakeFileName(const FilePath& directory, 7385 const FilePath& base_name, 7386 int number, 7387 const char* extension) { 7388 String file; 7389 if (number == 0) { 7390 file = String::Format("%s.%s", base_name.c_str(), extension); 7391 } else { 7392 file = String::Format("%s_%d.%s", base_name.c_str(), number, extension); 7393 } 7394 return ConcatPaths(directory, FilePath(file)); 7395} 7396 7397// Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml". 7398// On Windows, uses \ as the separator rather than /. 7399FilePath FilePath::ConcatPaths(const FilePath& directory, 7400 const FilePath& relative_path) { 7401 if (directory.IsEmpty()) 7402 return relative_path; 7403 const FilePath dir(directory.RemoveTrailingPathSeparator()); 7404 return FilePath(String::Format("%s%c%s", dir.c_str(), kPathSeparator, 7405 relative_path.c_str())); 7406} 7407 7408// Returns true if pathname describes something findable in the file-system, 7409// either a file, directory, or whatever. 7410bool FilePath::FileOrDirectoryExists() const { 7411#if GTEST_OS_WINDOWS_MOBILE 7412 LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str()); 7413 const DWORD attributes = GetFileAttributes(unicode); 7414 delete [] unicode; 7415 return attributes != kInvalidFileAttributes; 7416#else 7417 posix::StatStruct file_stat; 7418 return posix::Stat(pathname_.c_str(), &file_stat) == 0; 7419#endif // GTEST_OS_WINDOWS_MOBILE 7420} 7421 7422// Returns true if pathname describes a directory in the file-system 7423// that exists. 7424bool FilePath::DirectoryExists() const { 7425 bool result = false; 7426#if GTEST_OS_WINDOWS 7427 // Don't strip off trailing separator if path is a root directory on 7428 // Windows (like "C:\\"). 7429 const FilePath& path(IsRootDirectory() ? *this : 7430 RemoveTrailingPathSeparator()); 7431#else 7432 const FilePath& path(*this); 7433#endif 7434 7435#if GTEST_OS_WINDOWS_MOBILE 7436 LPCWSTR unicode = String::AnsiToUtf16(path.c_str()); 7437 const DWORD attributes = GetFileAttributes(unicode); 7438 delete [] unicode; 7439 if ((attributes != kInvalidFileAttributes) && 7440 (attributes & FILE_ATTRIBUTE_DIRECTORY)) { 7441 result = true; 7442 } 7443#else 7444 posix::StatStruct file_stat; 7445 result = posix::Stat(path.c_str(), &file_stat) == 0 && 7446 posix::IsDir(file_stat); 7447#endif // GTEST_OS_WINDOWS_MOBILE 7448 7449 return result; 7450} 7451 7452// Returns true if pathname describes a root directory. (Windows has one 7453// root directory per disk drive.) 7454bool FilePath::IsRootDirectory() const { 7455#if GTEST_OS_WINDOWS 7456 // TODO(wan@google.com): on Windows a network share like 7457 // \\server\share can be a root directory, although it cannot be the 7458 // current directory. Handle this properly. 7459 return pathname_.length() == 3 && IsAbsolutePath(); 7460#else 7461 return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]); 7462#endif 7463} 7464 7465// Returns true if pathname describes an absolute path. 7466bool FilePath::IsAbsolutePath() const { 7467 const char* const name = pathname_.c_str(); 7468#if GTEST_OS_WINDOWS 7469 return pathname_.length() >= 3 && 7470 ((name[0] >= 'a' && name[0] <= 'z') || 7471 (name[0] >= 'A' && name[0] <= 'Z')) && 7472 name[1] == ':' && 7473 IsPathSeparator(name[2]); 7474#else 7475 return IsPathSeparator(name[0]); 7476#endif 7477} 7478 7479// Returns a pathname for a file that does not currently exist. The pathname 7480// will be directory/base_name.extension or 7481// directory/base_name_<number>.extension if directory/base_name.extension 7482// already exists. The number will be incremented until a pathname is found 7483// that does not already exist. 7484// Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'. 7485// There could be a race condition if two or more processes are calling this 7486// function at the same time -- they could both pick the same filename. 7487FilePath FilePath::GenerateUniqueFileName(const FilePath& directory, 7488 const FilePath& base_name, 7489 const char* extension) { 7490 FilePath full_pathname; 7491 int number = 0; 7492 do { 7493 full_pathname.Set(MakeFileName(directory, base_name, number++, extension)); 7494 } while (full_pathname.FileOrDirectoryExists()); 7495 return full_pathname; 7496} 7497 7498// Returns true if FilePath ends with a path separator, which indicates that 7499// it is intended to represent a directory. Returns false otherwise. 7500// This does NOT check that a directory (or file) actually exists. 7501bool FilePath::IsDirectory() const { 7502 return !pathname_.empty() && 7503 IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]); 7504} 7505 7506// Create directories so that path exists. Returns true if successful or if 7507// the directories already exist; returns false if unable to create directories 7508// for any reason. 7509bool FilePath::CreateDirectoriesRecursively() const { 7510 if (!this->IsDirectory()) { 7511 return false; 7512 } 7513 7514 if (pathname_.length() == 0 || this->DirectoryExists()) { 7515 return true; 7516 } 7517 7518 const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName()); 7519 return parent.CreateDirectoriesRecursively() && this->CreateFolder(); 7520} 7521 7522// Create the directory so that path exists. Returns true if successful or 7523// if the directory already exists; returns false if unable to create the 7524// directory for any reason, including if the parent directory does not 7525// exist. Not named "CreateDirectory" because that's a macro on Windows. 7526bool FilePath::CreateFolder() const { 7527#if GTEST_OS_WINDOWS_MOBILE 7528 FilePath removed_sep(this->RemoveTrailingPathSeparator()); 7529 LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str()); 7530 int result = CreateDirectory(unicode, NULL) ? 0 : -1; 7531 delete [] unicode; 7532#elif GTEST_OS_WINDOWS 7533 int result = _mkdir(pathname_.c_str()); 7534#else 7535 int result = mkdir(pathname_.c_str(), 0777); 7536#endif // GTEST_OS_WINDOWS_MOBILE 7537 7538 if (result == -1) { 7539 return this->DirectoryExists(); // An error is OK if the directory exists. 7540 } 7541 return true; // No error. 7542} 7543 7544// If input name has a trailing separator character, remove it and return the 7545// name, otherwise return the name string unmodified. 7546// On Windows platform, uses \ as the separator, other platforms use /. 7547FilePath FilePath::RemoveTrailingPathSeparator() const { 7548 return IsDirectory() 7549 ? FilePath(String(pathname_.c_str(), pathname_.length() - 1)) 7550 : *this; 7551} 7552 7553// Removes any redundant separators that might be in the pathname. 7554// For example, "bar///foo" becomes "bar/foo". Does not eliminate other 7555// redundancies that might be in a pathname involving "." or "..". 7556// TODO(wan@google.com): handle Windows network shares (e.g. \\server\share). 7557void FilePath::Normalize() { 7558 if (pathname_.c_str() == NULL) { 7559 pathname_ = ""; 7560 return; 7561 } 7562 const char* src = pathname_.c_str(); 7563 char* const dest = new char[pathname_.length() + 1]; 7564 char* dest_ptr = dest; 7565 memset(dest_ptr, 0, pathname_.length() + 1); 7566 7567 while (*src != '\0') { 7568 *dest_ptr = *src; 7569 if (!IsPathSeparator(*src)) { 7570 src++; 7571 } else { 7572#if GTEST_HAS_ALT_PATH_SEP_ 7573 if (*dest_ptr == kAlternatePathSeparator) { 7574 *dest_ptr = kPathSeparator; 7575 } 7576#endif 7577 while (IsPathSeparator(*src)) 7578 src++; 7579 } 7580 dest_ptr++; 7581 } 7582 *dest_ptr = '\0'; 7583 pathname_ = dest; 7584 delete[] dest; 7585} 7586 7587} // namespace internal 7588} // namespace testing 7589// Copyright 2008, Google Inc. 7590// All rights reserved. 7591// 7592// Redistribution and use in source and binary forms, with or without 7593// modification, are permitted provided that the following conditions are 7594// met: 7595// 7596// * Redistributions of source code must retain the above copyright 7597// notice, this list of conditions and the following disclaimer. 7598// * Redistributions in binary form must reproduce the above 7599// copyright notice, this list of conditions and the following disclaimer 7600// in the documentation and/or other materials provided with the 7601// distribution. 7602// * Neither the name of Google Inc. nor the names of its 7603// contributors may be used to endorse or promote products derived from 7604// this software without specific prior written permission. 7605// 7606// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 7607// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 7608// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 7609// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 7610// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 7611// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 7612// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 7613// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 7614// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 7615// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 7616// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 7617// 7618// Author: wan@google.com (Zhanyong Wan) 7619 7620 7621#include <limits.h> 7622#include <stdlib.h> 7623#include <stdio.h> 7624 7625#if GTEST_OS_WINDOWS_MOBILE 7626#include <windows.h> // For TerminateProcess() 7627#elif GTEST_OS_WINDOWS 7628#include <io.h> 7629#include <sys/stat.h> 7630#else 7631#include <unistd.h> 7632#endif // GTEST_OS_WINDOWS_MOBILE 7633 7634#if GTEST_OS_MAC 7635#include <mach/mach_init.h> 7636#include <mach/task.h> 7637#include <mach/vm_map.h> 7638#endif // GTEST_OS_MAC 7639 7640 7641// Indicates that this translation unit is part of Google Test's 7642// implementation. It must come before gtest-internal-inl.h is 7643// included, or there will be a compiler error. This trick is to 7644// prevent a user from accidentally including gtest-internal-inl.h in 7645// his code. 7646#define GTEST_IMPLEMENTATION_ 1 7647#undef GTEST_IMPLEMENTATION_ 7648 7649namespace testing { 7650namespace internal { 7651 7652#if defined(_MSC_VER) || defined(__BORLANDC__) 7653// MSVC and C++Builder do not provide a definition of STDERR_FILENO. 7654const int kStdOutFileno = 1; 7655const int kStdErrFileno = 2; 7656#else 7657const int kStdOutFileno = STDOUT_FILENO; 7658const int kStdErrFileno = STDERR_FILENO; 7659#endif // _MSC_VER 7660 7661#if GTEST_OS_MAC 7662 7663// Returns the number of threads running in the process, or 0 to indicate that 7664// we cannot detect it. 7665size_t GetThreadCount() { 7666 const task_t task = mach_task_self(); 7667 mach_msg_type_number_t thread_count; 7668 thread_act_array_t thread_list; 7669 const kern_return_t status = task_threads(task, &thread_list, &thread_count); 7670 if (status == KERN_SUCCESS) { 7671 // task_threads allocates resources in thread_list and we need to free them 7672 // to avoid leaks. 7673 vm_deallocate(task, 7674 reinterpret_cast<vm_address_t>(thread_list), 7675 sizeof(thread_t) * thread_count); 7676 return static_cast<size_t>(thread_count); 7677 } else { 7678 return 0; 7679 } 7680} 7681 7682#else 7683 7684size_t GetThreadCount() { 7685 // There's no portable way to detect the number of threads, so we just 7686 // return 0 to indicate that we cannot detect it. 7687 return 0; 7688} 7689 7690#endif // GTEST_OS_MAC 7691 7692#if GTEST_USES_POSIX_RE 7693 7694// Implements RE. Currently only needed for death tests. 7695 7696RE::~RE() { 7697 if (is_valid_) { 7698 // regfree'ing an invalid regex might crash because the content 7699 // of the regex is undefined. Since the regex's are essentially 7700 // the same, one cannot be valid (or invalid) without the other 7701 // being so too. 7702 regfree(&partial_regex_); 7703 regfree(&full_regex_); 7704 } 7705 free(const_cast<char*>(pattern_)); 7706} 7707 7708// Returns true iff regular expression re matches the entire str. 7709bool RE::FullMatch(const char* str, const RE& re) { 7710 if (!re.is_valid_) return false; 7711 7712 regmatch_t match; 7713 return regexec(&re.full_regex_, str, 1, &match, 0) == 0; 7714} 7715 7716// Returns true iff regular expression re matches a substring of str 7717// (including str itself). 7718bool RE::PartialMatch(const char* str, const RE& re) { 7719 if (!re.is_valid_) return false; 7720 7721 regmatch_t match; 7722 return regexec(&re.partial_regex_, str, 1, &match, 0) == 0; 7723} 7724 7725// Initializes an RE from its string representation. 7726void RE::Init(const char* regex) { 7727 pattern_ = posix::StrDup(regex); 7728 7729 // Reserves enough bytes to hold the regular expression used for a 7730 // full match. 7731 const size_t full_regex_len = strlen(regex) + 10; 7732 char* const full_pattern = new char[full_regex_len]; 7733 7734 snprintf(full_pattern, full_regex_len, "^(%s)$", regex); 7735 is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0; 7736 // We want to call regcomp(&partial_regex_, ...) even if the 7737 // previous expression returns false. Otherwise partial_regex_ may 7738 // not be properly initialized can may cause trouble when it's 7739 // freed. 7740 // 7741 // Some implementation of POSIX regex (e.g. on at least some 7742 // versions of Cygwin) doesn't accept the empty string as a valid 7743 // regex. We change it to an equivalent form "()" to be safe. 7744 if (is_valid_) { 7745 const char* const partial_regex = (*regex == '\0') ? "()" : regex; 7746 is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0; 7747 } 7748 EXPECT_TRUE(is_valid_) 7749 << "Regular expression \"" << regex 7750 << "\" is not a valid POSIX Extended regular expression."; 7751 7752 delete[] full_pattern; 7753} 7754 7755#elif GTEST_USES_SIMPLE_RE 7756 7757// Returns true iff ch appears anywhere in str (excluding the 7758// terminating '\0' character). 7759bool IsInSet(char ch, const char* str) { 7760 return ch != '\0' && strchr(str, ch) != NULL; 7761} 7762 7763// Returns true iff ch belongs to the given classification. Unlike 7764// similar functions in <ctype.h>, these aren't affected by the 7765// current locale. 7766bool IsDigit(char ch) { return '0' <= ch && ch <= '9'; } 7767bool IsPunct(char ch) { 7768 return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~"); 7769} 7770bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); } 7771bool IsWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); } 7772bool IsWordChar(char ch) { 7773 return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') || 7774 ('0' <= ch && ch <= '9') || ch == '_'; 7775} 7776 7777// Returns true iff "\\c" is a supported escape sequence. 7778bool IsValidEscape(char c) { 7779 return (IsPunct(c) || IsInSet(c, "dDfnrsStvwW")); 7780} 7781 7782// Returns true iff the given atom (specified by escaped and pattern) 7783// matches ch. The result is undefined if the atom is invalid. 7784bool AtomMatchesChar(bool escaped, char pattern_char, char ch) { 7785 if (escaped) { // "\\p" where p is pattern_char. 7786 switch (pattern_char) { 7787 case 'd': return IsDigit(ch); 7788 case 'D': return !IsDigit(ch); 7789 case 'f': return ch == '\f'; 7790 case 'n': return ch == '\n'; 7791 case 'r': return ch == '\r'; 7792 case 's': return IsWhiteSpace(ch); 7793 case 'S': return !IsWhiteSpace(ch); 7794 case 't': return ch == '\t'; 7795 case 'v': return ch == '\v'; 7796 case 'w': return IsWordChar(ch); 7797 case 'W': return !IsWordChar(ch); 7798 } 7799 return IsPunct(pattern_char) && pattern_char == ch; 7800 } 7801 7802 return (pattern_char == '.' && ch != '\n') || pattern_char == ch; 7803} 7804 7805// Helper function used by ValidateRegex() to format error messages. 7806String FormatRegexSyntaxError(const char* regex, int index) { 7807 return (Message() << "Syntax error at index " << index 7808 << " in simple regular expression \"" << regex << "\": ").GetString(); 7809} 7810 7811// Generates non-fatal failures and returns false if regex is invalid; 7812// otherwise returns true. 7813bool ValidateRegex(const char* regex) { 7814 if (regex == NULL) { 7815 // TODO(wan@google.com): fix the source file location in the 7816 // assertion failures to match where the regex is used in user 7817 // code. 7818 ADD_FAILURE() << "NULL is not a valid simple regular expression."; 7819 return false; 7820 } 7821 7822 bool is_valid = true; 7823 7824 // True iff ?, *, or + can follow the previous atom. 7825 bool prev_repeatable = false; 7826 for (int i = 0; regex[i]; i++) { 7827 if (regex[i] == '\\') { // An escape sequence 7828 i++; 7829 if (regex[i] == '\0') { 7830 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1) 7831 << "'\\' cannot appear at the end."; 7832 return false; 7833 } 7834 7835 if (!IsValidEscape(regex[i])) { 7836 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1) 7837 << "invalid escape sequence \"\\" << regex[i] << "\"."; 7838 is_valid = false; 7839 } 7840 prev_repeatable = true; 7841 } else { // Not an escape sequence. 7842 const char ch = regex[i]; 7843 7844 if (ch == '^' && i > 0) { 7845 ADD_FAILURE() << FormatRegexSyntaxError(regex, i) 7846 << "'^' can only appear at the beginning."; 7847 is_valid = false; 7848 } else if (ch == '$' && regex[i + 1] != '\0') { 7849 ADD_FAILURE() << FormatRegexSyntaxError(regex, i) 7850 << "'$' can only appear at the end."; 7851 is_valid = false; 7852 } else if (IsInSet(ch, "()[]{}|")) { 7853 ADD_FAILURE() << FormatRegexSyntaxError(regex, i) 7854 << "'" << ch << "' is unsupported."; 7855 is_valid = false; 7856 } else if (IsRepeat(ch) && !prev_repeatable) { 7857 ADD_FAILURE() << FormatRegexSyntaxError(regex, i) 7858 << "'" << ch << "' can only follow a repeatable token."; 7859 is_valid = false; 7860 } 7861 7862 prev_repeatable = !IsInSet(ch, "^$?*+"); 7863 } 7864 } 7865 7866 return is_valid; 7867} 7868 7869// Matches a repeated regex atom followed by a valid simple regular 7870// expression. The regex atom is defined as c if escaped is false, 7871// or \c otherwise. repeat is the repetition meta character (?, *, 7872// or +). The behavior is undefined if str contains too many 7873// characters to be indexable by size_t, in which case the test will 7874// probably time out anyway. We are fine with this limitation as 7875// std::string has it too. 7876bool MatchRepetitionAndRegexAtHead( 7877 bool escaped, char c, char repeat, const char* regex, 7878 const char* str) { 7879 const size_t min_count = (repeat == '+') ? 1 : 0; 7880 const size_t max_count = (repeat == '?') ? 1 : 7881 static_cast<size_t>(-1) - 1; 7882 // We cannot call numeric_limits::max() as it conflicts with the 7883 // max() macro on Windows. 7884 7885 for (size_t i = 0; i <= max_count; ++i) { 7886 // We know that the atom matches each of the first i characters in str. 7887 if (i >= min_count && MatchRegexAtHead(regex, str + i)) { 7888 // We have enough matches at the head, and the tail matches too. 7889 // Since we only care about *whether* the pattern matches str 7890 // (as opposed to *how* it matches), there is no need to find a 7891 // greedy match. 7892 return true; 7893 } 7894 if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i])) 7895 return false; 7896 } 7897 return false; 7898} 7899 7900// Returns true iff regex matches a prefix of str. regex must be a 7901// valid simple regular expression and not start with "^", or the 7902// result is undefined. 7903bool MatchRegexAtHead(const char* regex, const char* str) { 7904 if (*regex == '\0') // An empty regex matches a prefix of anything. 7905 return true; 7906 7907 // "$" only matches the end of a string. Note that regex being 7908 // valid guarantees that there's nothing after "$" in it. 7909 if (*regex == '$') 7910 return *str == '\0'; 7911 7912 // Is the first thing in regex an escape sequence? 7913 const bool escaped = *regex == '\\'; 7914 if (escaped) 7915 ++regex; 7916 if (IsRepeat(regex[1])) { 7917 // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so 7918 // here's an indirect recursion. It terminates as the regex gets 7919 // shorter in each recursion. 7920 return MatchRepetitionAndRegexAtHead( 7921 escaped, regex[0], regex[1], regex + 2, str); 7922 } else { 7923 // regex isn't empty, isn't "$", and doesn't start with a 7924 // repetition. We match the first atom of regex with the first 7925 // character of str and recurse. 7926 return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) && 7927 MatchRegexAtHead(regex + 1, str + 1); 7928 } 7929} 7930 7931// Returns true iff regex matches any substring of str. regex must be 7932// a valid simple regular expression, or the result is undefined. 7933// 7934// The algorithm is recursive, but the recursion depth doesn't exceed 7935// the regex length, so we won't need to worry about running out of 7936// stack space normally. In rare cases the time complexity can be 7937// exponential with respect to the regex length + the string length, 7938// but usually it's must faster (often close to linear). 7939bool MatchRegexAnywhere(const char* regex, const char* str) { 7940 if (regex == NULL || str == NULL) 7941 return false; 7942 7943 if (*regex == '^') 7944 return MatchRegexAtHead(regex + 1, str); 7945 7946 // A successful match can be anywhere in str. 7947 do { 7948 if (MatchRegexAtHead(regex, str)) 7949 return true; 7950 } while (*str++ != '\0'); 7951 return false; 7952} 7953 7954// Implements the RE class. 7955 7956RE::~RE() { 7957 free(const_cast<char*>(pattern_)); 7958 free(const_cast<char*>(full_pattern_)); 7959} 7960 7961// Returns true iff regular expression re matches the entire str. 7962bool RE::FullMatch(const char* str, const RE& re) { 7963 return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str); 7964} 7965 7966// Returns true iff regular expression re matches a substring of str 7967// (including str itself). 7968bool RE::PartialMatch(const char* str, const RE& re) { 7969 return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str); 7970} 7971 7972// Initializes an RE from its string representation. 7973void RE::Init(const char* regex) { 7974 pattern_ = full_pattern_ = NULL; 7975 if (regex != NULL) { 7976 pattern_ = posix::StrDup(regex); 7977 } 7978 7979 is_valid_ = ValidateRegex(regex); 7980 if (!is_valid_) { 7981 // No need to calculate the full pattern when the regex is invalid. 7982 return; 7983 } 7984 7985 const size_t len = strlen(regex); 7986 // Reserves enough bytes to hold the regular expression used for a 7987 // full match: we need space to prepend a '^', append a '$', and 7988 // terminate the string with '\0'. 7989 char* buffer = static_cast<char*>(malloc(len + 3)); 7990 full_pattern_ = buffer; 7991 7992 if (*regex != '^') 7993 *buffer++ = '^'; // Makes sure full_pattern_ starts with '^'. 7994 7995 // We don't use snprintf or strncpy, as they trigger a warning when 7996 // compiled with VC++ 8.0. 7997 memcpy(buffer, regex, len); 7998 buffer += len; 7999 8000 if (len == 0 || regex[len - 1] != '$') 8001 *buffer++ = '$'; // Makes sure full_pattern_ ends with '$'. 8002 8003 *buffer = '\0'; 8004} 8005 8006#endif // GTEST_USES_POSIX_RE 8007 8008 8009GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line) 8010 : severity_(severity) { 8011 const char* const marker = 8012 severity == GTEST_INFO ? "[ INFO ]" : 8013 severity == GTEST_WARNING ? "[WARNING]" : 8014 severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]"; 8015 GetStream() << ::std::endl << marker << " " 8016 << FormatFileLocation(file, line).c_str() << ": "; 8017} 8018 8019// Flushes the buffers and, if severity is GTEST_FATAL, aborts the program. 8020GTestLog::~GTestLog() { 8021 GetStream() << ::std::endl; 8022 if (severity_ == GTEST_FATAL) { 8023 fflush(stderr); 8024 posix::Abort(); 8025 } 8026} 8027// Disable Microsoft deprecation warnings for POSIX functions called from 8028// this class (creat, dup, dup2, and close) 8029#ifdef _MSC_VER 8030#pragma warning(push) 8031#pragma warning(disable: 4996) 8032#endif // _MSC_VER 8033 8034#if GTEST_HAS_STREAM_REDIRECTION_ 8035 8036// Object that captures an output stream (stdout/stderr). 8037class CapturedStream { 8038 public: 8039 // The ctor redirects the stream to a temporary file. 8040 CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) { 8041#if GTEST_OS_WINDOWS 8042 char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT 8043 char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT 8044 8045 ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path); 8046 const UINT success = ::GetTempFileNameA(temp_dir_path, 8047 "gtest_redir", 8048 0, // Generate unique file name. 8049 temp_file_path); 8050 GTEST_CHECK_(success != 0) 8051 << "Unable to create a temporary file in " << temp_dir_path; 8052 const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE); 8053 GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file " 8054 << temp_file_path; 8055 filename_ = temp_file_path; 8056#else 8057 // There's no guarantee that a test has write access to the 8058 // current directory, so we create the temporary file in the /tmp 8059 // directory instead. 8060 char name_template[] = "/tmp/captured_stream.XXXXXX"; 8061 const int captured_fd = mkstemp(name_template); 8062 filename_ = name_template; 8063#endif // GTEST_OS_WINDOWS 8064 fflush(NULL); 8065 dup2(captured_fd, fd_); 8066 close(captured_fd); 8067 } 8068 8069 ~CapturedStream() { 8070 remove(filename_.c_str()); 8071 } 8072 8073 String GetCapturedString() { 8074 if (uncaptured_fd_ != -1) { 8075 // Restores the original stream. 8076 fflush(NULL); 8077 dup2(uncaptured_fd_, fd_); 8078 close(uncaptured_fd_); 8079 uncaptured_fd_ = -1; 8080 } 8081 8082 FILE* const file = posix::FOpen(filename_.c_str(), "r"); 8083 const String content = ReadEntireFile(file); 8084 posix::FClose(file); 8085 return content; 8086 } 8087 8088 private: 8089 // Reads the entire content of a file as a String. 8090 static String ReadEntireFile(FILE* file); 8091 8092 // Returns the size (in bytes) of a file. 8093 static size_t GetFileSize(FILE* file); 8094 8095 const int fd_; // A stream to capture. 8096 int uncaptured_fd_; 8097 // Name of the temporary file holding the stderr output. 8098 ::std::string filename_; 8099 8100 GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream); 8101}; 8102 8103// Returns the size (in bytes) of a file. 8104size_t CapturedStream::GetFileSize(FILE* file) { 8105 fseek(file, 0, SEEK_END); 8106 return static_cast<size_t>(ftell(file)); 8107} 8108 8109// Reads the entire content of a file as a string. 8110String CapturedStream::ReadEntireFile(FILE* file) { 8111 const size_t file_size = GetFileSize(file); 8112 char* const buffer = new char[file_size]; 8113 8114 size_t bytes_last_read = 0; // # of bytes read in the last fread() 8115 size_t bytes_read = 0; // # of bytes read so far 8116 8117 fseek(file, 0, SEEK_SET); 8118 8119 // Keeps reading the file until we cannot read further or the 8120 // pre-determined file size is reached. 8121 do { 8122 bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file); 8123 bytes_read += bytes_last_read; 8124 } while (bytes_last_read > 0 && bytes_read < file_size); 8125 8126 const String content(buffer, bytes_read); 8127 delete[] buffer; 8128 8129 return content; 8130} 8131 8132#ifdef _MSC_VER 8133#pragma warning(pop) 8134#endif // _MSC_VER 8135 8136static CapturedStream* g_captured_stderr = NULL; 8137static CapturedStream* g_captured_stdout = NULL; 8138 8139// Starts capturing an output stream (stdout/stderr). 8140void CaptureStream(int fd, const char* stream_name, CapturedStream** stream) { 8141 if (*stream != NULL) { 8142 GTEST_LOG_(FATAL) << "Only one " << stream_name 8143 << " capturer can exist at a time."; 8144 } 8145 *stream = new CapturedStream(fd); 8146} 8147 8148// Stops capturing the output stream and returns the captured string. 8149String GetCapturedStream(CapturedStream** captured_stream) { 8150 const String content = (*captured_stream)->GetCapturedString(); 8151 8152 delete *captured_stream; 8153 *captured_stream = NULL; 8154 8155 return content; 8156} 8157 8158// Starts capturing stdout. 8159void CaptureStdout() { 8160 CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout); 8161} 8162 8163// Starts capturing stderr. 8164void CaptureStderr() { 8165 CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr); 8166} 8167 8168// Stops capturing stdout and returns the captured string. 8169String GetCapturedStdout() { return GetCapturedStream(&g_captured_stdout); } 8170 8171// Stops capturing stderr and returns the captured string. 8172String GetCapturedStderr() { return GetCapturedStream(&g_captured_stderr); } 8173 8174#endif // GTEST_HAS_STREAM_REDIRECTION_ 8175 8176#if GTEST_HAS_DEATH_TEST 8177 8178// A copy of all command line arguments. Set by InitGoogleTest(). 8179::std::vector<String> g_argvs; 8180 8181// Returns the command line as a vector of strings. 8182const ::std::vector<String>& GetArgvs() { return g_argvs; } 8183 8184#endif // GTEST_HAS_DEATH_TEST 8185 8186#if GTEST_OS_WINDOWS_MOBILE 8187namespace posix { 8188void Abort() { 8189 DebugBreak(); 8190 TerminateProcess(GetCurrentProcess(), 1); 8191} 8192} // namespace posix 8193#endif // GTEST_OS_WINDOWS_MOBILE 8194 8195// Returns the name of the environment variable corresponding to the 8196// given flag. For example, FlagToEnvVar("foo") will return 8197// "GTEST_FOO" in the open-source version. 8198static String FlagToEnvVar(const char* flag) { 8199 const String full_flag = 8200 (Message() << GTEST_FLAG_PREFIX_ << flag).GetString(); 8201 8202 Message env_var; 8203 for (size_t i = 0; i != full_flag.length(); i++) { 8204 env_var << static_cast<char>(toupper(full_flag.c_str()[i])); 8205 } 8206 8207 return env_var.GetString(); 8208} 8209 8210// Parses 'str' for a 32-bit signed integer. If successful, writes 8211// the result to *value and returns true; otherwise leaves *value 8212// unchanged and returns false. 8213bool ParseInt32(const Message& src_text, const char* str, Int32* value) { 8214 // Parses the environment variable as a decimal integer. 8215 char* end = NULL; 8216 const long long_value = strtol(str, &end, 10); // NOLINT 8217 8218 // Has strtol() consumed all characters in the string? 8219 if (*end != '\0') { 8220 // No - an invalid character was encountered. 8221 Message msg; 8222 msg << "WARNING: " << src_text 8223 << " is expected to be a 32-bit integer, but actually" 8224 << " has value \"" << str << "\".\n"; 8225 printf("%s", msg.GetString().c_str()); 8226 fflush(stdout); 8227 return false; 8228 } 8229 8230 // Is the parsed value in the range of an Int32? 8231 const Int32 result = static_cast<Int32>(long_value); 8232 if (long_value == LONG_MAX || long_value == LONG_MIN || 8233 // The parsed value overflows as a long. (strtol() returns 8234 // LONG_MAX or LONG_MIN when the input overflows.) 8235 result != long_value 8236 // The parsed value overflows as an Int32. 8237 ) { 8238 Message msg; 8239 msg << "WARNING: " << src_text 8240 << " is expected to be a 32-bit integer, but actually" 8241 << " has value " << str << ", which overflows.\n"; 8242 printf("%s", msg.GetString().c_str()); 8243 fflush(stdout); 8244 return false; 8245 } 8246 8247 *value = result; 8248 return true; 8249} 8250 8251// Reads and returns the Boolean environment variable corresponding to 8252// the given flag; if it's not set, returns default_value. 8253// 8254// The value is considered true iff it's not "0". 8255bool BoolFromGTestEnv(const char* flag, bool default_value) { 8256 const String env_var = FlagToEnvVar(flag); 8257 const char* const string_value = posix::GetEnv(env_var.c_str()); 8258 return string_value == NULL ? 8259 default_value : strcmp(string_value, "0") != 0; 8260} 8261 8262// Reads and returns a 32-bit integer stored in the environment 8263// variable corresponding to the given flag; if it isn't set or 8264// doesn't represent a valid 32-bit integer, returns default_value. 8265Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) { 8266 const String env_var = FlagToEnvVar(flag); 8267 const char* const string_value = posix::GetEnv(env_var.c_str()); 8268 if (string_value == NULL) { 8269 // The environment variable is not set. 8270 return default_value; 8271 } 8272 8273 Int32 result = default_value; 8274 if (!ParseInt32(Message() << "Environment variable " << env_var, 8275 string_value, &result)) { 8276 printf("The default value %s is used.\n", 8277 (Message() << default_value).GetString().c_str()); 8278 fflush(stdout); 8279 return default_value; 8280 } 8281 8282 return result; 8283} 8284 8285// Reads and returns the string environment variable corresponding to 8286// the given flag; if it's not set, returns default_value. 8287const char* StringFromGTestEnv(const char* flag, const char* default_value) { 8288 const String env_var = FlagToEnvVar(flag); 8289 const char* const value = posix::GetEnv(env_var.c_str()); 8290 return value == NULL ? default_value : value; 8291} 8292 8293} // namespace internal 8294} // namespace testing 8295// Copyright 2008, Google Inc. 8296// All rights reserved. 8297// 8298// Redistribution and use in source and binary forms, with or without 8299// modification, are permitted provided that the following conditions are 8300// met: 8301// 8302// * Redistributions of source code must retain the above copyright 8303// notice, this list of conditions and the following disclaimer. 8304// * Redistributions in binary form must reproduce the above 8305// copyright notice, this list of conditions and the following disclaimer 8306// in the documentation and/or other materials provided with the 8307// distribution. 8308// * Neither the name of Google Inc. nor the names of its 8309// contributors may be used to endorse or promote products derived from 8310// this software without specific prior written permission. 8311// 8312// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 8313// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 8314// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 8315// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 8316// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 8317// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 8318// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 8319// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 8320// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 8321// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 8322// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 8323// 8324// Author: mheule@google.com (Markus Heule) 8325// 8326// The Google C++ Testing Framework (Google Test) 8327 8328 8329// Indicates that this translation unit is part of Google Test's 8330// implementation. It must come before gtest-internal-inl.h is 8331// included, or there will be a compiler error. This trick is to 8332// prevent a user from accidentally including gtest-internal-inl.h in 8333// his code. 8334#define GTEST_IMPLEMENTATION_ 1 8335#undef GTEST_IMPLEMENTATION_ 8336 8337namespace testing { 8338 8339using internal::GetUnitTestImpl; 8340 8341// Gets the summary of the failure message by omitting the stack trace 8342// in it. 8343internal::String TestPartResult::ExtractSummary(const char* message) { 8344 const char* const stack_trace = strstr(message, internal::kStackTraceMarker); 8345 return stack_trace == NULL ? internal::String(message) : 8346 internal::String(message, stack_trace - message); 8347} 8348 8349// Prints a TestPartResult object. 8350std::ostream& operator<<(std::ostream& os, const TestPartResult& result) { 8351 return os 8352 << result.file_name() << ":" << result.line_number() << ": " 8353 << (result.type() == TestPartResult::kSuccess ? "Success" : 8354 result.type() == TestPartResult::kFatalFailure ? "Fatal failure" : 8355 "Non-fatal failure") << ":\n" 8356 << result.message() << std::endl; 8357} 8358 8359// Appends a TestPartResult to the array. 8360void TestPartResultArray::Append(const TestPartResult& result) { 8361 array_.push_back(result); 8362} 8363 8364// Returns the TestPartResult at the given index (0-based). 8365const TestPartResult& TestPartResultArray::GetTestPartResult(int index) const { 8366 if (index < 0 || index >= size()) { 8367 printf("\nInvalid index (%d) into TestPartResultArray.\n", index); 8368 internal::posix::Abort(); 8369 } 8370 8371 return array_[index]; 8372} 8373 8374// Returns the number of TestPartResult objects in the array. 8375int TestPartResultArray::size() const { 8376 return static_cast<int>(array_.size()); 8377} 8378 8379namespace internal { 8380 8381HasNewFatalFailureHelper::HasNewFatalFailureHelper() 8382 : has_new_fatal_failure_(false), 8383 original_reporter_(GetUnitTestImpl()-> 8384 GetTestPartResultReporterForCurrentThread()) { 8385 GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this); 8386} 8387 8388HasNewFatalFailureHelper::~HasNewFatalFailureHelper() { 8389 GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread( 8390 original_reporter_); 8391} 8392 8393void HasNewFatalFailureHelper::ReportTestPartResult( 8394 const TestPartResult& result) { 8395 if (result.fatally_failed()) 8396 has_new_fatal_failure_ = true; 8397 original_reporter_->ReportTestPartResult(result); 8398} 8399 8400} // namespace internal 8401 8402} // namespace testing 8403// Copyright 2008 Google Inc. 8404// All Rights Reserved. 8405// 8406// Redistribution and use in source and binary forms, with or without 8407// modification, are permitted provided that the following conditions are 8408// met: 8409// 8410// * Redistributions of source code must retain the above copyright 8411// notice, this list of conditions and the following disclaimer. 8412// * Redistributions in binary form must reproduce the above 8413// copyright notice, this list of conditions and the following disclaimer 8414// in the documentation and/or other materials provided with the 8415// distribution. 8416// * Neither the name of Google Inc. nor the names of its 8417// contributors may be used to endorse or promote products derived from 8418// this software without specific prior written permission. 8419// 8420// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 8421// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 8422// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 8423// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 8424// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 8425// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 8426// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 8427// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 8428// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 8429// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 8430// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 8431// 8432// Author: wan@google.com (Zhanyong Wan) 8433 8434 8435namespace testing { 8436namespace internal { 8437 8438#if GTEST_HAS_TYPED_TEST_P 8439 8440// Skips to the first non-space char in str. Returns an empty string if str 8441// contains only whitespace characters. 8442static const char* SkipSpaces(const char* str) { 8443 while (isspace(*str)) 8444 str++; 8445 return str; 8446} 8447 8448// Verifies that registered_tests match the test names in 8449// defined_test_names_; returns registered_tests if successful, or 8450// aborts the program otherwise. 8451const char* TypedTestCasePState::VerifyRegisteredTestNames( 8452 const char* file, int line, const char* registered_tests) { 8453 typedef ::std::set<const char*>::const_iterator DefinedTestIter; 8454 registered_ = true; 8455 8456 // Skip initial whitespace in registered_tests since some 8457 // preprocessors prefix stringizied literals with whitespace. 8458 registered_tests = SkipSpaces(registered_tests); 8459 8460 Message errors; 8461 ::std::set<String> tests; 8462 for (const char* names = registered_tests; names != NULL; 8463 names = SkipComma(names)) { 8464 const String name = GetPrefixUntilComma(names); 8465 if (tests.count(name) != 0) { 8466 errors << "Test " << name << " is listed more than once.\n"; 8467 continue; 8468 } 8469 8470 bool found = false; 8471 for (DefinedTestIter it = defined_test_names_.begin(); 8472 it != defined_test_names_.end(); 8473 ++it) { 8474 if (name == *it) { 8475 found = true; 8476 break; 8477 } 8478 } 8479 8480 if (found) { 8481 tests.insert(name); 8482 } else { 8483 errors << "No test named " << name 8484 << " can be found in this test case.\n"; 8485 } 8486 } 8487 8488 for (DefinedTestIter it = defined_test_names_.begin(); 8489 it != defined_test_names_.end(); 8490 ++it) { 8491 if (tests.count(*it) == 0) { 8492 errors << "You forgot to list test " << *it << ".\n"; 8493 } 8494 } 8495 8496 const String& errors_str = errors.GetString(); 8497 if (errors_str != "") { 8498 fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(), 8499 errors_str.c_str()); 8500 fflush(stderr); 8501 posix::Abort(); 8502 } 8503 8504 return registered_tests; 8505} 8506 8507#endif // GTEST_HAS_TYPED_TEST_P 8508 8509} // namespace internal 8510} // namespace testing 8511