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