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