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