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