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 #include <errno.h> 49 #include <stddef.h> 50 #include <stdlib.h> // For strtoll/_strtoul64. 51 52 #include <string> 53 54 #include <gtest/internal/gtest-port.h> 55 56 #if GTEST_OS_WINDOWS 57 #include <windows.h> // For DWORD. 58 #endif // GTEST_OS_WINDOWS 59 60 #include <gtest/gtest.h> 61 #include <gtest/gtest-spi.h> 62 63 namespace testing { 64 65 // Declares the flags. 66 // 67 // We don't want the users to modify this flag in the code, but want 68 // Google Test's own unit tests to be able to access it. Therefore we 69 // declare it here as opposed to in gtest.h. 70 GTEST_DECLARE_bool_(death_test_use_fork); 71 72 namespace internal { 73 74 // The value of GetTestTypeId() as seen from within the Google Test 75 // library. This is solely for testing GetTestTypeId(). 76 extern const TypeId kTestTypeIdInGoogleTest; 77 78 // Names of the flags (needed for parsing Google Test flags). 79 const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests"; 80 const char kBreakOnFailureFlag[] = "break_on_failure"; 81 const char kCatchExceptionsFlag[] = "catch_exceptions"; 82 const char kColorFlag[] = "color"; 83 const char kFilterFlag[] = "filter"; 84 const char kListTestsFlag[] = "list_tests"; 85 const char kOutputFlag[] = "output"; 86 const char kPrintTimeFlag[] = "print_time"; 87 const char kRepeatFlag[] = "repeat"; 88 const char kThrowOnFailureFlag[] = "throw_on_failure"; 89 90 // This class saves the values of all Google Test flags in its c'tor, and 91 // restores them in its d'tor. 92 class GTestFlagSaver { 93 public: 94 // The c'tor. 95 GTestFlagSaver() { 96 also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests); 97 break_on_failure_ = GTEST_FLAG(break_on_failure); 98 catch_exceptions_ = GTEST_FLAG(catch_exceptions); 99 color_ = GTEST_FLAG(color); 100 death_test_style_ = GTEST_FLAG(death_test_style); 101 death_test_use_fork_ = GTEST_FLAG(death_test_use_fork); 102 filter_ = GTEST_FLAG(filter); 103 internal_run_death_test_ = GTEST_FLAG(internal_run_death_test); 104 list_tests_ = GTEST_FLAG(list_tests); 105 output_ = GTEST_FLAG(output); 106 print_time_ = GTEST_FLAG(print_time); 107 repeat_ = GTEST_FLAG(repeat); 108 throw_on_failure_ = GTEST_FLAG(throw_on_failure); 109 } 110 111 // The d'tor is not virtual. DO NOT INHERIT FROM THIS CLASS. 112 ~GTestFlagSaver() { 113 GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_; 114 GTEST_FLAG(break_on_failure) = break_on_failure_; 115 GTEST_FLAG(catch_exceptions) = catch_exceptions_; 116 GTEST_FLAG(color) = color_; 117 GTEST_FLAG(death_test_style) = death_test_style_; 118 GTEST_FLAG(death_test_use_fork) = death_test_use_fork_; 119 GTEST_FLAG(filter) = filter_; 120 GTEST_FLAG(internal_run_death_test) = internal_run_death_test_; 121 GTEST_FLAG(list_tests) = list_tests_; 122 GTEST_FLAG(output) = output_; 123 GTEST_FLAG(print_time) = print_time_; 124 GTEST_FLAG(repeat) = repeat_; 125 GTEST_FLAG(throw_on_failure) = throw_on_failure_; 126 } 127 private: 128 // Fields for saving the original values of flags. 129 bool also_run_disabled_tests_; 130 bool break_on_failure_; 131 bool catch_exceptions_; 132 String color_; 133 String death_test_style_; 134 bool death_test_use_fork_; 135 String filter_; 136 String internal_run_death_test_; 137 bool list_tests_; 138 String output_; 139 bool print_time_; 140 bool pretty_; 141 internal::Int32 repeat_; 142 bool throw_on_failure_; 143 } GTEST_ATTRIBUTE_UNUSED_; 144 145 // Converts a Unicode code point to a narrow string in UTF-8 encoding. 146 // code_point parameter is of type UInt32 because wchar_t may not be 147 // wide enough to contain a code point. 148 // The output buffer str must containt at least 32 characters. 149 // The function returns the address of the output buffer. 150 // If the code_point is not a valid Unicode code point 151 // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be output 152 // as '(Invalid Unicode 0xXXXXXXXX)'. 153 char* CodePointToUtf8(UInt32 code_point, char* str); 154 155 // Converts a wide string to a narrow string in UTF-8 encoding. 156 // The wide string is assumed to have the following encoding: 157 // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS) 158 // UTF-32 if sizeof(wchar_t) == 4 (on Linux) 159 // Parameter str points to a null-terminated wide string. 160 // Parameter num_chars may additionally limit the number 161 // of wchar_t characters processed. -1 is used when the entire string 162 // should be processed. 163 // If the string contains code points that are not valid Unicode code points 164 // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output 165 // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding 166 // and contains invalid UTF-16 surrogate pairs, values in those pairs 167 // will be encoded as individual Unicode characters from Basic Normal Plane. 168 String WideStringToUtf8(const wchar_t* str, int num_chars); 169 170 // Returns the number of active threads, or 0 when there is an error. 171 size_t GetThreadCount(); 172 173 // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file 174 // if the variable is present. If a file already exists at this location, this 175 // function will write over it. If the variable is present, but the file cannot 176 // be created, prints an error and exits. 177 void WriteToShardStatusFileIfNeeded(); 178 179 // Checks whether sharding is enabled by examining the relevant 180 // environment variable values. If the variables are present, 181 // but inconsistent (e.g., shard_index >= total_shards), prints 182 // an error and exits. If in_subprocess_for_death_test, sharding is 183 // disabled because it must only be applied to the original test 184 // process. Otherwise, we could filter out death tests we intended to execute. 185 bool ShouldShard(const char* total_shards_str, const char* shard_index_str, 186 bool in_subprocess_for_death_test); 187 188 // Parses the environment variable var as an Int32. If it is unset, 189 // returns default_val. If it is not an Int32, prints an error and 190 // and aborts. 191 Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val); 192 193 // Given the total number of shards, the shard index, and the test id, 194 // returns true iff the test should be run on this shard. The test id is 195 // some arbitrary but unique non-negative integer assigned to each test 196 // method. Assumes that 0 <= shard_index < total_shards. 197 bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id); 198 199 // List is a simple singly-linked list container. 200 // 201 // We cannot use std::list as Microsoft's implementation of STL has 202 // problems when exception is disabled. There is a hack to work 203 // around this, but we've seen cases where the hack fails to work. 204 // 205 // TODO(wan): switch to std::list when we have a reliable fix for the 206 // STL problem, e.g. when we upgrade to the next version of Visual 207 // C++, or (more likely) switch to STLport. 208 // 209 // The element type must support copy constructor. 210 211 // Forward declare List 212 template <typename E> // E is the element type. 213 class List; 214 215 // ListNode is a node in a singly-linked list. It consists of an 216 // element and a pointer to the next node. The last node in the list 217 // has a NULL value for its next pointer. 218 template <typename E> // E is the element type. 219 class ListNode { 220 friend class List<E>; 221 222 private: 223 224 E element_; 225 ListNode * next_; 226 227 // The c'tor is private s.t. only in the ListNode class and in its 228 // friend class List we can create a ListNode object. 229 // 230 // Creates a node with a given element value. The next pointer is 231 // set to NULL. 232 // 233 // ListNode does NOT have a default constructor. Always use this 234 // constructor (with parameter) to create a ListNode object. 235 explicit ListNode(const E & element) : element_(element), next_(NULL) {} 236 237 // We disallow copying ListNode 238 GTEST_DISALLOW_COPY_AND_ASSIGN_(ListNode); 239 240 public: 241 242 // Gets the element in this node. 243 E & element() { return element_; } 244 const E & element() const { return element_; } 245 246 // Gets the next node in the list. 247 ListNode * next() { return next_; } 248 const ListNode * next() const { return next_; } 249 }; 250 251 252 // List is a simple singly-linked list container. 253 template <typename E> // E is the element type. 254 class List { 255 public: 256 257 // Creates an empty list. 258 List() : head_(NULL), last_(NULL), size_(0) {} 259 260 // D'tor. 261 virtual ~List(); 262 263 // Clears the list. 264 void Clear() { 265 if ( size_ > 0 ) { 266 // 1. Deletes every node. 267 ListNode<E> * node = head_; 268 ListNode<E> * next = node->next(); 269 for ( ; ; ) { 270 delete node; 271 node = next; 272 if ( node == NULL ) break; 273 next = node->next(); 274 } 275 276 // 2. Resets the member variables. 277 head_ = last_ = NULL; 278 size_ = 0; 279 } 280 } 281 282 // Gets the number of elements. 283 int size() const { return size_; } 284 285 // Returns true if the list is empty. 286 bool IsEmpty() const { return size() == 0; } 287 288 // Gets the first element of the list, or NULL if the list is empty. 289 ListNode<E> * Head() { return head_; } 290 const ListNode<E> * Head() const { return head_; } 291 292 // Gets the last element of the list, or NULL if the list is empty. 293 ListNode<E> * Last() { return last_; } 294 const ListNode<E> * Last() const { return last_; } 295 296 // Adds an element to the end of the list. A copy of the element is 297 // created using the copy constructor, and then stored in the list. 298 // Changes made to the element in the list doesn't affect the source 299 // object, and vice versa. 300 void PushBack(const E & element) { 301 ListNode<E> * new_node = new ListNode<E>(element); 302 303 if ( size_ == 0 ) { 304 head_ = last_ = new_node; 305 size_ = 1; 306 } else { 307 last_->next_ = new_node; 308 last_ = new_node; 309 size_++; 310 } 311 } 312 313 // Adds an element to the beginning of this list. 314 void PushFront(const E& element) { 315 ListNode<E>* const new_node = new ListNode<E>(element); 316 317 if ( size_ == 0 ) { 318 head_ = last_ = new_node; 319 size_ = 1; 320 } else { 321 new_node->next_ = head_; 322 head_ = new_node; 323 size_++; 324 } 325 } 326 327 // Removes an element from the beginning of this list. If the 328 // result argument is not NULL, the removed element is stored in the 329 // memory it points to. Otherwise the element is thrown away. 330 // Returns true iff the list wasn't empty before the operation. 331 bool PopFront(E* result) { 332 if (size_ == 0) return false; 333 334 if (result != NULL) { 335 *result = head_->element_; 336 } 337 338 ListNode<E>* const old_head = head_; 339 size_--; 340 if (size_ == 0) { 341 head_ = last_ = NULL; 342 } else { 343 head_ = head_->next_; 344 } 345 delete old_head; 346 347 return true; 348 } 349 350 // Inserts an element after a given node in the list. It's the 351 // caller's responsibility to ensure that the given node is in the 352 // list. If the given node is NULL, inserts the element at the 353 // front of the list. 354 ListNode<E>* InsertAfter(ListNode<E>* node, const E& element) { 355 if (node == NULL) { 356 PushFront(element); 357 return Head(); 358 } 359 360 ListNode<E>* const new_node = new ListNode<E>(element); 361 new_node->next_ = node->next_; 362 node->next_ = new_node; 363 size_++; 364 if (node == last_) { 365 last_ = new_node; 366 } 367 368 return new_node; 369 } 370 371 // Returns the number of elements that satisfy a given predicate. 372 // The parameter 'predicate' is a Boolean function or functor that 373 // accepts a 'const E &', where E is the element type. 374 template <typename P> // P is the type of the predicate function/functor 375 int CountIf(P predicate) const { 376 int count = 0; 377 for ( const ListNode<E> * node = Head(); 378 node != NULL; 379 node = node->next() ) { 380 if ( predicate(node->element()) ) { 381 count++; 382 } 383 } 384 385 return count; 386 } 387 388 // Applies a function/functor to each element in the list. The 389 // parameter 'functor' is a function/functor that accepts a 'const 390 // E &', where E is the element type. This method does not change 391 // the elements. 392 template <typename F> // F is the type of the function/functor 393 void ForEach(F functor) const { 394 for ( const ListNode<E> * node = Head(); 395 node != NULL; 396 node = node->next() ) { 397 functor(node->element()); 398 } 399 } 400 401 // Returns the first node whose element satisfies a given predicate, 402 // or NULL if none is found. The parameter 'predicate' is a 403 // function/functor that accepts a 'const E &', where E is the 404 // element type. This method does not change the elements. 405 template <typename P> // P is the type of the predicate function/functor. 406 const ListNode<E> * FindIf(P predicate) const { 407 for ( const ListNode<E> * node = Head(); 408 node != NULL; 409 node = node->next() ) { 410 if ( predicate(node->element()) ) { 411 return node; 412 } 413 } 414 415 return NULL; 416 } 417 418 template <typename P> 419 ListNode<E> * FindIf(P predicate) { 420 for ( ListNode<E> * node = Head(); 421 node != NULL; 422 node = node->next() ) { 423 if ( predicate(node->element() ) ) { 424 return node; 425 } 426 } 427 428 return NULL; 429 } 430 431 private: 432 ListNode<E>* head_; // The first node of the list. 433 ListNode<E>* last_; // The last node of the list. 434 int size_; // The number of elements in the list. 435 436 // We disallow copying List. 437 GTEST_DISALLOW_COPY_AND_ASSIGN_(List); 438 }; 439 440 // The virtual destructor of List. 441 template <typename E> 442 List<E>::~List() { 443 Clear(); 444 } 445 446 // A function for deleting an object. Handy for being used as a 447 // functor. 448 template <typename T> 449 static void Delete(T * x) { 450 delete x; 451 } 452 453 // A copyable object representing a user specified test property which can be 454 // output as a key/value string pair. 455 // 456 // Don't inherit from TestProperty as its destructor is not virtual. 457 class TestProperty { 458 public: 459 // C'tor. TestProperty does NOT have a default constructor. 460 // Always use this constructor (with parameters) to create a 461 // TestProperty object. 462 TestProperty(const char* key, const char* value) : 463 key_(key), value_(value) { 464 } 465 466 // Gets the user supplied key. 467 const char* key() const { 468 return key_.c_str(); 469 } 470 471 // Gets the user supplied value. 472 const char* value() const { 473 return value_.c_str(); 474 } 475 476 // Sets a new value, overriding the one supplied in the constructor. 477 void SetValue(const char* new_value) { 478 value_ = new_value; 479 } 480 481 private: 482 // The key supplied by the user. 483 String key_; 484 // The value supplied by the user. 485 String value_; 486 }; 487 488 // A predicate that checks the key of a TestProperty against a known key. 489 // 490 // TestPropertyKeyIs is copyable. 491 class TestPropertyKeyIs { 492 public: 493 // Constructor. 494 // 495 // TestPropertyKeyIs has NO default constructor. 496 explicit TestPropertyKeyIs(const char* key) 497 : key_(key) {} 498 499 // Returns true iff the test name of test property matches on key_. 500 bool operator()(const TestProperty& test_property) const { 501 return String(test_property.key()).Compare(key_) == 0; 502 } 503 504 private: 505 String key_; 506 }; 507 508 // The result of a single Test. This includes a list of 509 // TestPartResults, a list of TestProperties, a count of how many 510 // death tests there are in the Test, and how much time it took to run 511 // the Test. 512 // 513 // TestResult is not copyable. 514 class TestResult { 515 public: 516 // Creates an empty TestResult. 517 TestResult(); 518 519 // D'tor. Do not inherit from TestResult. 520 ~TestResult(); 521 522 // Gets the list of TestPartResults. 523 const internal::List<TestPartResult> & test_part_results() const { 524 return test_part_results_; 525 } 526 527 // Gets the list of TestProperties. 528 const internal::List<internal::TestProperty> & test_properties() const { 529 return test_properties_; 530 } 531 532 // Gets the number of successful test parts. 533 int successful_part_count() const; 534 535 // Gets the number of failed test parts. 536 int failed_part_count() const; 537 538 // Gets the number of all test parts. This is the sum of the number 539 // of successful test parts and the number of failed test parts. 540 int total_part_count() const; 541 542 // Returns true iff the test passed (i.e. no test part failed). 543 bool Passed() const { return !Failed(); } 544 545 // Returns true iff the test failed. 546 bool Failed() const { return failed_part_count() > 0; } 547 548 // Returns true iff the test fatally failed. 549 bool HasFatalFailure() const; 550 551 // Returns the elapsed time, in milliseconds. 552 TimeInMillis elapsed_time() const { return elapsed_time_; } 553 554 // Sets the elapsed time. 555 void set_elapsed_time(TimeInMillis elapsed) { elapsed_time_ = elapsed; } 556 557 // Adds a test part result to the list. 558 void AddTestPartResult(const TestPartResult& test_part_result); 559 560 // Adds a test property to the list. The property is validated and may add 561 // a non-fatal failure if invalid (e.g., if it conflicts with reserved 562 // key names). If a property is already recorded for the same key, the 563 // value will be updated, rather than storing multiple values for the same 564 // key. 565 void RecordProperty(const internal::TestProperty& test_property); 566 567 // Adds a failure if the key is a reserved attribute of Google Test 568 // testcase tags. Returns true if the property is valid. 569 // TODO(russr): Validate attribute names are legal and human readable. 570 static bool ValidateTestProperty(const internal::TestProperty& test_property); 571 572 // Returns the death test count. 573 int death_test_count() const { return death_test_count_; } 574 575 // Increments the death test count, returning the new count. 576 int increment_death_test_count() { return ++death_test_count_; } 577 578 // Clears the object. 579 void Clear(); 580 private: 581 // Protects mutable state of the property list and of owned properties, whose 582 // values may be updated. 583 internal::Mutex test_properites_mutex_; 584 585 // The list of TestPartResults 586 internal::List<TestPartResult> test_part_results_; 587 // The list of TestProperties 588 internal::List<internal::TestProperty> test_properties_; 589 // Running count of death tests. 590 int death_test_count_; 591 // The elapsed time, in milliseconds. 592 TimeInMillis elapsed_time_; 593 594 // We disallow copying TestResult. 595 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestResult); 596 }; // class TestResult 597 598 class TestInfoImpl { 599 public: 600 TestInfoImpl(TestInfo* parent, const char* test_case_name, 601 const char* name, const char* test_case_comment, 602 const char* comment, TypeId fixture_class_id, 603 internal::TestFactoryBase* factory); 604 ~TestInfoImpl(); 605 606 // Returns true if this test should run. 607 bool should_run() const { return should_run_; } 608 609 // Sets the should_run member. 610 void set_should_run(bool should) { should_run_ = should; } 611 612 // Returns true if this test is disabled. Disabled tests are not run. 613 bool is_disabled() const { return is_disabled_; } 614 615 // Sets the is_disabled member. 616 void set_is_disabled(bool is) { is_disabled_ = is; } 617 618 // Returns the test case name. 619 const char* test_case_name() const { return test_case_name_.c_str(); } 620 621 // Returns the test name. 622 const char* name() const { return name_.c_str(); } 623 624 // Returns the test case comment. 625 const char* test_case_comment() const { return test_case_comment_.c_str(); } 626 627 // Returns the test comment. 628 const char* comment() const { return comment_.c_str(); } 629 630 // Returns the ID of the test fixture class. 631 TypeId fixture_class_id() const { return fixture_class_id_; } 632 633 // Returns the test result. 634 internal::TestResult* result() { return &result_; } 635 const internal::TestResult* result() const { return &result_; } 636 637 // Creates the test object, runs it, records its result, and then 638 // deletes it. 639 void Run(); 640 641 // Calls the given TestInfo object's Run() method. 642 static void RunTest(TestInfo * test_info) { 643 test_info->impl()->Run(); 644 } 645 646 // Clears the test result. 647 void ClearResult() { result_.Clear(); } 648 649 // Clears the test result in the given TestInfo object. 650 static void ClearTestResult(TestInfo * test_info) { 651 test_info->impl()->ClearResult(); 652 } 653 654 private: 655 // These fields are immutable properties of the test. 656 TestInfo* const parent_; // The owner of this object 657 const String test_case_name_; // Test case name 658 const String name_; // Test name 659 const String test_case_comment_; // Test case comment 660 const String comment_; // Test comment 661 const TypeId fixture_class_id_; // ID of the test fixture class 662 bool should_run_; // True iff this test should run 663 bool is_disabled_; // True iff this test is disabled 664 internal::TestFactoryBase* const factory_; // The factory that creates 665 // the test object 666 667 // This field is mutable and needs to be reset before running the 668 // test for the second time. 669 internal::TestResult result_; 670 671 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestInfoImpl); 672 }; 673 674 } // namespace internal 675 676 // A test case, which consists of a list of TestInfos. 677 // 678 // TestCase is not copyable. 679 class TestCase { 680 public: 681 // Creates a TestCase with the given name. 682 // 683 // TestCase does NOT have a default constructor. Always use this 684 // constructor to create a TestCase object. 685 // 686 // Arguments: 687 // 688 // name: name of the test case 689 // set_up_tc: pointer to the function that sets up the test case 690 // tear_down_tc: pointer to the function that tears down the test case 691 TestCase(const char* name, const char* comment, 692 Test::SetUpTestCaseFunc set_up_tc, 693 Test::TearDownTestCaseFunc tear_down_tc); 694 695 // Destructor of TestCase. 696 virtual ~TestCase(); 697 698 // Gets the name of the TestCase. 699 const char* name() const { return name_.c_str(); } 700 701 // Returns the test case comment. 702 const char* comment() const { return comment_.c_str(); } 703 704 // Returns true if any test in this test case should run. 705 bool should_run() const { return should_run_; } 706 707 // Sets the should_run member. 708 void set_should_run(bool should) { should_run_ = should; } 709 710 // Gets the (mutable) list of TestInfos in this TestCase. 711 internal::List<TestInfo*>& test_info_list() { return *test_info_list_; } 712 713 // Gets the (immutable) list of TestInfos in this TestCase. 714 const internal::List<TestInfo *> & test_info_list() const { 715 return *test_info_list_; 716 } 717 718 // Gets the number of successful tests in this test case. 719 int successful_test_count() const; 720 721 // Gets the number of failed tests in this test case. 722 int failed_test_count() const; 723 724 // Gets the number of disabled tests in this test case. 725 int disabled_test_count() const; 726 727 // Get the number of tests in this test case that should run. 728 int test_to_run_count() const; 729 730 // Gets the number of all tests in this test case. 731 int total_test_count() const; 732 733 // Returns true iff the test case passed. 734 bool Passed() const { return !Failed(); } 735 736 // Returns true iff the test case failed. 737 bool Failed() const { return failed_test_count() > 0; } 738 739 // Returns the elapsed time, in milliseconds. 740 internal::TimeInMillis elapsed_time() const { return elapsed_time_; } 741 742 // Adds a TestInfo to this test case. Will delete the TestInfo upon 743 // destruction of the TestCase object. 744 void AddTestInfo(TestInfo * test_info); 745 746 // Finds and returns a TestInfo with the given name. If one doesn't 747 // exist, returns NULL. 748 TestInfo* GetTestInfo(const char* test_name); 749 750 // Clears the results of all tests in this test case. 751 void ClearResult(); 752 753 // Clears the results of all tests in the given test case. 754 static void ClearTestCaseResult(TestCase* test_case) { 755 test_case->ClearResult(); 756 } 757 758 // Runs every test in this TestCase. 759 void Run(); 760 761 // Runs every test in the given TestCase. 762 static void RunTestCase(TestCase * test_case) { test_case->Run(); } 763 764 // Returns true iff test passed. 765 static bool TestPassed(const TestInfo * test_info) { 766 const internal::TestInfoImpl* const impl = test_info->impl(); 767 return impl->should_run() && impl->result()->Passed(); 768 } 769 770 // Returns true iff test failed. 771 static bool TestFailed(const TestInfo * test_info) { 772 const internal::TestInfoImpl* const impl = test_info->impl(); 773 return impl->should_run() && impl->result()->Failed(); 774 } 775 776 // Returns true iff test is disabled. 777 static bool TestDisabled(const TestInfo * test_info) { 778 return test_info->impl()->is_disabled(); 779 } 780 781 // Returns true if the given test should run. 782 static bool ShouldRunTest(const TestInfo *test_info) { 783 return test_info->impl()->should_run(); 784 } 785 786 private: 787 // Name of the test case. 788 internal::String name_; 789 // Comment on the test case. 790 internal::String comment_; 791 // List of TestInfos. 792 internal::List<TestInfo*>* test_info_list_; 793 // Pointer to the function that sets up the test case. 794 Test::SetUpTestCaseFunc set_up_tc_; 795 // Pointer to the function that tears down the test case. 796 Test::TearDownTestCaseFunc tear_down_tc_; 797 // True iff any test in this test case should run. 798 bool should_run_; 799 // Elapsed time, in milliseconds. 800 internal::TimeInMillis elapsed_time_; 801 802 // We disallow copying TestCases. 803 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestCase); 804 }; 805 806 namespace internal { 807 808 // Class UnitTestOptions. 809 // 810 // This class contains functions for processing options the user 811 // specifies when running the tests. It has only static members. 812 // 813 // In most cases, the user can specify an option using either an 814 // environment variable or a command line flag. E.g. you can set the 815 // test filter using either GTEST_FILTER or --gtest_filter. If both 816 // the variable and the flag are present, the latter overrides the 817 // former. 818 class UnitTestOptions { 819 public: 820 // Functions for processing the gtest_output flag. 821 822 // Returns the output format, or "" for normal printed output. 823 static String GetOutputFormat(); 824 825 // Returns the absolute path of the requested output file, or the 826 // default (test_detail.xml in the original working directory) if 827 // none was explicitly specified. 828 static String GetAbsolutePathToOutputFile(); 829 830 // Functions for processing the gtest_filter flag. 831 832 // Returns true iff the wildcard pattern matches the string. The 833 // first ':' or '\0' character in pattern marks the end of it. 834 // 835 // This recursive algorithm isn't very efficient, but is clear and 836 // works well enough for matching test names, which are short. 837 static bool PatternMatchesString(const char *pattern, const char *str); 838 839 // Returns true iff the user-specified filter matches the test case 840 // name and the test name. 841 static bool FilterMatchesTest(const String &test_case_name, 842 const String &test_name); 843 844 #if GTEST_OS_WINDOWS 845 // Function for supporting the gtest_catch_exception flag. 846 847 // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the 848 // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise. 849 // This function is useful as an __except condition. 850 static int GTestShouldProcessSEH(DWORD exception_code); 851 #endif // GTEST_OS_WINDOWS 852 853 // Returns true if "name" matches the ':' separated list of glob-style 854 // filters in "filter". 855 static bool MatchesFilter(const String& name, const char* filter); 856 }; 857 858 // Returns the current application's name, removing directory path if that 859 // is present. Used by UnitTestOptions::GetOutputFile. 860 FilePath GetCurrentExecutableName(); 861 862 // The role interface for getting the OS stack trace as a string. 863 class OsStackTraceGetterInterface { 864 public: 865 OsStackTraceGetterInterface() {} 866 virtual ~OsStackTraceGetterInterface() {} 867 868 // Returns the current OS stack trace as a String. Parameters: 869 // 870 // max_depth - the maximum number of stack frames to be included 871 // in the trace. 872 // skip_count - the number of top frames to be skipped; doesn't count 873 // against max_depth. 874 virtual String CurrentStackTrace(int max_depth, int skip_count) = 0; 875 876 // UponLeavingGTest() should be called immediately before Google Test calls 877 // user code. It saves some information about the current stack that 878 // CurrentStackTrace() will use to find and hide Google Test stack frames. 879 virtual void UponLeavingGTest() = 0; 880 881 private: 882 GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface); 883 }; 884 885 // A working implementation of the OsStackTraceGetterInterface interface. 886 class OsStackTraceGetter : public OsStackTraceGetterInterface { 887 public: 888 OsStackTraceGetter() {} 889 virtual String CurrentStackTrace(int max_depth, int skip_count); 890 virtual void UponLeavingGTest(); 891 892 // This string is inserted in place of stack frames that are part of 893 // Google Test's implementation. 894 static const char* const kElidedFramesMarker; 895 896 private: 897 Mutex mutex_; // protects all internal state 898 899 // We save the stack frame below the frame that calls user code. 900 // We do this because the address of the frame immediately below 901 // the user code changes between the call to UponLeavingGTest() 902 // and any calls to CurrentStackTrace() from within the user code. 903 void* caller_frame_; 904 905 GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter); 906 }; 907 908 // Information about a Google Test trace point. 909 struct TraceInfo { 910 const char* file; 911 int line; 912 String message; 913 }; 914 915 // This is the default global test part result reporter used in UnitTestImpl. 916 // This class should only be used by UnitTestImpl. 917 class DefaultGlobalTestPartResultReporter 918 : public TestPartResultReporterInterface { 919 public: 920 explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test); 921 // Implements the TestPartResultReporterInterface. Reports the test part 922 // result in the current test. 923 virtual void ReportTestPartResult(const TestPartResult& result); 924 925 private: 926 UnitTestImpl* const unit_test_; 927 928 GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter); 929 }; 930 931 // This is the default per thread test part result reporter used in 932 // UnitTestImpl. This class should only be used by UnitTestImpl. 933 class DefaultPerThreadTestPartResultReporter 934 : public TestPartResultReporterInterface { 935 public: 936 explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test); 937 // Implements the TestPartResultReporterInterface. The implementation just 938 // delegates to the current global test part result reporter of *unit_test_. 939 virtual void ReportTestPartResult(const TestPartResult& result); 940 941 private: 942 UnitTestImpl* const unit_test_; 943 944 GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter); 945 }; 946 947 // The private implementation of the UnitTest class. We don't protect 948 // the methods under a mutex, as this class is not accessible by a 949 // user and the UnitTest class that delegates work to this class does 950 // proper locking. 951 class UnitTestImpl { 952 public: 953 explicit UnitTestImpl(UnitTest* parent); 954 virtual ~UnitTestImpl(); 955 956 // There are two different ways to register your own TestPartResultReporter. 957 // You can register your own repoter to listen either only for test results 958 // from the current thread or for results from all threads. 959 // By default, each per-thread test result repoter just passes a new 960 // TestPartResult to the global test result reporter, which registers the 961 // test part result for the currently running test. 962 963 // Returns the global test part result reporter. 964 TestPartResultReporterInterface* GetGlobalTestPartResultReporter(); 965 966 // Sets the global test part result reporter. 967 void SetGlobalTestPartResultReporter( 968 TestPartResultReporterInterface* reporter); 969 970 // Returns the test part result reporter for the current thread. 971 TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread(); 972 973 // Sets the test part result reporter for the current thread. 974 void SetTestPartResultReporterForCurrentThread( 975 TestPartResultReporterInterface* reporter); 976 977 // Gets the number of successful test cases. 978 int successful_test_case_count() const; 979 980 // Gets the number of failed test cases. 981 int failed_test_case_count() const; 982 983 // Gets the number of all test cases. 984 int total_test_case_count() const; 985 986 // Gets the number of all test cases that contain at least one test 987 // that should run. 988 int test_case_to_run_count() const; 989 990 // Gets the number of successful tests. 991 int successful_test_count() const; 992 993 // Gets the number of failed tests. 994 int failed_test_count() const; 995 996 // Gets the number of disabled tests. 997 int disabled_test_count() const; 998 999 // Gets the number of all tests. 1000 int total_test_count() const; 1001 1002 // Gets the number of tests that should run. 1003 int test_to_run_count() const; 1004 1005 // Gets the elapsed time, in milliseconds. 1006 TimeInMillis elapsed_time() const { return elapsed_time_; } 1007 1008 // Returns true iff the unit test passed (i.e. all test cases passed). 1009 bool Passed() const { return !Failed(); } 1010 1011 // Returns true iff the unit test failed (i.e. some test case failed 1012 // or something outside of all tests failed). 1013 bool Failed() const { 1014 return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed(); 1015 } 1016 1017 // Returns the TestResult for the test that's currently running, or 1018 // the TestResult for the ad hoc test if no test is running. 1019 internal::TestResult* current_test_result(); 1020 1021 // Returns the TestResult for the ad hoc test. 1022 const internal::TestResult* ad_hoc_test_result() const { 1023 return &ad_hoc_test_result_; 1024 } 1025 1026 // Sets the unit test result printer. 1027 // 1028 // Does nothing if the input and the current printer object are the 1029 // same; otherwise, deletes the old printer object and makes the 1030 // input the current printer. 1031 void set_result_printer(UnitTestEventListenerInterface * result_printer); 1032 1033 // Returns the current unit test result printer if it is not NULL; 1034 // otherwise, creates an appropriate result printer, makes it the 1035 // current printer, and returns it. 1036 UnitTestEventListenerInterface* result_printer(); 1037 1038 // Sets the OS stack trace getter. 1039 // 1040 // Does nothing if the input and the current OS stack trace getter 1041 // are the same; otherwise, deletes the old getter and makes the 1042 // input the current getter. 1043 void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter); 1044 1045 // Returns the current OS stack trace getter if it is not NULL; 1046 // otherwise, creates an OsStackTraceGetter, makes it the current 1047 // getter, and returns it. 1048 OsStackTraceGetterInterface* os_stack_trace_getter(); 1049 1050 // Returns the current OS stack trace as a String. 1051 // 1052 // The maximum number of stack frames to be included is specified by 1053 // the gtest_stack_trace_depth flag. The skip_count parameter 1054 // specifies the number of top frames to be skipped, which doesn't 1055 // count against the number of frames to be included. 1056 // 1057 // For example, if Foo() calls Bar(), which in turn calls 1058 // CurrentOsStackTraceExceptTop(1), Foo() will be included in the 1059 // trace but Bar() and CurrentOsStackTraceExceptTop() won't. 1060 String CurrentOsStackTraceExceptTop(int skip_count); 1061 1062 // Finds and returns a TestCase with the given name. If one doesn't 1063 // exist, creates one and returns it. 1064 // 1065 // Arguments: 1066 // 1067 // test_case_name: name of the test case 1068 // set_up_tc: pointer to the function that sets up the test case 1069 // tear_down_tc: pointer to the function that tears down the test case 1070 TestCase* GetTestCase(const char* test_case_name, 1071 const char* comment, 1072 Test::SetUpTestCaseFunc set_up_tc, 1073 Test::TearDownTestCaseFunc tear_down_tc); 1074 1075 // Adds a TestInfo to the unit test. 1076 // 1077 // Arguments: 1078 // 1079 // set_up_tc: pointer to the function that sets up the test case 1080 // tear_down_tc: pointer to the function that tears down the test case 1081 // test_info: the TestInfo object 1082 void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc, 1083 Test::TearDownTestCaseFunc tear_down_tc, 1084 TestInfo * test_info) { 1085 // In order to support thread-safe death tests, we need to 1086 // remember the original working directory when the test program 1087 // was first invoked. We cannot do this in RUN_ALL_TESTS(), as 1088 // the user may have changed the current directory before calling 1089 // RUN_ALL_TESTS(). Therefore we capture the current directory in 1090 // AddTestInfo(), which is called to register a TEST or TEST_F 1091 // before main() is reached. 1092 if (original_working_dir_.IsEmpty()) { 1093 original_working_dir_.Set(FilePath::GetCurrentDir()); 1094 if (original_working_dir_.IsEmpty()) { 1095 printf("%s\n", "Failed to get the current working directory."); 1096 abort(); 1097 } 1098 } 1099 1100 GetTestCase(test_info->test_case_name(), 1101 test_info->test_case_comment(), 1102 set_up_tc, 1103 tear_down_tc)->AddTestInfo(test_info); 1104 } 1105 1106 #if GTEST_HAS_PARAM_TEST 1107 // Returns ParameterizedTestCaseRegistry object used to keep track of 1108 // value-parameterized tests and instantiate and register them. 1109 internal::ParameterizedTestCaseRegistry& parameterized_test_registry() { 1110 return parameterized_test_registry_; 1111 } 1112 #endif // GTEST_HAS_PARAM_TEST 1113 1114 // Sets the TestCase object for the test that's currently running. 1115 void set_current_test_case(TestCase* current_test_case) { 1116 current_test_case_ = current_test_case; 1117 } 1118 1119 // Sets the TestInfo object for the test that's currently running. If 1120 // current_test_info is NULL, the assertion results will be stored in 1121 // ad_hoc_test_result_. 1122 void set_current_test_info(TestInfo* current_test_info) { 1123 current_test_info_ = current_test_info; 1124 } 1125 1126 // Registers all parameterized tests defined using TEST_P and 1127 // INSTANTIATE_TEST_P, creating regular tests for each test/parameter 1128 // combination. This method can be called more then once; it has 1129 // guards protecting from registering the tests more then once. 1130 // If value-parameterized tests are disabled, RegisterParameterizedTests 1131 // is present but does nothing. 1132 void RegisterParameterizedTests(); 1133 1134 // Runs all tests in this UnitTest object, prints the result, and 1135 // returns 0 if all tests are successful, or 1 otherwise. If any 1136 // exception is thrown during a test on Windows, this test is 1137 // considered to be failed, but the rest of the tests will still be 1138 // run. (We disable exceptions on Linux and Mac OS X, so the issue 1139 // doesn't apply there.) 1140 int RunAllTests(); 1141 1142 // Clears the results of all tests, including the ad hoc test. 1143 void ClearResult() { 1144 test_cases_.ForEach(TestCase::ClearTestCaseResult); 1145 ad_hoc_test_result_.Clear(); 1146 } 1147 1148 enum ReactionToSharding { 1149 HONOR_SHARDING_PROTOCOL, 1150 IGNORE_SHARDING_PROTOCOL 1151 }; 1152 1153 // Matches the full name of each test against the user-specified 1154 // filter to decide whether the test should run, then records the 1155 // result in each TestCase and TestInfo object. 1156 // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests 1157 // based on sharding variables in the environment. 1158 // Returns the number of tests that should run. 1159 int FilterTests(ReactionToSharding shard_tests); 1160 1161 // Lists all the tests by name. 1162 void ListAllTests(); 1163 1164 const TestCase* current_test_case() const { return current_test_case_; } 1165 TestInfo* current_test_info() { return current_test_info_; } 1166 const TestInfo* current_test_info() const { return current_test_info_; } 1167 1168 // Returns the list of environments that need to be set-up/torn-down 1169 // before/after the tests are run. 1170 internal::List<Environment*>* environments() { return &environments_; } 1171 internal::List<Environment*>* environments_in_reverse_order() { 1172 return &environments_in_reverse_order_; 1173 } 1174 1175 internal::List<TestCase*>* test_cases() { return &test_cases_; } 1176 const internal::List<TestCase*>* test_cases() const { return &test_cases_; } 1177 1178 // Getters for the per-thread Google Test trace stack. 1179 internal::List<TraceInfo>* gtest_trace_stack() { 1180 return gtest_trace_stack_.pointer(); 1181 } 1182 const internal::List<TraceInfo>* gtest_trace_stack() const { 1183 return gtest_trace_stack_.pointer(); 1184 } 1185 1186 #if GTEST_HAS_DEATH_TEST 1187 // Returns a pointer to the parsed --gtest_internal_run_death_test 1188 // flag, or NULL if that flag was not specified. 1189 // This information is useful only in a death test child process. 1190 const InternalRunDeathTestFlag* internal_run_death_test_flag() const { 1191 return internal_run_death_test_flag_.get(); 1192 } 1193 1194 // Returns a pointer to the current death test factory. 1195 internal::DeathTestFactory* death_test_factory() { 1196 return death_test_factory_.get(); 1197 } 1198 1199 friend class ReplaceDeathTestFactory; 1200 #endif // GTEST_HAS_DEATH_TEST 1201 1202 private: 1203 friend class ::testing::UnitTest; 1204 1205 // The UnitTest object that owns this implementation object. 1206 UnitTest* const parent_; 1207 1208 // The working directory when the first TEST() or TEST_F() was 1209 // executed. 1210 internal::FilePath original_working_dir_; 1211 1212 // The default test part result reporters. 1213 DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_; 1214 DefaultPerThreadTestPartResultReporter 1215 default_per_thread_test_part_result_reporter_; 1216 1217 // Points to (but doesn't own) the global test part result reporter. 1218 TestPartResultReporterInterface* global_test_part_result_repoter_; 1219 1220 // Protects read and write access to global_test_part_result_reporter_. 1221 internal::Mutex global_test_part_result_reporter_mutex_; 1222 1223 // Points to (but doesn't own) the per-thread test part result reporter. 1224 internal::ThreadLocal<TestPartResultReporterInterface*> 1225 per_thread_test_part_result_reporter_; 1226 1227 // The list of environments that need to be set-up/torn-down 1228 // before/after the tests are run. environments_in_reverse_order_ 1229 // simply mirrors environments_ in reverse order. 1230 internal::List<Environment*> environments_; 1231 internal::List<Environment*> environments_in_reverse_order_; 1232 1233 internal::List<TestCase*> test_cases_; // The list of TestCases. 1234 1235 #if GTEST_HAS_PARAM_TEST 1236 // ParameterizedTestRegistry object used to register value-parameterized 1237 // tests. 1238 internal::ParameterizedTestCaseRegistry parameterized_test_registry_; 1239 1240 // Indicates whether RegisterParameterizedTests() has been called already. 1241 bool parameterized_tests_registered_; 1242 #endif // GTEST_HAS_PARAM_TEST 1243 1244 // Points to the last death test case registered. Initially NULL. 1245 internal::ListNode<TestCase*>* last_death_test_case_; 1246 1247 // This points to the TestCase for the currently running test. It 1248 // changes as Google Test goes through one test case after another. 1249 // When no test is running, this is set to NULL and Google Test 1250 // stores assertion results in ad_hoc_test_result_. Initally NULL. 1251 TestCase* current_test_case_; 1252 1253 // This points to the TestInfo for the currently running test. It 1254 // changes as Google Test goes through one test after another. When 1255 // no test is running, this is set to NULL and Google Test stores 1256 // assertion results in ad_hoc_test_result_. Initially NULL. 1257 TestInfo* current_test_info_; 1258 1259 // Normally, a user only writes assertions inside a TEST or TEST_F, 1260 // or inside a function called by a TEST or TEST_F. Since Google 1261 // Test keeps track of which test is current running, it can 1262 // associate such an assertion with the test it belongs to. 1263 // 1264 // If an assertion is encountered when no TEST or TEST_F is running, 1265 // Google Test attributes the assertion result to an imaginary "ad hoc" 1266 // test, and records the result in ad_hoc_test_result_. 1267 internal::TestResult ad_hoc_test_result_; 1268 1269 // The unit test result printer. Will be deleted when the UnitTest 1270 // object is destructed. By default, a plain text printer is used, 1271 // but the user can set this field to use a custom printer if that 1272 // is desired. 1273 UnitTestEventListenerInterface* result_printer_; 1274 1275 // The OS stack trace getter. Will be deleted when the UnitTest 1276 // object is destructed. By default, an OsStackTraceGetter is used, 1277 // but the user can set this field to use a custom getter if that is 1278 // desired. 1279 OsStackTraceGetterInterface* os_stack_trace_getter_; 1280 1281 // How long the test took to run, in milliseconds. 1282 TimeInMillis elapsed_time_; 1283 1284 #if GTEST_HAS_DEATH_TEST 1285 // The decomposed components of the gtest_internal_run_death_test flag, 1286 // parsed when RUN_ALL_TESTS is called. 1287 internal::scoped_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_; 1288 internal::scoped_ptr<internal::DeathTestFactory> death_test_factory_; 1289 #endif // GTEST_HAS_DEATH_TEST 1290 1291 // A per-thread stack of traces created by the SCOPED_TRACE() macro. 1292 internal::ThreadLocal<internal::List<TraceInfo> > gtest_trace_stack_; 1293 1294 GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl); 1295 }; // class UnitTestImpl 1296 1297 // Convenience function for accessing the global UnitTest 1298 // implementation object. 1299 inline UnitTestImpl* GetUnitTestImpl() { 1300 return UnitTest::GetInstance()->impl(); 1301 } 1302 1303 // Internal helper functions for implementing the simple regular 1304 // expression matcher. 1305 bool IsInSet(char ch, const char* str); 1306 bool IsDigit(char ch); 1307 bool IsPunct(char ch); 1308 bool IsRepeat(char ch); 1309 bool IsWhiteSpace(char ch); 1310 bool IsWordChar(char ch); 1311 bool IsValidEscape(char ch); 1312 bool AtomMatchesChar(bool escaped, char pattern, char ch); 1313 bool ValidateRegex(const char* regex); 1314 bool MatchRegexAtHead(const char* regex, const char* str); 1315 bool MatchRepetitionAndRegexAtHead( 1316 bool escaped, char ch, char repeat, const char* regex, const char* str); 1317 bool MatchRegexAnywhere(const char* regex, const char* str); 1318 1319 // Parses the command line for Google Test flags, without initializing 1320 // other parts of Google Test. 1321 void ParseGoogleTestFlagsOnly(int* argc, char** argv); 1322 void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv); 1323 1324 #if GTEST_HAS_DEATH_TEST 1325 1326 // Returns the message describing the last system error, regardless of the 1327 // platform. 1328 String GetLastSystemErrorMessage(); 1329 1330 #if GTEST_OS_WINDOWS 1331 // Provides leak-safe Windows kernel handle ownership. 1332 class AutoHandle { 1333 public: 1334 AutoHandle() : handle_(INVALID_HANDLE_VALUE) {} 1335 explicit AutoHandle(HANDLE handle) : handle_(handle) {} 1336 1337 ~AutoHandle() { Reset(); } 1338 1339 HANDLE Get() const { return handle_; } 1340 void Reset() { Reset(INVALID_HANDLE_VALUE); } 1341 void Reset(HANDLE handle) { 1342 if (handle != handle_) { 1343 if (handle_ != INVALID_HANDLE_VALUE) 1344 ::CloseHandle(handle_); 1345 handle_ = handle; 1346 } 1347 } 1348 1349 private: 1350 HANDLE handle_; 1351 1352 GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle); 1353 }; 1354 #endif // GTEST_OS_WINDOWS 1355 1356 // Attempts to parse a string into a positive integer pointed to by the 1357 // number parameter. Returns true if that is possible. 1358 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use 1359 // it here. 1360 template <typename Integer> 1361 bool ParseNaturalNumber(const ::std::string& str, Integer* number) { 1362 // Fail fast if the given string does not begin with a digit; 1363 // this bypasses strtoXXX's "optional leading whitespace and plus 1364 // or minus sign" semantics, which are undesirable here. 1365 if (str.empty() || !isdigit(str[0])) { 1366 return false; 1367 } 1368 errno = 0; 1369 1370 char* end; 1371 // BiggestConvertible is the largest integer type that system-provided 1372 // string-to-number conversion routines can return. 1373 #if GTEST_OS_WINDOWS 1374 typedef unsigned __int64 BiggestConvertible; 1375 const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10); 1376 #else 1377 typedef unsigned long long BiggestConvertible; // NOLINT 1378 const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10); 1379 #endif // GTEST_OS_WINDOWS 1380 const bool parse_success = *end == '\0' && errno == 0; 1381 1382 // TODO(vladl (at) google.com): Convert this to compile time assertion when it is 1383 // available. 1384 GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed)); 1385 1386 const Integer result = static_cast<Integer>(parsed); 1387 if (parse_success && static_cast<BiggestConvertible>(result) == parsed) { 1388 *number = result; 1389 return true; 1390 } 1391 return false; 1392 } 1393 #endif // GTEST_HAS_DEATH_TEST 1394 1395 } // namespace internal 1396 } // namespace testing 1397 1398 #endif // GTEST_SRC_GTEST_INTERNAL_INL_H_ 1399