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