gtest-internal-inl.h revision dd1c93d5709e32713961cfd95fe30489a4ad2d26
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 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
63namespace 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.
70GTEST_DECLARE_bool_(death_test_use_fork);
71
72namespace internal {
73
74// The value of GetTestTypeId() as seen from within the Google Test
75// library.  This is solely for testing GetTestTypeId().
76extern const TypeId kTestTypeIdInGoogleTest;
77
78// Names of the flags (needed for parsing Google Test flags).
79const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests";
80const char kBreakOnFailureFlag[] = "break_on_failure";
81const char kCatchExceptionsFlag[] = "catch_exceptions";
82const char kColorFlag[] = "color";
83const char kFilterFlag[] = "filter";
84const char kListTestsFlag[] = "list_tests";
85const char kOutputFlag[] = "output";
86const char kPrintTimeFlag[] = "print_time";
87const char kRepeatFlag[] = "repeat";
88const 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.
92class 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)'.
153char* 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.
168String WideStringToUtf8(const wchar_t* str, int num_chars);
169
170// Returns the number of active threads, or 0 when there is an error.
171size_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.
177void 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.
185bool 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.
191Int32 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.
197bool 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
212template <typename E>  // E is the element type.
213class 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.
218template <typename E>  // E is the element type.
219class 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.
253template <typename E>  // E is the element type.
254class 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.
441template <typename E>
442List<E>::~List() {
443  Clear();
444}
445
446// A function for deleting an object.  Handy for being used as a
447// functor.
448template <typename T>
449static 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.
457class 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.
491class 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.
514class 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 true iff the test has a non-fatal failure.
552  bool HasNonfatalFailure() const;
553
554  // Returns the elapsed time, in milliseconds.
555  TimeInMillis elapsed_time() const { return elapsed_time_; }
556
557  // Sets the elapsed time.
558  void set_elapsed_time(TimeInMillis elapsed) { elapsed_time_ = elapsed; }
559
560  // Adds a test part result to the list.
561  void AddTestPartResult(const TestPartResult& test_part_result);
562
563  // Adds a test property to the list. The property is validated and may add
564  // a non-fatal failure if invalid (e.g., if it conflicts with reserved
565  // key names). If a property is already recorded for the same key, the
566  // value will be updated, rather than storing multiple values for the same
567  // key.
568  void RecordProperty(const internal::TestProperty& test_property);
569
570  // Adds a failure if the key is a reserved attribute of Google Test
571  // testcase tags.  Returns true if the property is valid.
572  // TODO(russr): Validate attribute names are legal and human readable.
573  static bool ValidateTestProperty(const internal::TestProperty& test_property);
574
575  // Returns the death test count.
576  int death_test_count() const { return death_test_count_; }
577
578  // Increments the death test count, returning the new count.
579  int increment_death_test_count() { return ++death_test_count_; }
580
581  // Clears the test part results.
582  void ClearTestPartResults() { test_part_results_.Clear(); }
583
584  // Clears the object.
585  void Clear();
586 private:
587  // Protects mutable state of the property list and of owned properties, whose
588  // values may be updated.
589  internal::Mutex test_properites_mutex_;
590
591  // The list of TestPartResults
592  internal::List<TestPartResult> test_part_results_;
593  // The list of TestProperties
594  internal::List<internal::TestProperty> test_properties_;
595  // Running count of death tests.
596  int death_test_count_;
597  // The elapsed time, in milliseconds.
598  TimeInMillis elapsed_time_;
599
600  // We disallow copying TestResult.
601  GTEST_DISALLOW_COPY_AND_ASSIGN_(TestResult);
602};  // class TestResult
603
604class TestInfoImpl {
605 public:
606  TestInfoImpl(TestInfo* parent, const char* test_case_name,
607               const char* name, const char* test_case_comment,
608               const char* comment, TypeId fixture_class_id,
609               internal::TestFactoryBase* factory);
610  ~TestInfoImpl();
611
612  // Returns true if this test should run.
613  bool should_run() const { return should_run_; }
614
615  // Sets the should_run member.
616  void set_should_run(bool should) { should_run_ = should; }
617
618  // Returns true if this test is disabled. Disabled tests are not run.
619  bool is_disabled() const { return is_disabled_; }
620
621  // Sets the is_disabled member.
622  void set_is_disabled(bool is) { is_disabled_ = is; }
623
624  // Returns true if this test matches the filter specified by the user.
625  bool matches_filter() const { return matches_filter_; }
626
627  // Sets the matches_filter member.
628  void set_matches_filter(bool matches) { matches_filter_ = matches; }
629
630  // Returns the test case name.
631  const char* test_case_name() const { return test_case_name_.c_str(); }
632
633  // Returns the test name.
634  const char* name() const { return name_.c_str(); }
635
636  // Returns the test case comment.
637  const char* test_case_comment() const { return test_case_comment_.c_str(); }
638
639  // Returns the test comment.
640  const char* comment() const { return comment_.c_str(); }
641
642  // Returns the ID of the test fixture class.
643  TypeId fixture_class_id() const { return fixture_class_id_; }
644
645  // Returns the test result.
646  internal::TestResult* result() { return &result_; }
647  const internal::TestResult* result() const { return &result_; }
648
649  // Creates the test object, runs it, records its result, and then
650  // deletes it.
651  void Run();
652
653  // Calls the given TestInfo object's Run() method.
654  static void RunTest(TestInfo * test_info) {
655    test_info->impl()->Run();
656  }
657
658  // Clears the test result.
659  void ClearResult() { result_.Clear(); }
660
661  // Clears the test result in the given TestInfo object.
662  static void ClearTestResult(TestInfo * test_info) {
663    test_info->impl()->ClearResult();
664  }
665
666 private:
667  // These fields are immutable properties of the test.
668  TestInfo* const parent_;          // The owner of this object
669  const String test_case_name_;     // Test case name
670  const String name_;               // Test name
671  const String test_case_comment_;  // Test case comment
672  const String comment_;            // Test comment
673  const TypeId fixture_class_id_;   // ID of the test fixture class
674  bool should_run_;                 // True iff this test should run
675  bool is_disabled_;                // True iff this test is disabled
676  bool matches_filter_;             // True if this test matches the
677                                    // user-specified filter.
678  internal::TestFactoryBase* const factory_;  // The factory that creates
679                                              // the test object
680
681  // This field is mutable and needs to be reset before running the
682  // test for the second time.
683  internal::TestResult result_;
684
685  GTEST_DISALLOW_COPY_AND_ASSIGN_(TestInfoImpl);
686};
687
688}  // namespace internal
689
690// A test case, which consists of a list of TestInfos.
691//
692// TestCase is not copyable.
693class TestCase {
694 public:
695  // Creates a TestCase with the given name.
696  //
697  // TestCase does NOT have a default constructor.  Always use this
698  // constructor to create a TestCase object.
699  //
700  // Arguments:
701  //
702  //   name:         name of the test case
703  //   set_up_tc:    pointer to the function that sets up the test case
704  //   tear_down_tc: pointer to the function that tears down the test case
705  TestCase(const char* name, const char* comment,
706           Test::SetUpTestCaseFunc set_up_tc,
707           Test::TearDownTestCaseFunc tear_down_tc);
708
709  // Destructor of TestCase.
710  virtual ~TestCase();
711
712  // Gets the name of the TestCase.
713  const char* name() const { return name_.c_str(); }
714
715  // Returns the test case comment.
716  const char* comment() const { return comment_.c_str(); }
717
718  // Returns true if any test in this test case should run.
719  bool should_run() const { return should_run_; }
720
721  // Sets the should_run member.
722  void set_should_run(bool should) { should_run_ = should; }
723
724  // Gets the (mutable) list of TestInfos in this TestCase.
725  internal::List<TestInfo*>& test_info_list() { return *test_info_list_; }
726
727  // Gets the (immutable) list of TestInfos in this TestCase.
728  const internal::List<TestInfo *> & test_info_list() const {
729    return *test_info_list_;
730  }
731
732  // Gets the number of successful tests in this test case.
733  int successful_test_count() const;
734
735  // Gets the number of failed tests in this test case.
736  int failed_test_count() const;
737
738  // Gets the number of disabled tests in this test case.
739  int disabled_test_count() const;
740
741  // Get the number of tests in this test case that should run.
742  int test_to_run_count() const;
743
744  // Gets the number of all tests in this test case.
745  int total_test_count() const;
746
747  // Returns true iff the test case passed.
748  bool Passed() const { return !Failed(); }
749
750  // Returns true iff the test case failed.
751  bool Failed() const { return failed_test_count() > 0; }
752
753  // Returns the elapsed time, in milliseconds.
754  internal::TimeInMillis elapsed_time() const { return elapsed_time_; }
755
756  // Adds a TestInfo to this test case.  Will delete the TestInfo upon
757  // destruction of the TestCase object.
758  void AddTestInfo(TestInfo * test_info);
759
760  // Finds and returns a TestInfo with the given name.  If one doesn't
761  // exist, returns NULL.
762  TestInfo* GetTestInfo(const char* test_name);
763
764  // Clears the results of all tests in this test case.
765  void ClearResult();
766
767  // Clears the results of all tests in the given test case.
768  static void ClearTestCaseResult(TestCase* test_case) {
769    test_case->ClearResult();
770  }
771
772  // Runs every test in this TestCase.
773  void Run();
774
775  // Runs every test in the given TestCase.
776  static void RunTestCase(TestCase * test_case) { test_case->Run(); }
777
778  // Returns true iff test passed.
779  static bool TestPassed(const TestInfo * test_info) {
780    const internal::TestInfoImpl* const impl = test_info->impl();
781    return impl->should_run() && impl->result()->Passed();
782  }
783
784  // Returns true iff test failed.
785  static bool TestFailed(const TestInfo * test_info) {
786    const internal::TestInfoImpl* const impl = test_info->impl();
787    return impl->should_run() && impl->result()->Failed();
788  }
789
790  // Returns true iff test is disabled.
791  static bool TestDisabled(const TestInfo * test_info) {
792    return test_info->impl()->is_disabled();
793  }
794
795  // Returns true if the given test should run.
796  static bool ShouldRunTest(const TestInfo *test_info) {
797    return test_info->impl()->should_run();
798  }
799
800 private:
801  // Name of the test case.
802  internal::String name_;
803  // Comment on the test case.
804  internal::String comment_;
805  // List of TestInfos.
806  internal::List<TestInfo*>* test_info_list_;
807  // Pointer to the function that sets up the test case.
808  Test::SetUpTestCaseFunc set_up_tc_;
809  // Pointer to the function that tears down the test case.
810  Test::TearDownTestCaseFunc tear_down_tc_;
811  // True iff any test in this test case should run.
812  bool should_run_;
813  // Elapsed time, in milliseconds.
814  internal::TimeInMillis elapsed_time_;
815
816  // We disallow copying TestCases.
817  GTEST_DISALLOW_COPY_AND_ASSIGN_(TestCase);
818};
819
820namespace internal {
821
822// Class UnitTestOptions.
823//
824// This class contains functions for processing options the user
825// specifies when running the tests.  It has only static members.
826//
827// In most cases, the user can specify an option using either an
828// environment variable or a command line flag.  E.g. you can set the
829// test filter using either GTEST_FILTER or --gtest_filter.  If both
830// the variable and the flag are present, the latter overrides the
831// former.
832class UnitTestOptions {
833 public:
834  // Functions for processing the gtest_output flag.
835
836  // Returns the output format, or "" for normal printed output.
837  static String GetOutputFormat();
838
839  // Returns the absolute path of the requested output file, or the
840  // default (test_detail.xml in the original working directory) if
841  // none was explicitly specified.
842  static String GetAbsolutePathToOutputFile();
843
844  // Functions for processing the gtest_filter flag.
845
846  // Returns true iff the wildcard pattern matches the string.  The
847  // first ':' or '\0' character in pattern marks the end of it.
848  //
849  // This recursive algorithm isn't very efficient, but is clear and
850  // works well enough for matching test names, which are short.
851  static bool PatternMatchesString(const char *pattern, const char *str);
852
853  // Returns true iff the user-specified filter matches the test case
854  // name and the test name.
855  static bool FilterMatchesTest(const String &test_case_name,
856                                const String &test_name);
857
858#if GTEST_OS_WINDOWS
859  // Function for supporting the gtest_catch_exception flag.
860
861  // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
862  // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
863  // This function is useful as an __except condition.
864  static int GTestShouldProcessSEH(DWORD exception_code);
865#endif  // GTEST_OS_WINDOWS
866
867  // Returns true if "name" matches the ':' separated list of glob-style
868  // filters in "filter".
869  static bool MatchesFilter(const String& name, const char* filter);
870};
871
872// Returns the current application's name, removing directory path if that
873// is present.  Used by UnitTestOptions::GetOutputFile.
874FilePath GetCurrentExecutableName();
875
876// The role interface for getting the OS stack trace as a string.
877class OsStackTraceGetterInterface {
878 public:
879  OsStackTraceGetterInterface() {}
880  virtual ~OsStackTraceGetterInterface() {}
881
882  // Returns the current OS stack trace as a String.  Parameters:
883  //
884  //   max_depth  - the maximum number of stack frames to be included
885  //                in the trace.
886  //   skip_count - the number of top frames to be skipped; doesn't count
887  //                against max_depth.
888  virtual String CurrentStackTrace(int max_depth, int skip_count) = 0;
889
890  // UponLeavingGTest() should be called immediately before Google Test calls
891  // user code. It saves some information about the current stack that
892  // CurrentStackTrace() will use to find and hide Google Test stack frames.
893  virtual void UponLeavingGTest() = 0;
894
895 private:
896  GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface);
897};
898
899// A working implementation of the OsStackTraceGetterInterface interface.
900class OsStackTraceGetter : public OsStackTraceGetterInterface {
901 public:
902  OsStackTraceGetter() {}
903  virtual String CurrentStackTrace(int max_depth, int skip_count);
904  virtual void UponLeavingGTest();
905
906  // This string is inserted in place of stack frames that are part of
907  // Google Test's implementation.
908  static const char* const kElidedFramesMarker;
909
910 private:
911  Mutex mutex_;  // protects all internal state
912
913  // We save the stack frame below the frame that calls user code.
914  // We do this because the address of the frame immediately below
915  // the user code changes between the call to UponLeavingGTest()
916  // and any calls to CurrentStackTrace() from within the user code.
917  void* caller_frame_;
918
919  GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter);
920};
921
922// Information about a Google Test trace point.
923struct TraceInfo {
924  const char* file;
925  int line;
926  String message;
927};
928
929// This is the default global test part result reporter used in UnitTestImpl.
930// This class should only be used by UnitTestImpl.
931class DefaultGlobalTestPartResultReporter
932  : public TestPartResultReporterInterface {
933 public:
934  explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test);
935  // Implements the TestPartResultReporterInterface. Reports the test part
936  // result in the current test.
937  virtual void ReportTestPartResult(const TestPartResult& result);
938
939 private:
940  UnitTestImpl* const unit_test_;
941
942  GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter);
943};
944
945// This is the default per thread test part result reporter used in
946// UnitTestImpl. This class should only be used by UnitTestImpl.
947class DefaultPerThreadTestPartResultReporter
948    : public TestPartResultReporterInterface {
949 public:
950  explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test);
951  // Implements the TestPartResultReporterInterface. The implementation just
952  // delegates to the current global test part result reporter of *unit_test_.
953  virtual void ReportTestPartResult(const TestPartResult& result);
954
955 private:
956  UnitTestImpl* const unit_test_;
957
958  GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter);
959};
960
961// The private implementation of the UnitTest class.  We don't protect
962// the methods under a mutex, as this class is not accessible by a
963// user and the UnitTest class that delegates work to this class does
964// proper locking.
965class UnitTestImpl {
966 public:
967  explicit UnitTestImpl(UnitTest* parent);
968  virtual ~UnitTestImpl();
969
970  // There are two different ways to register your own TestPartResultReporter.
971  // You can register your own repoter to listen either only for test results
972  // from the current thread or for results from all threads.
973  // By default, each per-thread test result repoter just passes a new
974  // TestPartResult to the global test result reporter, which registers the
975  // test part result for the currently running test.
976
977  // Returns the global test part result reporter.
978  TestPartResultReporterInterface* GetGlobalTestPartResultReporter();
979
980  // Sets the global test part result reporter.
981  void SetGlobalTestPartResultReporter(
982      TestPartResultReporterInterface* reporter);
983
984  // Returns the test part result reporter for the current thread.
985  TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread();
986
987  // Sets the test part result reporter for the current thread.
988  void SetTestPartResultReporterForCurrentThread(
989      TestPartResultReporterInterface* reporter);
990
991  // Gets the number of successful test cases.
992  int successful_test_case_count() const;
993
994  // Gets the number of failed test cases.
995  int failed_test_case_count() const;
996
997  // Gets the number of all test cases.
998  int total_test_case_count() const;
999
1000  // Gets the number of all test cases that contain at least one test
1001  // that should run.
1002  int test_case_to_run_count() const;
1003
1004  // Gets the number of successful tests.
1005  int successful_test_count() const;
1006
1007  // Gets the number of failed tests.
1008  int failed_test_count() const;
1009
1010  // Gets the number of disabled tests.
1011  int disabled_test_count() const;
1012
1013  // Gets the number of all tests.
1014  int total_test_count() const;
1015
1016  // Gets the number of tests that should run.
1017  int test_to_run_count() const;
1018
1019  // Gets the elapsed time, in milliseconds.
1020  TimeInMillis elapsed_time() const { return elapsed_time_; }
1021
1022  // Returns true iff the unit test passed (i.e. all test cases passed).
1023  bool Passed() const { return !Failed(); }
1024
1025  // Returns true iff the unit test failed (i.e. some test case failed
1026  // or something outside of all tests failed).
1027  bool Failed() const {
1028    return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed();
1029  }
1030
1031  // Returns the TestResult for the test that's currently running, or
1032  // the TestResult for the ad hoc test if no test is running.
1033  internal::TestResult* current_test_result();
1034
1035  // Returns the TestResult for the ad hoc test.
1036  const internal::TestResult* ad_hoc_test_result() const {
1037    return &ad_hoc_test_result_;
1038  }
1039
1040  // Sets the unit test result printer.
1041  //
1042  // Does nothing if the input and the current printer object are the
1043  // same; otherwise, deletes the old printer object and makes the
1044  // input the current printer.
1045  void set_result_printer(UnitTestEventListenerInterface * result_printer);
1046
1047  // Returns the current unit test result printer if it is not NULL;
1048  // otherwise, creates an appropriate result printer, makes it the
1049  // current printer, and returns it.
1050  UnitTestEventListenerInterface* result_printer();
1051
1052  // Sets the OS stack trace getter.
1053  //
1054  // Does nothing if the input and the current OS stack trace getter
1055  // are the same; otherwise, deletes the old getter and makes the
1056  // input the current getter.
1057  void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter);
1058
1059  // Returns the current OS stack trace getter if it is not NULL;
1060  // otherwise, creates an OsStackTraceGetter, makes it the current
1061  // getter, and returns it.
1062  OsStackTraceGetterInterface* os_stack_trace_getter();
1063
1064  // Returns the current OS stack trace as a String.
1065  //
1066  // The maximum number of stack frames to be included is specified by
1067  // the gtest_stack_trace_depth flag.  The skip_count parameter
1068  // specifies the number of top frames to be skipped, which doesn't
1069  // count against the number of frames to be included.
1070  //
1071  // For example, if Foo() calls Bar(), which in turn calls
1072  // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
1073  // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
1074  String CurrentOsStackTraceExceptTop(int skip_count);
1075
1076  // Finds and returns a TestCase with the given name.  If one doesn't
1077  // exist, creates one and returns it.
1078  //
1079  // Arguments:
1080  //
1081  //   test_case_name: name of the test case
1082  //   set_up_tc:      pointer to the function that sets up the test case
1083  //   tear_down_tc:   pointer to the function that tears down the test case
1084  TestCase* GetTestCase(const char* test_case_name,
1085                        const char* comment,
1086                        Test::SetUpTestCaseFunc set_up_tc,
1087                        Test::TearDownTestCaseFunc tear_down_tc);
1088
1089  // Adds a TestInfo to the unit test.
1090  //
1091  // Arguments:
1092  //
1093  //   set_up_tc:    pointer to the function that sets up the test case
1094  //   tear_down_tc: pointer to the function that tears down the test case
1095  //   test_info:    the TestInfo object
1096  void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc,
1097                   Test::TearDownTestCaseFunc tear_down_tc,
1098                   TestInfo * test_info) {
1099    // In order to support thread-safe death tests, we need to
1100    // remember the original working directory when the test program
1101    // was first invoked.  We cannot do this in RUN_ALL_TESTS(), as
1102    // the user may have changed the current directory before calling
1103    // RUN_ALL_TESTS().  Therefore we capture the current directory in
1104    // AddTestInfo(), which is called to register a TEST or TEST_F
1105    // before main() is reached.
1106    if (original_working_dir_.IsEmpty()) {
1107      original_working_dir_.Set(FilePath::GetCurrentDir());
1108      if (original_working_dir_.IsEmpty()) {
1109        printf("%s\n", "Failed to get the current working directory.");
1110        abort();
1111      }
1112    }
1113
1114    GetTestCase(test_info->test_case_name(),
1115                test_info->test_case_comment(),
1116                set_up_tc,
1117                tear_down_tc)->AddTestInfo(test_info);
1118  }
1119
1120#if GTEST_HAS_PARAM_TEST
1121  // Returns ParameterizedTestCaseRegistry object used to keep track of
1122  // value-parameterized tests and instantiate and register them.
1123  internal::ParameterizedTestCaseRegistry& parameterized_test_registry() {
1124    return parameterized_test_registry_;
1125  }
1126#endif  // GTEST_HAS_PARAM_TEST
1127
1128  // Sets the TestCase object for the test that's currently running.
1129  void set_current_test_case(TestCase* current_test_case) {
1130    current_test_case_ = current_test_case;
1131  }
1132
1133  // Sets the TestInfo object for the test that's currently running.  If
1134  // current_test_info is NULL, the assertion results will be stored in
1135  // ad_hoc_test_result_.
1136  void set_current_test_info(TestInfo* current_test_info) {
1137    current_test_info_ = current_test_info;
1138  }
1139
1140  // Registers all parameterized tests defined using TEST_P and
1141  // INSTANTIATE_TEST_P, creating regular tests for each test/parameter
1142  // combination. This method can be called more then once; it has
1143  // guards protecting from registering the tests more then once.
1144  // If value-parameterized tests are disabled, RegisterParameterizedTests
1145  // is present but does nothing.
1146  void RegisterParameterizedTests();
1147
1148  // Runs all tests in this UnitTest object, prints the result, and
1149  // returns 0 if all tests are successful, or 1 otherwise.  If any
1150  // exception is thrown during a test on Windows, this test is
1151  // considered to be failed, but the rest of the tests will still be
1152  // run.  (We disable exceptions on Linux and Mac OS X, so the issue
1153  // doesn't apply there.)
1154  int RunAllTests();
1155
1156  // Clears the results of all tests, including the ad hoc test.
1157  void ClearResult() {
1158    test_cases_.ForEach(TestCase::ClearTestCaseResult);
1159    ad_hoc_test_result_.Clear();
1160  }
1161
1162  enum ReactionToSharding {
1163    HONOR_SHARDING_PROTOCOL,
1164    IGNORE_SHARDING_PROTOCOL
1165  };
1166
1167  // Matches the full name of each test against the user-specified
1168  // filter to decide whether the test should run, then records the
1169  // result in each TestCase and TestInfo object.
1170  // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests
1171  // based on sharding variables in the environment.
1172  // Returns the number of tests that should run.
1173  int FilterTests(ReactionToSharding shard_tests);
1174
1175  // Prints the names of the tests matching the user-specified filter flag.
1176  void ListTestsMatchingFilter();
1177
1178  const TestCase* current_test_case() const { return current_test_case_; }
1179  TestInfo* current_test_info() { return current_test_info_; }
1180  const TestInfo* current_test_info() const { return current_test_info_; }
1181
1182  // Returns the list of environments that need to be set-up/torn-down
1183  // before/after the tests are run.
1184  internal::List<Environment*>* environments() { return &environments_; }
1185  internal::List<Environment*>* environments_in_reverse_order() {
1186    return &environments_in_reverse_order_;
1187  }
1188
1189  internal::List<TestCase*>* test_cases() { return &test_cases_; }
1190  const internal::List<TestCase*>* test_cases() const { return &test_cases_; }
1191
1192  // Getters for the per-thread Google Test trace stack.
1193  internal::List<TraceInfo>* gtest_trace_stack() {
1194    return gtest_trace_stack_.pointer();
1195  }
1196  const internal::List<TraceInfo>* gtest_trace_stack() const {
1197    return gtest_trace_stack_.pointer();
1198  }
1199
1200#if GTEST_HAS_DEATH_TEST
1201  // Returns a pointer to the parsed --gtest_internal_run_death_test
1202  // flag, or NULL if that flag was not specified.
1203  // This information is useful only in a death test child process.
1204  const InternalRunDeathTestFlag* internal_run_death_test_flag() const {
1205    return internal_run_death_test_flag_.get();
1206  }
1207
1208  // Returns a pointer to the current death test factory.
1209  internal::DeathTestFactory* death_test_factory() {
1210    return death_test_factory_.get();
1211  }
1212
1213  friend class ReplaceDeathTestFactory;
1214#endif  // GTEST_HAS_DEATH_TEST
1215
1216 private:
1217  friend class ::testing::UnitTest;
1218
1219  // The UnitTest object that owns this implementation object.
1220  UnitTest* const parent_;
1221
1222  // The working directory when the first TEST() or TEST_F() was
1223  // executed.
1224  internal::FilePath original_working_dir_;
1225
1226  // The default test part result reporters.
1227  DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_;
1228  DefaultPerThreadTestPartResultReporter
1229      default_per_thread_test_part_result_reporter_;
1230
1231  // Points to (but doesn't own) the global test part result reporter.
1232  TestPartResultReporterInterface* global_test_part_result_repoter_;
1233
1234  // Protects read and write access to global_test_part_result_reporter_.
1235  internal::Mutex global_test_part_result_reporter_mutex_;
1236
1237  // Points to (but doesn't own) the per-thread test part result reporter.
1238  internal::ThreadLocal<TestPartResultReporterInterface*>
1239      per_thread_test_part_result_reporter_;
1240
1241  // The list of environments that need to be set-up/torn-down
1242  // before/after the tests are run.  environments_in_reverse_order_
1243  // simply mirrors environments_ in reverse order.
1244  internal::List<Environment*> environments_;
1245  internal::List<Environment*> environments_in_reverse_order_;
1246
1247  internal::List<TestCase*> test_cases_;  // The list of TestCases.
1248
1249#if GTEST_HAS_PARAM_TEST
1250  // ParameterizedTestRegistry object used to register value-parameterized
1251  // tests.
1252  internal::ParameterizedTestCaseRegistry parameterized_test_registry_;
1253
1254  // Indicates whether RegisterParameterizedTests() has been called already.
1255  bool parameterized_tests_registered_;
1256#endif  // GTEST_HAS_PARAM_TEST
1257
1258  // Points to the last death test case registered.  Initially NULL.
1259  internal::ListNode<TestCase*>* last_death_test_case_;
1260
1261  // This points to the TestCase for the currently running test.  It
1262  // changes as Google Test goes through one test case after another.
1263  // When no test is running, this is set to NULL and Google Test
1264  // stores assertion results in ad_hoc_test_result_.  Initally NULL.
1265  TestCase* current_test_case_;
1266
1267  // This points to the TestInfo for the currently running test.  It
1268  // changes as Google Test goes through one test after another.  When
1269  // no test is running, this is set to NULL and Google Test stores
1270  // assertion results in ad_hoc_test_result_.  Initially NULL.
1271  TestInfo* current_test_info_;
1272
1273  // Normally, a user only writes assertions inside a TEST or TEST_F,
1274  // or inside a function called by a TEST or TEST_F.  Since Google
1275  // Test keeps track of which test is current running, it can
1276  // associate such an assertion with the test it belongs to.
1277  //
1278  // If an assertion is encountered when no TEST or TEST_F is running,
1279  // Google Test attributes the assertion result to an imaginary "ad hoc"
1280  // test, and records the result in ad_hoc_test_result_.
1281  internal::TestResult ad_hoc_test_result_;
1282
1283  // The unit test result printer.  Will be deleted when the UnitTest
1284  // object is destructed.  By default, a plain text printer is used,
1285  // but the user can set this field to use a custom printer if that
1286  // is desired.
1287  UnitTestEventListenerInterface* result_printer_;
1288
1289  // The OS stack trace getter.  Will be deleted when the UnitTest
1290  // object is destructed.  By default, an OsStackTraceGetter is used,
1291  // but the user can set this field to use a custom getter if that is
1292  // desired.
1293  OsStackTraceGetterInterface* os_stack_trace_getter_;
1294
1295  // How long the test took to run, in milliseconds.
1296  TimeInMillis elapsed_time_;
1297
1298#if GTEST_HAS_DEATH_TEST
1299  // The decomposed components of the gtest_internal_run_death_test flag,
1300  // parsed when RUN_ALL_TESTS is called.
1301  internal::scoped_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;
1302  internal::scoped_ptr<internal::DeathTestFactory> death_test_factory_;
1303#endif  // GTEST_HAS_DEATH_TEST
1304
1305  // A per-thread stack of traces created by the SCOPED_TRACE() macro.
1306  internal::ThreadLocal<internal::List<TraceInfo> > gtest_trace_stack_;
1307
1308  GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl);
1309};  // class UnitTestImpl
1310
1311// Convenience function for accessing the global UnitTest
1312// implementation object.
1313inline UnitTestImpl* GetUnitTestImpl() {
1314  return UnitTest::GetInstance()->impl();
1315}
1316
1317// Clears all test part results of the current test.
1318inline void ClearCurrentTestPartResults() {
1319  GetUnitTestImpl()->current_test_result()->ClearTestPartResults();
1320}
1321
1322// Internal helper functions for implementing the simple regular
1323// expression matcher.
1324bool IsInSet(char ch, const char* str);
1325bool IsDigit(char ch);
1326bool IsPunct(char ch);
1327bool IsRepeat(char ch);
1328bool IsWhiteSpace(char ch);
1329bool IsWordChar(char ch);
1330bool IsValidEscape(char ch);
1331bool AtomMatchesChar(bool escaped, char pattern, char ch);
1332bool ValidateRegex(const char* regex);
1333bool MatchRegexAtHead(const char* regex, const char* str);
1334bool MatchRepetitionAndRegexAtHead(
1335    bool escaped, char ch, char repeat, const char* regex, const char* str);
1336bool MatchRegexAnywhere(const char* regex, const char* str);
1337
1338// Parses the command line for Google Test flags, without initializing
1339// other parts of Google Test.
1340void ParseGoogleTestFlagsOnly(int* argc, char** argv);
1341void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv);
1342
1343#if GTEST_HAS_DEATH_TEST
1344
1345// Returns the message describing the last system error, regardless of the
1346// platform.
1347String GetLastErrnoDescription();
1348
1349#if GTEST_OS_WINDOWS
1350// Provides leak-safe Windows kernel handle ownership.
1351class AutoHandle {
1352 public:
1353  AutoHandle() : handle_(INVALID_HANDLE_VALUE) {}
1354  explicit AutoHandle(HANDLE handle) : handle_(handle) {}
1355
1356  ~AutoHandle() { Reset(); }
1357
1358  HANDLE Get() const { return handle_; }
1359  void Reset() { Reset(INVALID_HANDLE_VALUE); }
1360  void Reset(HANDLE handle) {
1361    if (handle != handle_) {
1362      if (handle_ != INVALID_HANDLE_VALUE)
1363        ::CloseHandle(handle_);
1364      handle_ = handle;
1365    }
1366  }
1367
1368 private:
1369  HANDLE handle_;
1370
1371  GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle);
1372};
1373#endif  // GTEST_OS_WINDOWS
1374
1375// Attempts to parse a string into a positive integer pointed to by the
1376// number parameter.  Returns true if that is possible.
1377// GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use
1378// it here.
1379template <typename Integer>
1380bool ParseNaturalNumber(const ::std::string& str, Integer* number) {
1381  // Fail fast if the given string does not begin with a digit;
1382  // this bypasses strtoXXX's "optional leading whitespace and plus
1383  // or minus sign" semantics, which are undesirable here.
1384  if (str.empty() || !isdigit(str[0])) {
1385    return false;
1386  }
1387  errno = 0;
1388
1389  char* end;
1390  // BiggestConvertible is the largest integer type that system-provided
1391  // string-to-number conversion routines can return.
1392#if GTEST_OS_WINDOWS
1393  typedef unsigned __int64 BiggestConvertible;
1394  const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10);
1395#else
1396  typedef unsigned long long BiggestConvertible;  // NOLINT
1397  const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10);
1398#endif  // GTEST_OS_WINDOWS
1399  const bool parse_success = *end == '\0' && errno == 0;
1400
1401  // TODO(vladl@google.com): Convert this to compile time assertion when it is
1402  // available.
1403  GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed));
1404
1405  const Integer result = static_cast<Integer>(parsed);
1406  if (parse_success && static_cast<BiggestConvertible>(result) == parsed) {
1407    *number = result;
1408    return true;
1409  }
1410  return false;
1411}
1412#endif  // GTEST_HAS_DEATH_TEST
1413
1414}  // namespace internal
1415}  // namespace testing
1416
1417#endif  // GTEST_SRC_GTEST_INTERNAL_INL_H_
1418