1 // Copyright 2005, Google Inc. 2 // All rights reserved. 3 // 4 // Redistribution and use in source and binary forms, with or without 5 // modification, are permitted provided that the following conditions are 6 // met: 7 // 8 // * Redistributions of source code must retain the above copyright 9 // notice, this list of conditions and the following disclaimer. 10 // * Redistributions in binary form must reproduce the above 11 // copyright notice, this list of conditions and the following disclaimer 12 // in the documentation and/or other materials provided with the 13 // distribution. 14 // * Neither the name of Google Inc. nor the names of its 15 // contributors may be used to endorse or promote products derived from 16 // this software without specific prior written permission. 17 // 18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 30 // Utility functions and classes used by the Google C++ testing framework. 31 // 32 // Author: wan (at) google.com (Zhanyong Wan) 33 // 34 // This file contains purely Google Test's internal implementation. Please 35 // DO NOT #INCLUDE IT IN A USER PROGRAM. 36 37 #ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_ 38 #define GTEST_SRC_GTEST_INTERNAL_INL_H_ 39 40 // GTEST_IMPLEMENTATION_ is defined to 1 iff the current translation unit is 41 // part of Google Test's implementation; otherwise it's undefined. 42 #if !GTEST_IMPLEMENTATION_ 43 // A user is trying to include this from his code - just say no. 44 #error "gtest-internal-inl.h is part of Google Test's internal implementation." 45 #error "It must not be included except by Google Test itself." 46 #endif // GTEST_IMPLEMENTATION_ 47 48 #ifndef _WIN32_WCE 49 #include <errno.h> 50 #endif // !_WIN32_WCE 51 #include <stddef.h> 52 #include <stdlib.h> // For strtoll/_strtoul64/malloc/free. 53 #include <string.h> // For memmove. 54 55 #include <algorithm> 56 #include <string> 57 #include <vector> 58 59 #include <gtest/internal/gtest-port.h> 60 61 #if GTEST_OS_WINDOWS 62 #include <windows.h> // For DWORD. 63 #endif // GTEST_OS_WINDOWS 64 65 #include <gtest/gtest.h> // NOLINT 66 #include <gtest/gtest-spi.h> 67 68 namespace testing { 69 70 // Declares the flags. 71 // 72 // We don't want the users to modify this flag in the code, but want 73 // Google Test's own unit tests to be able to access it. Therefore we 74 // declare it here as opposed to in gtest.h. 75 GTEST_DECLARE_bool_(death_test_use_fork); 76 77 namespace internal { 78 79 // The value of GetTestTypeId() as seen from within the Google Test 80 // library. This is solely for testing GetTestTypeId(). 81 GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest; 82 83 // Names of the flags (needed for parsing Google Test flags). 84 const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests"; 85 const char kBreakOnFailureFlag[] = "break_on_failure"; 86 const char kCatchExceptionsFlag[] = "catch_exceptions"; 87 const char kColorFlag[] = "color"; 88 const char kFilterFlag[] = "filter"; 89 const char kListTestsFlag[] = "list_tests"; 90 const char kOutputFlag[] = "output"; 91 const char kPrintTimeFlag[] = "print_time"; 92 const char kRandomSeedFlag[] = "random_seed"; 93 const char kRepeatFlag[] = "repeat"; 94 const char kShuffleFlag[] = "shuffle"; 95 const char kStackTraceDepthFlag[] = "stack_trace_depth"; 96 const char kThrowOnFailureFlag[] = "throw_on_failure"; 97 98 // A valid random seed must be in [1, kMaxRandomSeed]. 99 const int kMaxRandomSeed = 99999; 100 101 // g_help_flag is true iff the --help flag or an equivalent form is 102 // specified on the command line. 103 GTEST_API_ extern bool g_help_flag; 104 105 // Returns the current time in milliseconds. 106 GTEST_API_ TimeInMillis GetTimeInMillis(); 107 108 // Returns true iff Google Test should use colors in the output. 109 GTEST_API_ bool ShouldUseColor(bool stdout_is_tty); 110 111 // Formats the given time in milliseconds as seconds. 112 GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms); 113 114 // Parses a string for an Int32 flag, in the form of "--flag=value". 115 // 116 // On success, stores the value of the flag in *value, and returns 117 // true. On failure, returns false without changing *value. 118 GTEST_API_ bool ParseInt32Flag( 119 const char* str, const char* flag, Int32* value); 120 121 // Returns a random seed in range [1, kMaxRandomSeed] based on the 122 // given --gtest_random_seed flag value. 123 inline int GetRandomSeedFromFlag(Int32 random_seed_flag) { 124 const unsigned int raw_seed = (random_seed_flag == 0) ? 125 static_cast<unsigned int>(GetTimeInMillis()) : 126 static_cast<unsigned int>(random_seed_flag); 127 128 // Normalizes the actual seed to range [1, kMaxRandomSeed] such that 129 // it's easy to type. 130 const int normalized_seed = 131 static_cast<int>((raw_seed - 1U) % 132 static_cast<unsigned int>(kMaxRandomSeed)) + 1; 133 return normalized_seed; 134 } 135 136 // Returns the first valid random seed after 'seed'. The behavior is 137 // undefined if 'seed' is invalid. The seed after kMaxRandomSeed is 138 // considered to be 1. 139 inline int GetNextRandomSeed(int seed) { 140 GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed) 141 << "Invalid random seed " << seed << " - must be in [1, " 142 << kMaxRandomSeed << "]."; 143 const int next_seed = seed + 1; 144 return (next_seed > kMaxRandomSeed) ? 1 : next_seed; 145 } 146 147 // This class saves the values of all Google Test flags in its c'tor, and 148 // restores them in its d'tor. 149 class GTestFlagSaver { 150 public: 151 // The c'tor. 152 GTestFlagSaver() { 153 also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests); 154 break_on_failure_ = GTEST_FLAG(break_on_failure); 155 catch_exceptions_ = GTEST_FLAG(catch_exceptions); 156 color_ = GTEST_FLAG(color); 157 death_test_style_ = GTEST_FLAG(death_test_style); 158 death_test_use_fork_ = GTEST_FLAG(death_test_use_fork); 159 filter_ = GTEST_FLAG(filter); 160 internal_run_death_test_ = GTEST_FLAG(internal_run_death_test); 161 list_tests_ = GTEST_FLAG(list_tests); 162 output_ = GTEST_FLAG(output); 163 print_time_ = GTEST_FLAG(print_time); 164 random_seed_ = GTEST_FLAG(random_seed); 165 repeat_ = GTEST_FLAG(repeat); 166 shuffle_ = GTEST_FLAG(shuffle); 167 stack_trace_depth_ = GTEST_FLAG(stack_trace_depth); 168 throw_on_failure_ = GTEST_FLAG(throw_on_failure); 169 } 170 171 // The d'tor is not virtual. DO NOT INHERIT FROM THIS CLASS. 172 ~GTestFlagSaver() { 173 GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_; 174 GTEST_FLAG(break_on_failure) = break_on_failure_; 175 GTEST_FLAG(catch_exceptions) = catch_exceptions_; 176 GTEST_FLAG(color) = color_; 177 GTEST_FLAG(death_test_style) = death_test_style_; 178 GTEST_FLAG(death_test_use_fork) = death_test_use_fork_; 179 GTEST_FLAG(filter) = filter_; 180 GTEST_FLAG(internal_run_death_test) = internal_run_death_test_; 181 GTEST_FLAG(list_tests) = list_tests_; 182 GTEST_FLAG(output) = output_; 183 GTEST_FLAG(print_time) = print_time_; 184 GTEST_FLAG(random_seed) = random_seed_; 185 GTEST_FLAG(repeat) = repeat_; 186 GTEST_FLAG(shuffle) = shuffle_; 187 GTEST_FLAG(stack_trace_depth) = stack_trace_depth_; 188 GTEST_FLAG(throw_on_failure) = throw_on_failure_; 189 } 190 private: 191 // Fields for saving the original values of flags. 192 bool also_run_disabled_tests_; 193 bool break_on_failure_; 194 bool catch_exceptions_; 195 String color_; 196 String death_test_style_; 197 bool death_test_use_fork_; 198 String filter_; 199 String internal_run_death_test_; 200 bool list_tests_; 201 String output_; 202 bool print_time_; 203 bool pretty_; 204 internal::Int32 random_seed_; 205 internal::Int32 repeat_; 206 bool shuffle_; 207 internal::Int32 stack_trace_depth_; 208 bool throw_on_failure_; 209 } GTEST_ATTRIBUTE_UNUSED_; 210 211 // Converts a Unicode code point to a narrow string in UTF-8 encoding. 212 // code_point parameter is of type UInt32 because wchar_t may not be 213 // wide enough to contain a code point. 214 // The output buffer str must containt at least 32 characters. 215 // The function returns the address of the output buffer. 216 // If the code_point is not a valid Unicode code point 217 // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be output 218 // as '(Invalid Unicode 0xXXXXXXXX)'. 219 GTEST_API_ char* CodePointToUtf8(UInt32 code_point, char* str); 220 221 // Converts a wide string to a narrow string in UTF-8 encoding. 222 // The wide string is assumed to have the following encoding: 223 // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS) 224 // UTF-32 if sizeof(wchar_t) == 4 (on Linux) 225 // Parameter str points to a null-terminated wide string. 226 // Parameter num_chars may additionally limit the number 227 // of wchar_t characters processed. -1 is used when the entire string 228 // should be processed. 229 // If the string contains code points that are not valid Unicode code points 230 // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output 231 // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding 232 // and contains invalid UTF-16 surrogate pairs, values in those pairs 233 // will be encoded as individual Unicode characters from Basic Normal Plane. 234 GTEST_API_ String WideStringToUtf8(const wchar_t* str, int num_chars); 235 236 // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file 237 // if the variable is present. If a file already exists at this location, this 238 // function will write over it. If the variable is present, but the file cannot 239 // be created, prints an error and exits. 240 void WriteToShardStatusFileIfNeeded(); 241 242 // Checks whether sharding is enabled by examining the relevant 243 // environment variable values. If the variables are present, 244 // but inconsistent (e.g., shard_index >= total_shards), prints 245 // an error and exits. If in_subprocess_for_death_test, sharding is 246 // disabled because it must only be applied to the original test 247 // process. Otherwise, we could filter out death tests we intended to execute. 248 GTEST_API_ bool ShouldShard(const char* total_shards_str, 249 const char* shard_index_str, 250 bool in_subprocess_for_death_test); 251 252 // Parses the environment variable var as an Int32. If it is unset, 253 // returns default_val. If it is not an Int32, prints an error and 254 // and aborts. 255 GTEST_API_ Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val); 256 257 // Given the total number of shards, the shard index, and the test id, 258 // returns true iff the test should be run on this shard. The test id is 259 // some arbitrary but unique non-negative integer assigned to each test 260 // method. Assumes that 0 <= shard_index < total_shards. 261 GTEST_API_ bool ShouldRunTestOnShard( 262 int total_shards, int shard_index, int test_id); 263 264 // STL container utilities. 265 266 // Returns the number of elements in the given container that satisfy 267 // the given predicate. 268 template <class Container, typename Predicate> 269 inline int CountIf(const Container& c, Predicate predicate) { 270 return static_cast<int>(std::count_if(c.begin(), c.end(), predicate)); 271 } 272 273 // Applies a function/functor to each element in the container. 274 template <class Container, typename Functor> 275 void ForEach(const Container& c, Functor functor) { 276 std::for_each(c.begin(), c.end(), functor); 277 } 278 279 // Returns the i-th element of the vector, or default_value if i is not 280 // in range [0, v.size()). 281 template <typename E> 282 inline E GetElementOr(const std::vector<E>& v, int i, E default_value) { 283 return (i < 0 || i >= static_cast<int>(v.size())) ? default_value : v[i]; 284 } 285 286 // Performs an in-place shuffle of a range of the vector's elements. 287 // 'begin' and 'end' are element indices as an STL-style range; 288 // i.e. [begin, end) are shuffled, where 'end' == size() means to 289 // shuffle to the end of the vector. 290 template <typename E> 291 void ShuffleRange(internal::Random* random, int begin, int end, 292 std::vector<E>* v) { 293 const int size = static_cast<int>(v->size()); 294 GTEST_CHECK_(0 <= begin && begin <= size) 295 << "Invalid shuffle range start " << begin << ": must be in range [0, " 296 << size << "]."; 297 GTEST_CHECK_(begin <= end && end <= size) 298 << "Invalid shuffle range finish " << end << ": must be in range [" 299 << begin << ", " << size << "]."; 300 301 // Fisher-Yates shuffle, from 302 // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle 303 for (int range_width = end - begin; range_width >= 2; range_width--) { 304 const int last_in_range = begin + range_width - 1; 305 const int selected = begin + random->Generate(range_width); 306 std::swap((*v)[selected], (*v)[last_in_range]); 307 } 308 } 309 310 // Performs an in-place shuffle of the vector's elements. 311 template <typename E> 312 inline void Shuffle(internal::Random* random, std::vector<E>* v) { 313 ShuffleRange(random, 0, static_cast<int>(v->size()), v); 314 } 315 316 // A function for deleting an object. Handy for being used as a 317 // functor. 318 template <typename T> 319 static void Delete(T* x) { 320 delete x; 321 } 322 323 // A predicate that checks the key of a TestProperty against a known key. 324 // 325 // TestPropertyKeyIs is copyable. 326 class TestPropertyKeyIs { 327 public: 328 // Constructor. 329 // 330 // TestPropertyKeyIs has NO default constructor. 331 explicit TestPropertyKeyIs(const char* key) 332 : key_(key) {} 333 334 // Returns true iff the test name of test property matches on key_. 335 bool operator()(const TestProperty& test_property) const { 336 return String(test_property.key()).Compare(key_) == 0; 337 } 338 339 private: 340 String key_; 341 }; 342 343 class TestInfoImpl { 344 public: 345 TestInfoImpl(TestInfo* parent, const char* test_case_name, 346 const char* name, const char* test_case_comment, 347 const char* comment, TypeId fixture_class_id, 348 internal::TestFactoryBase* factory); 349 ~TestInfoImpl(); 350 351 // Returns true if this test should run. 352 bool should_run() const { return should_run_; } 353 354 // Sets the should_run member. 355 void set_should_run(bool should) { should_run_ = should; } 356 357 // Returns true if this test is disabled. Disabled tests are not run. 358 bool is_disabled() const { return is_disabled_; } 359 360 // Sets the is_disabled member. 361 void set_is_disabled(bool is) { is_disabled_ = is; } 362 363 // Returns true if this test matches the filter specified by the user. 364 bool matches_filter() const { return matches_filter_; } 365 366 // Sets the matches_filter member. 367 void set_matches_filter(bool matches) { matches_filter_ = matches; } 368 369 // Returns the test case name. 370 const char* test_case_name() const { return test_case_name_.c_str(); } 371 372 // Returns the test name. 373 const char* name() const { return name_.c_str(); } 374 375 // Returns the test case comment. 376 const char* test_case_comment() const { return test_case_comment_.c_str(); } 377 378 // Returns the test comment. 379 const char* comment() const { return comment_.c_str(); } 380 381 // Returns the ID of the test fixture class. 382 TypeId fixture_class_id() const { return fixture_class_id_; } 383 384 // Returns the test result. 385 TestResult* result() { return &result_; } 386 const TestResult* result() const { return &result_; } 387 388 // Creates the test object, runs it, records its result, and then 389 // deletes it. 390 void Run(); 391 392 // Clears the test result. 393 void ClearResult() { result_.Clear(); } 394 395 // Clears the test result in the given TestInfo object. 396 static void ClearTestResult(TestInfo * test_info) { 397 test_info->impl()->ClearResult(); 398 } 399 400 private: 401 // These fields are immutable properties of the test. 402 TestInfo* const parent_; // The owner of this object 403 const String test_case_name_; // Test case name 404 const String name_; // Test name 405 const String test_case_comment_; // Test case comment 406 const String comment_; // Test comment 407 const TypeId fixture_class_id_; // ID of the test fixture class 408 bool should_run_; // True iff this test should run 409 bool is_disabled_; // True iff this test is disabled 410 bool matches_filter_; // True if this test matches the 411 // user-specified filter. 412 internal::TestFactoryBase* const factory_; // The factory that creates 413 // the test object 414 415 // This field is mutable and needs to be reset before running the 416 // test for the second time. 417 TestResult result_; 418 419 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestInfoImpl); 420 }; 421 422 // Class UnitTestOptions. 423 // 424 // This class contains functions for processing options the user 425 // specifies when running the tests. It has only static members. 426 // 427 // In most cases, the user can specify an option using either an 428 // environment variable or a command line flag. E.g. you can set the 429 // test filter using either GTEST_FILTER or --gtest_filter. If both 430 // the variable and the flag are present, the latter overrides the 431 // former. 432 class GTEST_API_ UnitTestOptions { 433 public: 434 // Functions for processing the gtest_output flag. 435 436 // Returns the output format, or "" for normal printed output. 437 static String GetOutputFormat(); 438 439 // Returns the absolute path of the requested output file, or the 440 // default (test_detail.xml in the original working directory) if 441 // none was explicitly specified. 442 static String GetAbsolutePathToOutputFile(); 443 444 // Functions for processing the gtest_filter flag. 445 446 // Returns true iff the wildcard pattern matches the string. The 447 // first ':' or '\0' character in pattern marks the end of it. 448 // 449 // This recursive algorithm isn't very efficient, but is clear and 450 // works well enough for matching test names, which are short. 451 static bool PatternMatchesString(const char *pattern, const char *str); 452 453 // Returns true iff the user-specified filter matches the test case 454 // name and the test name. 455 static bool FilterMatchesTest(const String &test_case_name, 456 const String &test_name); 457 458 #if GTEST_OS_WINDOWS 459 // Function for supporting the gtest_catch_exception flag. 460 461 // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the 462 // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise. 463 // This function is useful as an __except condition. 464 static int GTestShouldProcessSEH(DWORD exception_code); 465 #endif // GTEST_OS_WINDOWS 466 467 // Returns true if "name" matches the ':' separated list of glob-style 468 // filters in "filter". 469 static bool MatchesFilter(const String& name, const char* filter); 470 }; 471 472 // Returns the current application's name, removing directory path if that 473 // is present. Used by UnitTestOptions::GetOutputFile. 474 GTEST_API_ FilePath GetCurrentExecutableName(); 475 476 // The role interface for getting the OS stack trace as a string. 477 class OsStackTraceGetterInterface { 478 public: 479 OsStackTraceGetterInterface() {} 480 virtual ~OsStackTraceGetterInterface() {} 481 482 // Returns the current OS stack trace as a String. Parameters: 483 // 484 // max_depth - the maximum number of stack frames to be included 485 // in the trace. 486 // skip_count - the number of top frames to be skipped; doesn't count 487 // against max_depth. 488 virtual String CurrentStackTrace(int max_depth, int skip_count) = 0; 489 490 // UponLeavingGTest() should be called immediately before Google Test calls 491 // user code. It saves some information about the current stack that 492 // CurrentStackTrace() will use to find and hide Google Test stack frames. 493 virtual void UponLeavingGTest() = 0; 494 495 private: 496 GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface); 497 }; 498 499 // A working implementation of the OsStackTraceGetterInterface interface. 500 class OsStackTraceGetter : public OsStackTraceGetterInterface { 501 public: 502 OsStackTraceGetter() : caller_frame_(NULL) {} 503 virtual String CurrentStackTrace(int max_depth, int skip_count); 504 virtual void UponLeavingGTest(); 505 506 // This string is inserted in place of stack frames that are part of 507 // Google Test's implementation. 508 static const char* const kElidedFramesMarker; 509 510 private: 511 Mutex mutex_; // protects all internal state 512 513 // We save the stack frame below the frame that calls user code. 514 // We do this because the address of the frame immediately below 515 // the user code changes between the call to UponLeavingGTest() 516 // and any calls to CurrentStackTrace() from within the user code. 517 void* caller_frame_; 518 519 GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter); 520 }; 521 522 // Information about a Google Test trace point. 523 struct TraceInfo { 524 const char* file; 525 int line; 526 String message; 527 }; 528 529 // This is the default global test part result reporter used in UnitTestImpl. 530 // This class should only be used by UnitTestImpl. 531 class DefaultGlobalTestPartResultReporter 532 : public TestPartResultReporterInterface { 533 public: 534 explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test); 535 // Implements the TestPartResultReporterInterface. Reports the test part 536 // result in the current test. 537 virtual void ReportTestPartResult(const TestPartResult& result); 538 539 private: 540 UnitTestImpl* const unit_test_; 541 542 GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter); 543 }; 544 545 // This is the default per thread test part result reporter used in 546 // UnitTestImpl. This class should only be used by UnitTestImpl. 547 class DefaultPerThreadTestPartResultReporter 548 : public TestPartResultReporterInterface { 549 public: 550 explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test); 551 // Implements the TestPartResultReporterInterface. The implementation just 552 // delegates to the current global test part result reporter of *unit_test_. 553 virtual void ReportTestPartResult(const TestPartResult& result); 554 555 private: 556 UnitTestImpl* const unit_test_; 557 558 GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter); 559 }; 560 561 // The private implementation of the UnitTest class. We don't protect 562 // the methods under a mutex, as this class is not accessible by a 563 // user and the UnitTest class that delegates work to this class does 564 // proper locking. 565 class GTEST_API_ UnitTestImpl { 566 public: 567 explicit UnitTestImpl(UnitTest* parent); 568 virtual ~UnitTestImpl(); 569 570 // There are two different ways to register your own TestPartResultReporter. 571 // You can register your own repoter to listen either only for test results 572 // from the current thread or for results from all threads. 573 // By default, each per-thread test result repoter just passes a new 574 // TestPartResult to the global test result reporter, which registers the 575 // test part result for the currently running test. 576 577 // Returns the global test part result reporter. 578 TestPartResultReporterInterface* GetGlobalTestPartResultReporter(); 579 580 // Sets the global test part result reporter. 581 void SetGlobalTestPartResultReporter( 582 TestPartResultReporterInterface* reporter); 583 584 // Returns the test part result reporter for the current thread. 585 TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread(); 586 587 // Sets the test part result reporter for the current thread. 588 void SetTestPartResultReporterForCurrentThread( 589 TestPartResultReporterInterface* reporter); 590 591 // Gets the number of successful test cases. 592 int successful_test_case_count() const; 593 594 // Gets the number of failed test cases. 595 int failed_test_case_count() const; 596 597 // Gets the number of all test cases. 598 int total_test_case_count() const; 599 600 // Gets the number of all test cases that contain at least one test 601 // that should run. 602 int test_case_to_run_count() const; 603 604 // Gets the number of successful tests. 605 int successful_test_count() const; 606 607 // Gets the number of failed tests. 608 int failed_test_count() const; 609 610 // Gets the number of disabled tests. 611 int disabled_test_count() const; 612 613 // Gets the number of all tests. 614 int total_test_count() const; 615 616 // Gets the number of tests that should run. 617 int test_to_run_count() const; 618 619 // Gets the elapsed time, in milliseconds. 620 TimeInMillis elapsed_time() const { return elapsed_time_; } 621 622 // Returns true iff the unit test passed (i.e. all test cases passed). 623 bool Passed() const { return !Failed(); } 624 625 // Returns true iff the unit test failed (i.e. some test case failed 626 // or something outside of all tests failed). 627 bool Failed() const { 628 return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed(); 629 } 630 631 // Gets the i-th test case among all the test cases. i can range from 0 to 632 // total_test_case_count() - 1. If i is not in that range, returns NULL. 633 const TestCase* GetTestCase(int i) const { 634 const int index = GetElementOr(test_case_indices_, i, -1); 635 return index < 0 ? NULL : test_cases_[i]; 636 } 637 638 // Gets the i-th test case among all the test cases. i can range from 0 to 639 // total_test_case_count() - 1. If i is not in that range, returns NULL. 640 TestCase* GetMutableTestCase(int i) { 641 const int index = GetElementOr(test_case_indices_, i, -1); 642 return index < 0 ? NULL : test_cases_[index]; 643 } 644 645 // Provides access to the event listener list. 646 TestEventListeners* listeners() { return &listeners_; } 647 648 // Returns the TestResult for the test that's currently running, or 649 // the TestResult for the ad hoc test if no test is running. 650 TestResult* current_test_result(); 651 652 // Returns the TestResult for the ad hoc test. 653 const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; } 654 655 // Sets the OS stack trace getter. 656 // 657 // Does nothing if the input and the current OS stack trace getter 658 // are the same; otherwise, deletes the old getter and makes the 659 // input the current getter. 660 void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter); 661 662 // Returns the current OS stack trace getter if it is not NULL; 663 // otherwise, creates an OsStackTraceGetter, makes it the current 664 // getter, and returns it. 665 OsStackTraceGetterInterface* os_stack_trace_getter(); 666 667 // Returns the current OS stack trace as a String. 668 // 669 // The maximum number of stack frames to be included is specified by 670 // the gtest_stack_trace_depth flag. The skip_count parameter 671 // specifies the number of top frames to be skipped, which doesn't 672 // count against the number of frames to be included. 673 // 674 // For example, if Foo() calls Bar(), which in turn calls 675 // CurrentOsStackTraceExceptTop(1), Foo() will be included in the 676 // trace but Bar() and CurrentOsStackTraceExceptTop() won't. 677 String CurrentOsStackTraceExceptTop(int skip_count); 678 679 // Finds and returns a TestCase with the given name. If one doesn't 680 // exist, creates one and returns it. 681 // 682 // Arguments: 683 // 684 // test_case_name: name of the test case 685 // set_up_tc: pointer to the function that sets up the test case 686 // tear_down_tc: pointer to the function that tears down the test case 687 TestCase* GetTestCase(const char* test_case_name, 688 const char* comment, 689 Test::SetUpTestCaseFunc set_up_tc, 690 Test::TearDownTestCaseFunc tear_down_tc); 691 692 // Adds a TestInfo to the unit test. 693 // 694 // Arguments: 695 // 696 // set_up_tc: pointer to the function that sets up the test case 697 // tear_down_tc: pointer to the function that tears down the test case 698 // test_info: the TestInfo object 699 void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc, 700 Test::TearDownTestCaseFunc tear_down_tc, 701 TestInfo * test_info) { 702 // In order to support thread-safe death tests, we need to 703 // remember the original working directory when the test program 704 // was first invoked. We cannot do this in RUN_ALL_TESTS(), as 705 // the user may have changed the current directory before calling 706 // RUN_ALL_TESTS(). Therefore we capture the current directory in 707 // AddTestInfo(), which is called to register a TEST or TEST_F 708 // before main() is reached. 709 if (original_working_dir_.IsEmpty()) { 710 original_working_dir_.Set(FilePath::GetCurrentDir()); 711 GTEST_CHECK_(!original_working_dir_.IsEmpty()) 712 << "Failed to get the current working directory."; 713 } 714 715 GetTestCase(test_info->test_case_name(), 716 test_info->test_case_comment(), 717 set_up_tc, 718 tear_down_tc)->AddTestInfo(test_info); 719 } 720 721 #if GTEST_HAS_PARAM_TEST 722 // Returns ParameterizedTestCaseRegistry object used to keep track of 723 // value-parameterized tests and instantiate and register them. 724 internal::ParameterizedTestCaseRegistry& parameterized_test_registry() { 725 return parameterized_test_registry_; 726 } 727 #endif // GTEST_HAS_PARAM_TEST 728 729 // Sets the TestCase object for the test that's currently running. 730 void set_current_test_case(TestCase* a_current_test_case) { 731 current_test_case_ = a_current_test_case; 732 } 733 734 // Sets the TestInfo object for the test that's currently running. If 735 // current_test_info is NULL, the assertion results will be stored in 736 // ad_hoc_test_result_. 737 void set_current_test_info(TestInfo* a_current_test_info) { 738 current_test_info_ = a_current_test_info; 739 } 740 741 // Registers all parameterized tests defined using TEST_P and 742 // INSTANTIATE_TEST_P, creating regular tests for each test/parameter 743 // combination. This method can be called more then once; it has 744 // guards protecting from registering the tests more then once. 745 // If value-parameterized tests are disabled, RegisterParameterizedTests 746 // is present but does nothing. 747 void RegisterParameterizedTests(); 748 749 // Runs all tests in this UnitTest object, prints the result, and 750 // returns 0 if all tests are successful, or 1 otherwise. If any 751 // exception is thrown during a test on Windows, this test is 752 // considered to be failed, but the rest of the tests will still be 753 // run. (We disable exceptions on Linux and Mac OS X, so the issue 754 // doesn't apply there.) 755 int RunAllTests(); 756 757 // Clears the results of all tests, including the ad hoc test. 758 void ClearResult() { 759 ForEach(test_cases_, TestCase::ClearTestCaseResult); 760 ad_hoc_test_result_.Clear(); 761 } 762 763 enum ReactionToSharding { 764 HONOR_SHARDING_PROTOCOL, 765 IGNORE_SHARDING_PROTOCOL 766 }; 767 768 // Matches the full name of each test against the user-specified 769 // filter to decide whether the test should run, then records the 770 // result in each TestCase and TestInfo object. 771 // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests 772 // based on sharding variables in the environment. 773 // Returns the number of tests that should run. 774 int FilterTests(ReactionToSharding shard_tests); 775 776 // Prints the names of the tests matching the user-specified filter flag. 777 void ListTestsMatchingFilter(); 778 779 const TestCase* current_test_case() const { return current_test_case_; } 780 TestInfo* current_test_info() { return current_test_info_; } 781 const TestInfo* current_test_info() const { return current_test_info_; } 782 783 // Returns the vector of environments that need to be set-up/torn-down 784 // before/after the tests are run. 785 std::vector<Environment*>& environments() { return environments_; } 786 787 // Getters for the per-thread Google Test trace stack. 788 std::vector<TraceInfo>& gtest_trace_stack() { 789 return *(gtest_trace_stack_.pointer()); 790 } 791 const std::vector<TraceInfo>& gtest_trace_stack() const { 792 return gtest_trace_stack_.get(); 793 } 794 795 #if GTEST_HAS_DEATH_TEST 796 void InitDeathTestSubprocessControlInfo() { 797 internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag()); 798 } 799 // Returns a pointer to the parsed --gtest_internal_run_death_test 800 // flag, or NULL if that flag was not specified. 801 // This information is useful only in a death test child process. 802 // Must not be called before a call to InitGoogleTest. 803 const InternalRunDeathTestFlag* internal_run_death_test_flag() const { 804 return internal_run_death_test_flag_.get(); 805 } 806 807 // Returns a pointer to the current death test factory. 808 internal::DeathTestFactory* death_test_factory() { 809 return death_test_factory_.get(); 810 } 811 812 void SuppressTestEventsIfInSubprocess(); 813 814 friend class ReplaceDeathTestFactory; 815 #endif // GTEST_HAS_DEATH_TEST 816 817 // Initializes the event listener performing XML output as specified by 818 // UnitTestOptions. Must not be called before InitGoogleTest. 819 void ConfigureXmlOutput(); 820 821 // Performs initialization dependent upon flag values obtained in 822 // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to 823 // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest 824 // this function is also called from RunAllTests. Since this function can be 825 // called more than once, it has to be idempotent. 826 void PostFlagParsingInit(); 827 828 // Gets the random seed used at the start of the current test iteration. 829 int random_seed() const { return random_seed_; } 830 831 // Gets the random number generator. 832 internal::Random* random() { return &random_; } 833 834 // Shuffles all test cases, and the tests within each test case, 835 // making sure that death tests are still run first. 836 void ShuffleTests(); 837 838 // Restores the test cases and tests to their order before the first shuffle. 839 void UnshuffleTests(); 840 841 private: 842 friend class ::testing::UnitTest; 843 844 // The UnitTest object that owns this implementation object. 845 UnitTest* const parent_; 846 847 // The working directory when the first TEST() or TEST_F() was 848 // executed. 849 internal::FilePath original_working_dir_; 850 851 // The default test part result reporters. 852 DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_; 853 DefaultPerThreadTestPartResultReporter 854 default_per_thread_test_part_result_reporter_; 855 856 // Points to (but doesn't own) the global test part result reporter. 857 TestPartResultReporterInterface* global_test_part_result_repoter_; 858 859 // Protects read and write access to global_test_part_result_reporter_. 860 internal::Mutex global_test_part_result_reporter_mutex_; 861 862 // Points to (but doesn't own) the per-thread test part result reporter. 863 internal::ThreadLocal<TestPartResultReporterInterface*> 864 per_thread_test_part_result_reporter_; 865 866 // The vector of environments that need to be set-up/torn-down 867 // before/after the tests are run. 868 std::vector<Environment*> environments_; 869 870 // The vector of TestCases in their original order. It owns the 871 // elements in the vector. 872 std::vector<TestCase*> test_cases_; 873 874 // Provides a level of indirection for the test case list to allow 875 // easy shuffling and restoring the test case order. The i-th 876 // element of this vector is the index of the i-th test case in the 877 // shuffled order. 878 std::vector<int> test_case_indices_; 879 880 #if GTEST_HAS_PARAM_TEST 881 // ParameterizedTestRegistry object used to register value-parameterized 882 // tests. 883 internal::ParameterizedTestCaseRegistry parameterized_test_registry_; 884 885 // Indicates whether RegisterParameterizedTests() has been called already. 886 bool parameterized_tests_registered_; 887 #endif // GTEST_HAS_PARAM_TEST 888 889 // Index of the last death test case registered. Initially -1. 890 int last_death_test_case_; 891 892 // This points to the TestCase for the currently running test. It 893 // changes as Google Test goes through one test case after another. 894 // When no test is running, this is set to NULL and Google Test 895 // stores assertion results in ad_hoc_test_result_. Initially NULL. 896 TestCase* current_test_case_; 897 898 // This points to the TestInfo for the currently running test. It 899 // changes as Google Test goes through one test after another. When 900 // no test is running, this is set to NULL and Google Test stores 901 // assertion results in ad_hoc_test_result_. Initially NULL. 902 TestInfo* current_test_info_; 903 904 // Normally, a user only writes assertions inside a TEST or TEST_F, 905 // or inside a function called by a TEST or TEST_F. Since Google 906 // Test keeps track of which test is current running, it can 907 // associate such an assertion with the test it belongs to. 908 // 909 // If an assertion is encountered when no TEST or TEST_F is running, 910 // Google Test attributes the assertion result to an imaginary "ad hoc" 911 // test, and records the result in ad_hoc_test_result_. 912 TestResult ad_hoc_test_result_; 913 914 // The list of event listeners that can be used to track events inside 915 // Google Test. 916 TestEventListeners listeners_; 917 918 // The OS stack trace getter. Will be deleted when the UnitTest 919 // object is destructed. By default, an OsStackTraceGetter is used, 920 // but the user can set this field to use a custom getter if that is 921 // desired. 922 OsStackTraceGetterInterface* os_stack_trace_getter_; 923 924 // True iff PostFlagParsingInit() has been called. 925 bool post_flag_parse_init_performed_; 926 927 // The random number seed used at the beginning of the test run. 928 int random_seed_; 929 930 // Our random number generator. 931 internal::Random random_; 932 933 // How long the test took to run, in milliseconds. 934 TimeInMillis elapsed_time_; 935 936 #if GTEST_HAS_DEATH_TEST 937 // The decomposed components of the gtest_internal_run_death_test flag, 938 // parsed when RUN_ALL_TESTS is called. 939 internal::scoped_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_; 940 internal::scoped_ptr<internal::DeathTestFactory> death_test_factory_; 941 #endif // GTEST_HAS_DEATH_TEST 942 943 // A per-thread stack of traces created by the SCOPED_TRACE() macro. 944 internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_; 945 946 GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl); 947 }; // class UnitTestImpl 948 949 // Convenience function for accessing the global UnitTest 950 // implementation object. 951 inline UnitTestImpl* GetUnitTestImpl() { 952 return UnitTest::GetInstance()->impl(); 953 } 954 955 // Internal helper functions for implementing the simple regular 956 // expression matcher. 957 GTEST_API_ bool IsInSet(char ch, const char* str); 958 GTEST_API_ bool IsDigit(char ch); 959 GTEST_API_ bool IsPunct(char ch); 960 GTEST_API_ bool IsRepeat(char ch); 961 GTEST_API_ bool IsWhiteSpace(char ch); 962 GTEST_API_ bool IsWordChar(char ch); 963 GTEST_API_ bool IsValidEscape(char ch); 964 GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch); 965 GTEST_API_ bool ValidateRegex(const char* regex); 966 GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str); 967 GTEST_API_ bool MatchRepetitionAndRegexAtHead( 968 bool escaped, char ch, char repeat, const char* regex, const char* str); 969 GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str); 970 971 // Parses the command line for Google Test flags, without initializing 972 // other parts of Google Test. 973 GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv); 974 GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv); 975 976 #if GTEST_HAS_DEATH_TEST 977 978 // Returns the message describing the last system error, regardless of the 979 // platform. 980 String GetLastErrnoDescription(); 981 982 #if GTEST_OS_WINDOWS 983 // Provides leak-safe Windows kernel handle ownership. 984 class AutoHandle { 985 public: 986 AutoHandle() : handle_(INVALID_HANDLE_VALUE) {} 987 explicit AutoHandle(HANDLE handle) : handle_(handle) {} 988 989 ~AutoHandle() { Reset(); } 990 991 HANDLE Get() const { return handle_; } 992 void Reset() { Reset(INVALID_HANDLE_VALUE); } 993 void Reset(HANDLE handle) { 994 if (handle != handle_) { 995 if (handle_ != INVALID_HANDLE_VALUE) 996 ::CloseHandle(handle_); 997 handle_ = handle; 998 } 999 } 1000 1001 private: 1002 HANDLE handle_; 1003 1004 GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle); 1005 }; 1006 #endif // GTEST_OS_WINDOWS 1007 1008 // Attempts to parse a string into a positive integer pointed to by the 1009 // number parameter. Returns true if that is possible. 1010 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use 1011 // it here. 1012 template <typename Integer> 1013 bool ParseNaturalNumber(const ::std::string& str, Integer* number) { 1014 // Fail fast if the given string does not begin with a digit; 1015 // this bypasses strtoXXX's "optional leading whitespace and plus 1016 // or minus sign" semantics, which are undesirable here. 1017 if (str.empty() || !isdigit(str[0])) { 1018 return false; 1019 } 1020 errno = 0; 1021 1022 char* end; 1023 // BiggestConvertible is the largest integer type that system-provided 1024 // string-to-number conversion routines can return. 1025 #if GTEST_OS_WINDOWS && !defined(__GNUC__) 1026 // MSVC and C++ Builder define __int64 instead of the standard long long. 1027 typedef unsigned __int64 BiggestConvertible; 1028 const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10); 1029 #else 1030 typedef unsigned long long BiggestConvertible; // NOLINT 1031 const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10); 1032 #endif // GTEST_OS_WINDOWS && !defined(__GNUC__) 1033 const bool parse_success = *end == '\0' && errno == 0; 1034 1035 // TODO(vladl (at) google.com): Convert this to compile time assertion when it is 1036 // available. 1037 GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed)); 1038 1039 const Integer result = static_cast<Integer>(parsed); 1040 if (parse_success && static_cast<BiggestConvertible>(result) == parsed) { 1041 *number = result; 1042 return true; 1043 } 1044 return false; 1045 } 1046 #endif // GTEST_HAS_DEATH_TEST 1047 1048 // TestResult contains some private methods that should be hidden from 1049 // Google Test user but are required for testing. This class allow our tests 1050 // to access them. 1051 // 1052 // This class is supplied only for the purpose of testing Google Test's own 1053 // constructs. Do not use it in user tests, either directly or indirectly. 1054 class TestResultAccessor { 1055 public: 1056 static void RecordProperty(TestResult* test_result, 1057 const TestProperty& property) { 1058 test_result->RecordProperty(property); 1059 } 1060 1061 static void ClearTestPartResults(TestResult* test_result) { 1062 test_result->ClearTestPartResults(); 1063 } 1064 1065 static const std::vector<testing::TestPartResult>& test_part_results( 1066 const TestResult& test_result) { 1067 return test_result.test_part_results(); 1068 } 1069 }; 1070 1071 } // namespace internal 1072 } // namespace testing 1073 1074 #endif // GTEST_SRC_GTEST_INTERNAL_INL_H_ 1075