1b89a7cc2SEnji Cooper // Copyright 2005, Google Inc.
2b89a7cc2SEnji Cooper // All rights reserved.
3b89a7cc2SEnji Cooper //
4b89a7cc2SEnji Cooper // Redistribution and use in source and binary forms, with or without
5b89a7cc2SEnji Cooper // modification, are permitted provided that the following conditions are
6b89a7cc2SEnji Cooper // met:
7b89a7cc2SEnji Cooper //
8b89a7cc2SEnji Cooper //     * Redistributions of source code must retain the above copyright
9b89a7cc2SEnji Cooper // notice, this list of conditions and the following disclaimer.
10b89a7cc2SEnji Cooper //     * Redistributions in binary form must reproduce the above
11b89a7cc2SEnji Cooper // copyright notice, this list of conditions and the following disclaimer
12b89a7cc2SEnji Cooper // in the documentation and/or other materials provided with the
13b89a7cc2SEnji Cooper // distribution.
14b89a7cc2SEnji Cooper //     * Neither the name of Google Inc. nor the names of its
15b89a7cc2SEnji Cooper // contributors may be used to endorse or promote products derived from
16b89a7cc2SEnji Cooper // this software without specific prior written permission.
17b89a7cc2SEnji Cooper //
18b89a7cc2SEnji Cooper // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19b89a7cc2SEnji Cooper // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20b89a7cc2SEnji Cooper // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21b89a7cc2SEnji Cooper // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22b89a7cc2SEnji Cooper // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23b89a7cc2SEnji Cooper // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24b89a7cc2SEnji Cooper // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25b89a7cc2SEnji Cooper // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26b89a7cc2SEnji Cooper // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27b89a7cc2SEnji Cooper // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28b89a7cc2SEnji Cooper // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29b89a7cc2SEnji Cooper 
30b89a7cc2SEnji Cooper // Utility functions and classes used by the Google C++ testing framework.//
31b89a7cc2SEnji Cooper // This file contains purely Google Test's internal implementation.  Please
32b89a7cc2SEnji Cooper // DO NOT #INCLUDE IT IN A USER PROGRAM.
33b89a7cc2SEnji Cooper 
3428f6c2f2SEnji Cooper #ifndef GOOGLETEST_SRC_GTEST_INTERNAL_INL_H_
3528f6c2f2SEnji Cooper #define GOOGLETEST_SRC_GTEST_INTERNAL_INL_H_
36b89a7cc2SEnji Cooper 
37b89a7cc2SEnji Cooper #ifndef _WIN32_WCE
38b89a7cc2SEnji Cooper #include <errno.h>
39b89a7cc2SEnji Cooper #endif  // !_WIN32_WCE
40b89a7cc2SEnji Cooper #include <stddef.h>
41b89a7cc2SEnji Cooper #include <stdlib.h>  // For strtoll/_strtoul64/malloc/free.
42b89a7cc2SEnji Cooper #include <string.h>  // For memmove.
43b89a7cc2SEnji Cooper 
44b89a7cc2SEnji Cooper #include <algorithm>
4528f6c2f2SEnji Cooper #include <cstdint>
4628f6c2f2SEnji Cooper #include <memory>
4728f6c2f2SEnji Cooper #include <set>
48b89a7cc2SEnji Cooper #include <string>
49b89a7cc2SEnji Cooper #include <vector>
50b89a7cc2SEnji Cooper 
51b89a7cc2SEnji Cooper #include "gtest/internal/gtest-port.h"
52b89a7cc2SEnji Cooper 
53b89a7cc2SEnji Cooper #if GTEST_CAN_STREAM_RESULTS_
54b89a7cc2SEnji Cooper #include <arpa/inet.h>  // NOLINT
55b89a7cc2SEnji Cooper #include <netdb.h>      // NOLINT
56b89a7cc2SEnji Cooper #endif
57b89a7cc2SEnji Cooper 
5828f6c2f2SEnji Cooper #ifdef GTEST_OS_WINDOWS
59b89a7cc2SEnji Cooper #include <windows.h>  // NOLINT
60b89a7cc2SEnji Cooper #endif                // GTEST_OS_WINDOWS
61b89a7cc2SEnji Cooper 
62b89a7cc2SEnji Cooper #include "gtest/gtest-spi.h"
6328f6c2f2SEnji Cooper #include "gtest/gtest.h"
64b89a7cc2SEnji Cooper 
65b89a7cc2SEnji Cooper GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
66b89a7cc2SEnji Cooper /* class A needs to have dll-interface to be used by clients of class B */)
67b89a7cc2SEnji Cooper 
68b89a7cc2SEnji Cooper // Declares the flags.
69b89a7cc2SEnji Cooper //
70b89a7cc2SEnji Cooper // We don't want the users to modify this flag in the code, but want
71b89a7cc2SEnji Cooper // Google Test's own unit tests to be able to access it. Therefore we
72b89a7cc2SEnji Cooper // declare it here as opposed to in gtest.h.
73b89a7cc2SEnji Cooper GTEST_DECLARE_bool_(death_test_use_fork);
74b89a7cc2SEnji Cooper 
7528f6c2f2SEnji Cooper namespace testing {
76b89a7cc2SEnji Cooper namespace internal {
77b89a7cc2SEnji Cooper 
78b89a7cc2SEnji Cooper // The value of GetTestTypeId() as seen from within the Google Test
79b89a7cc2SEnji Cooper // library.  This is solely for testing GetTestTypeId().
80b89a7cc2SEnji Cooper GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest;
81b89a7cc2SEnji Cooper 
82b89a7cc2SEnji Cooper // A valid random seed must be in [1, kMaxRandomSeed].
83b89a7cc2SEnji Cooper const int kMaxRandomSeed = 99999;
84b89a7cc2SEnji Cooper 
8528f6c2f2SEnji Cooper // g_help_flag is true if and only if the --help flag or an equivalent form
8628f6c2f2SEnji Cooper // is specified on the command line.
87b89a7cc2SEnji Cooper GTEST_API_ extern bool g_help_flag;
88b89a7cc2SEnji Cooper 
89b89a7cc2SEnji Cooper // Returns the current time in milliseconds.
90b89a7cc2SEnji Cooper GTEST_API_ TimeInMillis GetTimeInMillis();
91b89a7cc2SEnji Cooper 
9228f6c2f2SEnji Cooper // Returns true if and only if Google Test should use colors in the output.
93b89a7cc2SEnji Cooper GTEST_API_ bool ShouldUseColor(bool stdout_is_tty);
94b89a7cc2SEnji Cooper 
9528f6c2f2SEnji Cooper // Formats the given time in milliseconds as seconds. If the input is an exact N
9628f6c2f2SEnji Cooper // seconds, the output has a trailing decimal point (e.g., "N." instead of "N").
97b89a7cc2SEnji Cooper GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms);
98b89a7cc2SEnji Cooper 
99b89a7cc2SEnji Cooper // Converts the given time in milliseconds to a date string in the ISO 8601
100b89a7cc2SEnji Cooper // format, without the timezone information.  N.B.: due to the use the
101b89a7cc2SEnji Cooper // non-reentrant localtime() function, this function is not thread safe.  Do
102b89a7cc2SEnji Cooper // not use it in any code that can be called from multiple threads.
103b89a7cc2SEnji Cooper GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms);
104b89a7cc2SEnji Cooper 
105b89a7cc2SEnji Cooper // Parses a string for an Int32 flag, in the form of "--flag=value".
106b89a7cc2SEnji Cooper //
107b89a7cc2SEnji Cooper // On success, stores the value of the flag in *value, and returns
108b89a7cc2SEnji Cooper // true.  On failure, returns false without changing *value.
10928f6c2f2SEnji Cooper GTEST_API_ bool ParseFlag(const char* str, const char* flag, int32_t* value);
110b89a7cc2SEnji Cooper 
111b89a7cc2SEnji Cooper // Returns a random seed in range [1, kMaxRandomSeed] based on the
112b89a7cc2SEnji Cooper // given --gtest_random_seed flag value.
GetRandomSeedFromFlag(int32_t random_seed_flag)11328f6c2f2SEnji Cooper inline int GetRandomSeedFromFlag(int32_t random_seed_flag) {
11428f6c2f2SEnji Cooper   const unsigned int raw_seed =
11528f6c2f2SEnji Cooper       (random_seed_flag == 0) ? static_cast<unsigned int>(GetTimeInMillis())
11628f6c2f2SEnji Cooper                               : static_cast<unsigned int>(random_seed_flag);
117b89a7cc2SEnji Cooper 
118b89a7cc2SEnji Cooper   // Normalizes the actual seed to range [1, kMaxRandomSeed] such that
119b89a7cc2SEnji Cooper   // it's easy to type.
120b89a7cc2SEnji Cooper   const int normalized_seed =
121b89a7cc2SEnji Cooper       static_cast<int>((raw_seed - 1U) %
12228f6c2f2SEnji Cooper                        static_cast<unsigned int>(kMaxRandomSeed)) +
12328f6c2f2SEnji Cooper       1;
124b89a7cc2SEnji Cooper   return normalized_seed;
125b89a7cc2SEnji Cooper }
126b89a7cc2SEnji Cooper 
127b89a7cc2SEnji Cooper // Returns the first valid random seed after 'seed'.  The behavior is
128b89a7cc2SEnji Cooper // undefined if 'seed' is invalid.  The seed after kMaxRandomSeed is
129b89a7cc2SEnji Cooper // considered to be 1.
GetNextRandomSeed(int seed)130b89a7cc2SEnji Cooper inline int GetNextRandomSeed(int seed) {
131b89a7cc2SEnji Cooper   GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed)
132b89a7cc2SEnji Cooper       << "Invalid random seed " << seed << " - must be in [1, "
133b89a7cc2SEnji Cooper       << kMaxRandomSeed << "].";
134b89a7cc2SEnji Cooper   const int next_seed = seed + 1;
135b89a7cc2SEnji Cooper   return (next_seed > kMaxRandomSeed) ? 1 : next_seed;
136b89a7cc2SEnji Cooper }
137b89a7cc2SEnji Cooper 
138b89a7cc2SEnji Cooper // This class saves the values of all Google Test flags in its c'tor, and
139b89a7cc2SEnji Cooper // restores them in its d'tor.
140b89a7cc2SEnji Cooper class GTestFlagSaver {
141b89a7cc2SEnji Cooper  public:
142b89a7cc2SEnji Cooper   // The c'tor.
GTestFlagSaver()143b89a7cc2SEnji Cooper   GTestFlagSaver() {
14428f6c2f2SEnji Cooper     also_run_disabled_tests_ = GTEST_FLAG_GET(also_run_disabled_tests);
14528f6c2f2SEnji Cooper     break_on_failure_ = GTEST_FLAG_GET(break_on_failure);
14628f6c2f2SEnji Cooper     catch_exceptions_ = GTEST_FLAG_GET(catch_exceptions);
14728f6c2f2SEnji Cooper     color_ = GTEST_FLAG_GET(color);
14828f6c2f2SEnji Cooper     death_test_style_ = GTEST_FLAG_GET(death_test_style);
14928f6c2f2SEnji Cooper     death_test_use_fork_ = GTEST_FLAG_GET(death_test_use_fork);
15028f6c2f2SEnji Cooper     fail_fast_ = GTEST_FLAG_GET(fail_fast);
15128f6c2f2SEnji Cooper     filter_ = GTEST_FLAG_GET(filter);
15228f6c2f2SEnji Cooper     internal_run_death_test_ = GTEST_FLAG_GET(internal_run_death_test);
15328f6c2f2SEnji Cooper     list_tests_ = GTEST_FLAG_GET(list_tests);
15428f6c2f2SEnji Cooper     output_ = GTEST_FLAG_GET(output);
15528f6c2f2SEnji Cooper     brief_ = GTEST_FLAG_GET(brief);
15628f6c2f2SEnji Cooper     print_time_ = GTEST_FLAG_GET(print_time);
15728f6c2f2SEnji Cooper     print_utf8_ = GTEST_FLAG_GET(print_utf8);
15828f6c2f2SEnji Cooper     random_seed_ = GTEST_FLAG_GET(random_seed);
15928f6c2f2SEnji Cooper     repeat_ = GTEST_FLAG_GET(repeat);
16028f6c2f2SEnji Cooper     recreate_environments_when_repeating_ =
16128f6c2f2SEnji Cooper         GTEST_FLAG_GET(recreate_environments_when_repeating);
16228f6c2f2SEnji Cooper     shuffle_ = GTEST_FLAG_GET(shuffle);
16328f6c2f2SEnji Cooper     stack_trace_depth_ = GTEST_FLAG_GET(stack_trace_depth);
16428f6c2f2SEnji Cooper     stream_result_to_ = GTEST_FLAG_GET(stream_result_to);
16528f6c2f2SEnji Cooper     throw_on_failure_ = GTEST_FLAG_GET(throw_on_failure);
166b89a7cc2SEnji Cooper   }
167b89a7cc2SEnji Cooper 
168b89a7cc2SEnji Cooper   // The d'tor is not virtual.  DO NOT INHERIT FROM THIS CLASS.
~GTestFlagSaver()169b89a7cc2SEnji Cooper   ~GTestFlagSaver() {
17028f6c2f2SEnji Cooper     GTEST_FLAG_SET(also_run_disabled_tests, also_run_disabled_tests_);
17128f6c2f2SEnji Cooper     GTEST_FLAG_SET(break_on_failure, break_on_failure_);
17228f6c2f2SEnji Cooper     GTEST_FLAG_SET(catch_exceptions, catch_exceptions_);
17328f6c2f2SEnji Cooper     GTEST_FLAG_SET(color, color_);
17428f6c2f2SEnji Cooper     GTEST_FLAG_SET(death_test_style, death_test_style_);
17528f6c2f2SEnji Cooper     GTEST_FLAG_SET(death_test_use_fork, death_test_use_fork_);
17628f6c2f2SEnji Cooper     GTEST_FLAG_SET(filter, filter_);
17728f6c2f2SEnji Cooper     GTEST_FLAG_SET(fail_fast, fail_fast_);
17828f6c2f2SEnji Cooper     GTEST_FLAG_SET(internal_run_death_test, internal_run_death_test_);
17928f6c2f2SEnji Cooper     GTEST_FLAG_SET(list_tests, list_tests_);
18028f6c2f2SEnji Cooper     GTEST_FLAG_SET(output, output_);
18128f6c2f2SEnji Cooper     GTEST_FLAG_SET(brief, brief_);
18228f6c2f2SEnji Cooper     GTEST_FLAG_SET(print_time, print_time_);
18328f6c2f2SEnji Cooper     GTEST_FLAG_SET(print_utf8, print_utf8_);
18428f6c2f2SEnji Cooper     GTEST_FLAG_SET(random_seed, random_seed_);
18528f6c2f2SEnji Cooper     GTEST_FLAG_SET(repeat, repeat_);
18628f6c2f2SEnji Cooper     GTEST_FLAG_SET(recreate_environments_when_repeating,
18728f6c2f2SEnji Cooper                    recreate_environments_when_repeating_);
18828f6c2f2SEnji Cooper     GTEST_FLAG_SET(shuffle, shuffle_);
18928f6c2f2SEnji Cooper     GTEST_FLAG_SET(stack_trace_depth, stack_trace_depth_);
19028f6c2f2SEnji Cooper     GTEST_FLAG_SET(stream_result_to, stream_result_to_);
19128f6c2f2SEnji Cooper     GTEST_FLAG_SET(throw_on_failure, throw_on_failure_);
192b89a7cc2SEnji Cooper   }
193b89a7cc2SEnji Cooper 
194b89a7cc2SEnji Cooper  private:
195b89a7cc2SEnji Cooper   // Fields for saving the original values of flags.
196b89a7cc2SEnji Cooper   bool also_run_disabled_tests_;
197b89a7cc2SEnji Cooper   bool break_on_failure_;
198b89a7cc2SEnji Cooper   bool catch_exceptions_;
199b89a7cc2SEnji Cooper   std::string color_;
200b89a7cc2SEnji Cooper   std::string death_test_style_;
201b89a7cc2SEnji Cooper   bool death_test_use_fork_;
20228f6c2f2SEnji Cooper   bool fail_fast_;
203b89a7cc2SEnji Cooper   std::string filter_;
204b89a7cc2SEnji Cooper   std::string internal_run_death_test_;
205b89a7cc2SEnji Cooper   bool list_tests_;
206b89a7cc2SEnji Cooper   std::string output_;
20728f6c2f2SEnji Cooper   bool brief_;
208b89a7cc2SEnji Cooper   bool print_time_;
209b89a7cc2SEnji Cooper   bool print_utf8_;
21028f6c2f2SEnji Cooper   int32_t random_seed_;
21128f6c2f2SEnji Cooper   int32_t repeat_;
21228f6c2f2SEnji Cooper   bool recreate_environments_when_repeating_;
213b89a7cc2SEnji Cooper   bool shuffle_;
21428f6c2f2SEnji Cooper   int32_t stack_trace_depth_;
215b89a7cc2SEnji Cooper   std::string stream_result_to_;
216b89a7cc2SEnji Cooper   bool throw_on_failure_;
21728f6c2f2SEnji Cooper };
218b89a7cc2SEnji Cooper 
219b89a7cc2SEnji Cooper // Converts a Unicode code point to a narrow string in UTF-8 encoding.
220b89a7cc2SEnji Cooper // code_point parameter is of type UInt32 because wchar_t may not be
221b89a7cc2SEnji Cooper // wide enough to contain a code point.
222b89a7cc2SEnji Cooper // If the code_point is not a valid Unicode code point
223b89a7cc2SEnji Cooper // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
224b89a7cc2SEnji Cooper // to "(Invalid Unicode 0xXXXXXXXX)".
22528f6c2f2SEnji Cooper GTEST_API_ std::string CodePointToUtf8(uint32_t code_point);
226b89a7cc2SEnji Cooper 
227b89a7cc2SEnji Cooper // Converts a wide string to a narrow string in UTF-8 encoding.
228b89a7cc2SEnji Cooper // The wide string is assumed to have the following encoding:
22928f6c2f2SEnji Cooper //   UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin)
230b89a7cc2SEnji Cooper //   UTF-32 if sizeof(wchar_t) == 4 (on Linux)
231b89a7cc2SEnji Cooper // Parameter str points to a null-terminated wide string.
232b89a7cc2SEnji Cooper // Parameter num_chars may additionally limit the number
233b89a7cc2SEnji Cooper // of wchar_t characters processed. -1 is used when the entire string
234b89a7cc2SEnji Cooper // should be processed.
235b89a7cc2SEnji Cooper // If the string contains code points that are not valid Unicode code points
236b89a7cc2SEnji Cooper // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
237b89a7cc2SEnji Cooper // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
238b89a7cc2SEnji Cooper // and contains invalid UTF-16 surrogate pairs, values in those pairs
239b89a7cc2SEnji Cooper // will be encoded as individual Unicode characters from Basic Normal Plane.
240b89a7cc2SEnji Cooper GTEST_API_ std::string WideStringToUtf8(const wchar_t* str, int num_chars);
241b89a7cc2SEnji Cooper 
242b89a7cc2SEnji Cooper // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
243b89a7cc2SEnji Cooper // if the variable is present. If a file already exists at this location, this
244b89a7cc2SEnji Cooper // function will write over it. If the variable is present, but the file cannot
245b89a7cc2SEnji Cooper // be created, prints an error and exits.
246b89a7cc2SEnji Cooper void WriteToShardStatusFileIfNeeded();
247b89a7cc2SEnji Cooper 
248b89a7cc2SEnji Cooper // Checks whether sharding is enabled by examining the relevant
249b89a7cc2SEnji Cooper // environment variable values. If the variables are present,
250b89a7cc2SEnji Cooper // but inconsistent (e.g., shard_index >= total_shards), prints
251b89a7cc2SEnji Cooper // an error and exits. If in_subprocess_for_death_test, sharding is
252b89a7cc2SEnji Cooper // disabled because it must only be applied to the original test
253b89a7cc2SEnji Cooper // process. Otherwise, we could filter out death tests we intended to execute.
254b89a7cc2SEnji Cooper GTEST_API_ bool ShouldShard(const char* total_shards_str,
255b89a7cc2SEnji Cooper                             const char* shard_index_str,
256b89a7cc2SEnji Cooper                             bool in_subprocess_for_death_test);
257b89a7cc2SEnji Cooper 
25828f6c2f2SEnji Cooper // Parses the environment variable var as a 32-bit integer. If it is unset,
25928f6c2f2SEnji Cooper // returns default_val. If it is not a 32-bit integer, prints an error and
260b89a7cc2SEnji Cooper // and aborts.
26128f6c2f2SEnji Cooper GTEST_API_ int32_t Int32FromEnvOrDie(const char* env_var, int32_t default_val);
262b89a7cc2SEnji Cooper 
263b89a7cc2SEnji Cooper // Given the total number of shards, the shard index, and the test id,
26428f6c2f2SEnji Cooper // returns true if and only if the test should be run on this shard. The test id
26528f6c2f2SEnji Cooper // is some arbitrary but unique non-negative integer assigned to each test
266b89a7cc2SEnji Cooper // method. Assumes that 0 <= shard_index < total_shards.
26728f6c2f2SEnji Cooper GTEST_API_ bool ShouldRunTestOnShard(int total_shards, int shard_index,
26828f6c2f2SEnji Cooper                                      int test_id);
269b89a7cc2SEnji Cooper 
270b89a7cc2SEnji Cooper // STL container utilities.
271b89a7cc2SEnji Cooper 
272b89a7cc2SEnji Cooper // Returns the number of elements in the given container that satisfy
273b89a7cc2SEnji Cooper // the given predicate.
274b89a7cc2SEnji Cooper template <class Container, typename Predicate>
CountIf(const Container & c,Predicate predicate)275b89a7cc2SEnji Cooper inline int CountIf(const Container& c, Predicate predicate) {
276b89a7cc2SEnji Cooper   // Implemented as an explicit loop since std::count_if() in libCstd on
277b89a7cc2SEnji Cooper   // Solaris has a non-standard signature.
278b89a7cc2SEnji Cooper   int count = 0;
27928f6c2f2SEnji Cooper   for (auto it = c.begin(); it != c.end(); ++it) {
28028f6c2f2SEnji Cooper     if (predicate(*it)) ++count;
281b89a7cc2SEnji Cooper   }
282b89a7cc2SEnji Cooper   return count;
283b89a7cc2SEnji Cooper }
284b89a7cc2SEnji Cooper 
285b89a7cc2SEnji Cooper // Applies a function/functor to each element in the container.
286b89a7cc2SEnji Cooper template <class Container, typename Functor>
ForEach(const Container & c,Functor functor)287b89a7cc2SEnji Cooper void ForEach(const Container& c, Functor functor) {
288b89a7cc2SEnji Cooper   std::for_each(c.begin(), c.end(), functor);
289b89a7cc2SEnji Cooper }
290b89a7cc2SEnji Cooper 
291b89a7cc2SEnji Cooper // Returns the i-th element of the vector, or default_value if i is not
292b89a7cc2SEnji Cooper // in range [0, v.size()).
293b89a7cc2SEnji Cooper template <typename E>
GetElementOr(const std::vector<E> & v,int i,E default_value)294b89a7cc2SEnji Cooper inline E GetElementOr(const std::vector<E>& v, int i, E default_value) {
29528f6c2f2SEnji Cooper   return (i < 0 || i >= static_cast<int>(v.size())) ? default_value
29628f6c2f2SEnji Cooper                                                     : v[static_cast<size_t>(i)];
297b89a7cc2SEnji Cooper }
298b89a7cc2SEnji Cooper 
299b89a7cc2SEnji Cooper // Performs an in-place shuffle of a range of the vector's elements.
300b89a7cc2SEnji Cooper // 'begin' and 'end' are element indices as an STL-style range;
301b89a7cc2SEnji Cooper // i.e. [begin, end) are shuffled, where 'end' == size() means to
302b89a7cc2SEnji Cooper // shuffle to the end of the vector.
303b89a7cc2SEnji Cooper template <typename E>
ShuffleRange(internal::Random * random,int begin,int end,std::vector<E> * v)304b89a7cc2SEnji Cooper void ShuffleRange(internal::Random* random, int begin, int end,
305b89a7cc2SEnji Cooper                   std::vector<E>* v) {
306b89a7cc2SEnji Cooper   const int size = static_cast<int>(v->size());
307b89a7cc2SEnji Cooper   GTEST_CHECK_(0 <= begin && begin <= size)
308b89a7cc2SEnji Cooper       << "Invalid shuffle range start " << begin << ": must be in range [0, "
309b89a7cc2SEnji Cooper       << size << "].";
310b89a7cc2SEnji Cooper   GTEST_CHECK_(begin <= end && end <= size)
311b89a7cc2SEnji Cooper       << "Invalid shuffle range finish " << end << ": must be in range ["
312b89a7cc2SEnji Cooper       << begin << ", " << size << "].";
313b89a7cc2SEnji Cooper 
314b89a7cc2SEnji Cooper   // Fisher-Yates shuffle, from
315b89a7cc2SEnji Cooper   // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
316b89a7cc2SEnji Cooper   for (int range_width = end - begin; range_width >= 2; range_width--) {
317b89a7cc2SEnji Cooper     const int last_in_range = begin + range_width - 1;
31828f6c2f2SEnji Cooper     const int selected =
31928f6c2f2SEnji Cooper         begin +
32028f6c2f2SEnji Cooper         static_cast<int>(random->Generate(static_cast<uint32_t>(range_width)));
32128f6c2f2SEnji Cooper     std::swap((*v)[static_cast<size_t>(selected)],
32228f6c2f2SEnji Cooper               (*v)[static_cast<size_t>(last_in_range)]);
323b89a7cc2SEnji Cooper   }
324b89a7cc2SEnji Cooper }
325b89a7cc2SEnji Cooper 
326b89a7cc2SEnji Cooper // Performs an in-place shuffle of the vector's elements.
327b89a7cc2SEnji Cooper template <typename E>
Shuffle(internal::Random * random,std::vector<E> * v)328b89a7cc2SEnji Cooper inline void Shuffle(internal::Random* random, std::vector<E>* v) {
329b89a7cc2SEnji Cooper   ShuffleRange(random, 0, static_cast<int>(v->size()), v);
330b89a7cc2SEnji Cooper }
331b89a7cc2SEnji Cooper 
332b89a7cc2SEnji Cooper // A function for deleting an object.  Handy for being used as a
333b89a7cc2SEnji Cooper // functor.
334b89a7cc2SEnji Cooper template <typename T>
Delete(T * x)335b89a7cc2SEnji Cooper static void Delete(T* x) {
336b89a7cc2SEnji Cooper   delete x;
337b89a7cc2SEnji Cooper }
338b89a7cc2SEnji Cooper 
339b89a7cc2SEnji Cooper // A predicate that checks the key of a TestProperty against a known key.
340b89a7cc2SEnji Cooper //
341b89a7cc2SEnji Cooper // TestPropertyKeyIs is copyable.
342b89a7cc2SEnji Cooper class TestPropertyKeyIs {
343b89a7cc2SEnji Cooper  public:
344b89a7cc2SEnji Cooper   // Constructor.
345b89a7cc2SEnji Cooper   //
346b89a7cc2SEnji Cooper   // TestPropertyKeyIs has NO default constructor.
TestPropertyKeyIs(const std::string & key)347b89a7cc2SEnji Cooper   explicit TestPropertyKeyIs(const std::string& key) : key_(key) {}
348b89a7cc2SEnji Cooper 
34928f6c2f2SEnji Cooper   // Returns true if and only if the test name of test property matches on key_.
operator()350b89a7cc2SEnji Cooper   bool operator()(const TestProperty& test_property) const {
351b89a7cc2SEnji Cooper     return test_property.key() == key_;
352b89a7cc2SEnji Cooper   }
353b89a7cc2SEnji Cooper 
354b89a7cc2SEnji Cooper  private:
355b89a7cc2SEnji Cooper   std::string key_;
356b89a7cc2SEnji Cooper };
357b89a7cc2SEnji Cooper 
358b89a7cc2SEnji Cooper // Class UnitTestOptions.
359b89a7cc2SEnji Cooper //
360b89a7cc2SEnji Cooper // This class contains functions for processing options the user
361b89a7cc2SEnji Cooper // specifies when running the tests.  It has only static members.
362b89a7cc2SEnji Cooper //
363b89a7cc2SEnji Cooper // In most cases, the user can specify an option using either an
364b89a7cc2SEnji Cooper // environment variable or a command line flag.  E.g. you can set the
365b89a7cc2SEnji Cooper // test filter using either GTEST_FILTER or --gtest_filter.  If both
366b89a7cc2SEnji Cooper // the variable and the flag are present, the latter overrides the
367b89a7cc2SEnji Cooper // former.
368b89a7cc2SEnji Cooper class GTEST_API_ UnitTestOptions {
369b89a7cc2SEnji Cooper  public:
370b89a7cc2SEnji Cooper   // Functions for processing the gtest_output flag.
371b89a7cc2SEnji Cooper 
372b89a7cc2SEnji Cooper   // Returns the output format, or "" for normal printed output.
373b89a7cc2SEnji Cooper   static std::string GetOutputFormat();
374b89a7cc2SEnji Cooper 
375b89a7cc2SEnji Cooper   // Returns the absolute path of the requested output file, or the
376b89a7cc2SEnji Cooper   // default (test_detail.xml in the original working directory) if
377b89a7cc2SEnji Cooper   // none was explicitly specified.
378b89a7cc2SEnji Cooper   static std::string GetAbsolutePathToOutputFile();
379b89a7cc2SEnji Cooper 
380b89a7cc2SEnji Cooper   // Functions for processing the gtest_filter flag.
381b89a7cc2SEnji Cooper 
38228f6c2f2SEnji Cooper   // Returns true if and only if the user-specified filter matches the test
38328f6c2f2SEnji Cooper   // suite name and the test name.
38428f6c2f2SEnji Cooper   static bool FilterMatchesTest(const std::string& test_suite_name,
385b89a7cc2SEnji Cooper                                 const std::string& test_name);
386b89a7cc2SEnji Cooper 
38728f6c2f2SEnji Cooper #ifdef GTEST_OS_WINDOWS
388b89a7cc2SEnji Cooper   // Function for supporting the gtest_catch_exception flag.
389b89a7cc2SEnji Cooper 
39028f6c2f2SEnji Cooper   // Returns EXCEPTION_EXECUTE_HANDLER if given SEH exception was handled, or
39128f6c2f2SEnji Cooper   // EXCEPTION_CONTINUE_SEARCH otherwise.
392b89a7cc2SEnji Cooper   // This function is useful as an __except condition.
39328f6c2f2SEnji Cooper   static int GTestProcessSEH(DWORD seh_code, const char* location);
394b89a7cc2SEnji Cooper #endif  // GTEST_OS_WINDOWS
395b89a7cc2SEnji Cooper 
396b89a7cc2SEnji Cooper   // Returns true if "name" matches the ':' separated list of glob-style
397b89a7cc2SEnji Cooper   // filters in "filter".
398b89a7cc2SEnji Cooper   static bool MatchesFilter(const std::string& name, const char* filter);
399b89a7cc2SEnji Cooper };
400b89a7cc2SEnji Cooper 
40128f6c2f2SEnji Cooper #if GTEST_HAS_FILE_SYSTEM
402b89a7cc2SEnji Cooper // Returns the current application's name, removing directory path if that
403b89a7cc2SEnji Cooper // is present.  Used by UnitTestOptions::GetOutputFile.
404b89a7cc2SEnji Cooper GTEST_API_ FilePath GetCurrentExecutableName();
40528f6c2f2SEnji Cooper #endif  // GTEST_HAS_FILE_SYSTEM
406b89a7cc2SEnji Cooper 
407b89a7cc2SEnji Cooper // The role interface for getting the OS stack trace as a string.
408b89a7cc2SEnji Cooper class OsStackTraceGetterInterface {
409b89a7cc2SEnji Cooper  public:
41028f6c2f2SEnji Cooper   OsStackTraceGetterInterface() = default;
41128f6c2f2SEnji Cooper   virtual ~OsStackTraceGetterInterface() = default;
412b89a7cc2SEnji Cooper 
413b89a7cc2SEnji Cooper   // Returns the current OS stack trace as an std::string.  Parameters:
414b89a7cc2SEnji Cooper   //
415b89a7cc2SEnji Cooper   //   max_depth  - the maximum number of stack frames to be included
416b89a7cc2SEnji Cooper   //                in the trace.
417b89a7cc2SEnji Cooper   //   skip_count - the number of top frames to be skipped; doesn't count
418b89a7cc2SEnji Cooper   //                against max_depth.
419b89a7cc2SEnji Cooper   virtual std::string CurrentStackTrace(int max_depth, int skip_count) = 0;
420b89a7cc2SEnji Cooper 
421b89a7cc2SEnji Cooper   // UponLeavingGTest() should be called immediately before Google Test calls
422b89a7cc2SEnji Cooper   // user code. It saves some information about the current stack that
423b89a7cc2SEnji Cooper   // CurrentStackTrace() will use to find and hide Google Test stack frames.
424b89a7cc2SEnji Cooper   virtual void UponLeavingGTest() = 0;
425b89a7cc2SEnji Cooper 
426b89a7cc2SEnji Cooper   // This string is inserted in place of stack frames that are part of
427b89a7cc2SEnji Cooper   // Google Test's implementation.
428b89a7cc2SEnji Cooper   static const char* const kElidedFramesMarker;
429b89a7cc2SEnji Cooper 
430b89a7cc2SEnji Cooper  private:
43128f6c2f2SEnji Cooper   OsStackTraceGetterInterface(const OsStackTraceGetterInterface&) = delete;
43228f6c2f2SEnji Cooper   OsStackTraceGetterInterface& operator=(const OsStackTraceGetterInterface&) =
43328f6c2f2SEnji Cooper       delete;
434b89a7cc2SEnji Cooper };
435b89a7cc2SEnji Cooper 
436b89a7cc2SEnji Cooper // A working implementation of the OsStackTraceGetterInterface interface.
437b89a7cc2SEnji Cooper class OsStackTraceGetter : public OsStackTraceGetterInterface {
438b89a7cc2SEnji Cooper  public:
43928f6c2f2SEnji Cooper   OsStackTraceGetter() = default;
440b89a7cc2SEnji Cooper 
44128f6c2f2SEnji Cooper   std::string CurrentStackTrace(int max_depth, int skip_count) override;
44228f6c2f2SEnji Cooper   void UponLeavingGTest() override;
443b89a7cc2SEnji Cooper 
444b89a7cc2SEnji Cooper  private:
44528f6c2f2SEnji Cooper #ifdef GTEST_HAS_ABSL
446b89a7cc2SEnji Cooper   Mutex mutex_;  // Protects all internal state.
447b89a7cc2SEnji Cooper 
448b89a7cc2SEnji Cooper   // We save the stack frame below the frame that calls user code.
449b89a7cc2SEnji Cooper   // We do this because the address of the frame immediately below
450b89a7cc2SEnji Cooper   // the user code changes between the call to UponLeavingGTest()
451b89a7cc2SEnji Cooper   // and any calls to the stack trace code from within the user code.
452b89a7cc2SEnji Cooper   void* caller_frame_ = nullptr;
453b89a7cc2SEnji Cooper #endif  // GTEST_HAS_ABSL
454b89a7cc2SEnji Cooper 
45528f6c2f2SEnji Cooper   OsStackTraceGetter(const OsStackTraceGetter&) = delete;
45628f6c2f2SEnji Cooper   OsStackTraceGetter& operator=(const OsStackTraceGetter&) = delete;
457b89a7cc2SEnji Cooper };
458b89a7cc2SEnji Cooper 
459b89a7cc2SEnji Cooper // Information about a Google Test trace point.
460b89a7cc2SEnji Cooper struct TraceInfo {
461b89a7cc2SEnji Cooper   const char* file;
462b89a7cc2SEnji Cooper   int line;
463b89a7cc2SEnji Cooper   std::string message;
464b89a7cc2SEnji Cooper };
465b89a7cc2SEnji Cooper 
466b89a7cc2SEnji Cooper // This is the default global test part result reporter used in UnitTestImpl.
467b89a7cc2SEnji Cooper // This class should only be used by UnitTestImpl.
468b89a7cc2SEnji Cooper class DefaultGlobalTestPartResultReporter
469b89a7cc2SEnji Cooper     : public TestPartResultReporterInterface {
470b89a7cc2SEnji Cooper  public:
471b89a7cc2SEnji Cooper   explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test);
472b89a7cc2SEnji Cooper   // Implements the TestPartResultReporterInterface. Reports the test part
473b89a7cc2SEnji Cooper   // result in the current test.
47428f6c2f2SEnji Cooper   void ReportTestPartResult(const TestPartResult& result) override;
475b89a7cc2SEnji Cooper 
476b89a7cc2SEnji Cooper  private:
477b89a7cc2SEnji Cooper   UnitTestImpl* const unit_test_;
478b89a7cc2SEnji Cooper 
47928f6c2f2SEnji Cooper   DefaultGlobalTestPartResultReporter(
48028f6c2f2SEnji Cooper       const DefaultGlobalTestPartResultReporter&) = delete;
48128f6c2f2SEnji Cooper   DefaultGlobalTestPartResultReporter& operator=(
48228f6c2f2SEnji Cooper       const DefaultGlobalTestPartResultReporter&) = delete;
483b89a7cc2SEnji Cooper };
484b89a7cc2SEnji Cooper 
485b89a7cc2SEnji Cooper // This is the default per thread test part result reporter used in
486b89a7cc2SEnji Cooper // UnitTestImpl. This class should only be used by UnitTestImpl.
487b89a7cc2SEnji Cooper class DefaultPerThreadTestPartResultReporter
488b89a7cc2SEnji Cooper     : public TestPartResultReporterInterface {
489b89a7cc2SEnji Cooper  public:
490b89a7cc2SEnji Cooper   explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test);
491b89a7cc2SEnji Cooper   // Implements the TestPartResultReporterInterface. The implementation just
492b89a7cc2SEnji Cooper   // delegates to the current global test part result reporter of *unit_test_.
49328f6c2f2SEnji Cooper   void ReportTestPartResult(const TestPartResult& result) override;
494b89a7cc2SEnji Cooper 
495b89a7cc2SEnji Cooper  private:
496b89a7cc2SEnji Cooper   UnitTestImpl* const unit_test_;
497b89a7cc2SEnji Cooper 
49828f6c2f2SEnji Cooper   DefaultPerThreadTestPartResultReporter(
49928f6c2f2SEnji Cooper       const DefaultPerThreadTestPartResultReporter&) = delete;
50028f6c2f2SEnji Cooper   DefaultPerThreadTestPartResultReporter& operator=(
50128f6c2f2SEnji Cooper       const DefaultPerThreadTestPartResultReporter&) = delete;
502b89a7cc2SEnji Cooper };
503b89a7cc2SEnji Cooper 
504b89a7cc2SEnji Cooper // The private implementation of the UnitTest class.  We don't protect
505b89a7cc2SEnji Cooper // the methods under a mutex, as this class is not accessible by a
506b89a7cc2SEnji Cooper // user and the UnitTest class that delegates work to this class does
507b89a7cc2SEnji Cooper // proper locking.
508b89a7cc2SEnji Cooper class GTEST_API_ UnitTestImpl {
509b89a7cc2SEnji Cooper  public:
510b89a7cc2SEnji Cooper   explicit UnitTestImpl(UnitTest* parent);
511b89a7cc2SEnji Cooper   virtual ~UnitTestImpl();
512b89a7cc2SEnji Cooper 
513b89a7cc2SEnji Cooper   // There are two different ways to register your own TestPartResultReporter.
51428f6c2f2SEnji Cooper   // You can register your own reporter to listen either only for test results
515b89a7cc2SEnji Cooper   // from the current thread or for results from all threads.
51628f6c2f2SEnji Cooper   // By default, each per-thread test result reporter just passes a new
517b89a7cc2SEnji Cooper   // TestPartResult to the global test result reporter, which registers the
518b89a7cc2SEnji Cooper   // test part result for the currently running test.
519b89a7cc2SEnji Cooper 
520b89a7cc2SEnji Cooper   // Returns the global test part result reporter.
521b89a7cc2SEnji Cooper   TestPartResultReporterInterface* GetGlobalTestPartResultReporter();
522b89a7cc2SEnji Cooper 
523b89a7cc2SEnji Cooper   // Sets the global test part result reporter.
524b89a7cc2SEnji Cooper   void SetGlobalTestPartResultReporter(
525b89a7cc2SEnji Cooper       TestPartResultReporterInterface* reporter);
526b89a7cc2SEnji Cooper 
527b89a7cc2SEnji Cooper   // Returns the test part result reporter for the current thread.
528b89a7cc2SEnji Cooper   TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread();
529b89a7cc2SEnji Cooper 
530b89a7cc2SEnji Cooper   // Sets the test part result reporter for the current thread.
531b89a7cc2SEnji Cooper   void SetTestPartResultReporterForCurrentThread(
532b89a7cc2SEnji Cooper       TestPartResultReporterInterface* reporter);
533b89a7cc2SEnji Cooper 
53428f6c2f2SEnji Cooper   // Gets the number of successful test suites.
53528f6c2f2SEnji Cooper   int successful_test_suite_count() const;
536b89a7cc2SEnji Cooper 
53728f6c2f2SEnji Cooper   // Gets the number of failed test suites.
53828f6c2f2SEnji Cooper   int failed_test_suite_count() const;
539b89a7cc2SEnji Cooper 
54028f6c2f2SEnji Cooper   // Gets the number of all test suites.
54128f6c2f2SEnji Cooper   int total_test_suite_count() const;
542b89a7cc2SEnji Cooper 
54328f6c2f2SEnji Cooper   // Gets the number of all test suites that contain at least one test
544b89a7cc2SEnji Cooper   // that should run.
54528f6c2f2SEnji Cooper   int test_suite_to_run_count() const;
546b89a7cc2SEnji Cooper 
547b89a7cc2SEnji Cooper   // Gets the number of successful tests.
548b89a7cc2SEnji Cooper   int successful_test_count() const;
549b89a7cc2SEnji Cooper 
550da1a9eb0SAlan Somers   // Gets the number of skipped tests.
551da1a9eb0SAlan Somers   int skipped_test_count() const;
552da1a9eb0SAlan Somers 
553b89a7cc2SEnji Cooper   // Gets the number of failed tests.
554b89a7cc2SEnji Cooper   int failed_test_count() const;
555b89a7cc2SEnji Cooper 
556b89a7cc2SEnji Cooper   // Gets the number of disabled tests that will be reported in the XML report.
557b89a7cc2SEnji Cooper   int reportable_disabled_test_count() const;
558b89a7cc2SEnji Cooper 
559b89a7cc2SEnji Cooper   // Gets the number of disabled tests.
560b89a7cc2SEnji Cooper   int disabled_test_count() const;
561b89a7cc2SEnji Cooper 
562b89a7cc2SEnji Cooper   // Gets the number of tests to be printed in the XML report.
563b89a7cc2SEnji Cooper   int reportable_test_count() const;
564b89a7cc2SEnji Cooper 
565b89a7cc2SEnji Cooper   // Gets the number of all tests.
566b89a7cc2SEnji Cooper   int total_test_count() const;
567b89a7cc2SEnji Cooper 
568b89a7cc2SEnji Cooper   // Gets the number of tests that should run.
569b89a7cc2SEnji Cooper   int test_to_run_count() const;
570b89a7cc2SEnji Cooper 
571b89a7cc2SEnji Cooper   // Gets the time of the test program start, in ms from the start of the
572b89a7cc2SEnji Cooper   // UNIX epoch.
start_timestamp()573b89a7cc2SEnji Cooper   TimeInMillis start_timestamp() const { return start_timestamp_; }
574b89a7cc2SEnji Cooper 
575b89a7cc2SEnji Cooper   // Gets the elapsed time, in milliseconds.
elapsed_time()576b89a7cc2SEnji Cooper   TimeInMillis elapsed_time() const { return elapsed_time_; }
577b89a7cc2SEnji Cooper 
57828f6c2f2SEnji Cooper   // Returns true if and only if the unit test passed (i.e. all test suites
57928f6c2f2SEnji Cooper   // passed).
Passed()580b89a7cc2SEnji Cooper   bool Passed() const { return !Failed(); }
581b89a7cc2SEnji Cooper 
58228f6c2f2SEnji Cooper   // Returns true if and only if the unit test failed (i.e. some test suite
58328f6c2f2SEnji Cooper   // failed or something outside of all tests failed).
Failed()584b89a7cc2SEnji Cooper   bool Failed() const {
58528f6c2f2SEnji Cooper     return failed_test_suite_count() > 0 || ad_hoc_test_result()->Failed();
586b89a7cc2SEnji Cooper   }
587b89a7cc2SEnji Cooper 
58828f6c2f2SEnji Cooper   // Gets the i-th test suite among all the test suites. i can range from 0 to
58928f6c2f2SEnji Cooper   // total_test_suite_count() - 1. If i is not in that range, returns NULL.
GetTestSuite(int i)59028f6c2f2SEnji Cooper   const TestSuite* GetTestSuite(int i) const {
59128f6c2f2SEnji Cooper     const int index = GetElementOr(test_suite_indices_, i, -1);
59228f6c2f2SEnji Cooper     return index < 0 ? nullptr : test_suites_[static_cast<size_t>(i)];
593b89a7cc2SEnji Cooper   }
594b89a7cc2SEnji Cooper 
59528f6c2f2SEnji Cooper   //  Legacy API is deprecated but still available
59628f6c2f2SEnji Cooper #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
GetTestCase(int i)59728f6c2f2SEnji Cooper   const TestCase* GetTestCase(int i) const { return GetTestSuite(i); }
59828f6c2f2SEnji Cooper #endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI_
59928f6c2f2SEnji Cooper 
60028f6c2f2SEnji Cooper   // Gets the i-th test suite among all the test suites. i can range from 0 to
60128f6c2f2SEnji Cooper   // total_test_suite_count() - 1. If i is not in that range, returns NULL.
GetMutableSuiteCase(int i)60228f6c2f2SEnji Cooper   TestSuite* GetMutableSuiteCase(int i) {
60328f6c2f2SEnji Cooper     const int index = GetElementOr(test_suite_indices_, i, -1);
60428f6c2f2SEnji Cooper     return index < 0 ? nullptr : test_suites_[static_cast<size_t>(index)];
605b89a7cc2SEnji Cooper   }
606b89a7cc2SEnji Cooper 
607b89a7cc2SEnji Cooper   // Provides access to the event listener list.
listeners()608b89a7cc2SEnji Cooper   TestEventListeners* listeners() { return &listeners_; }
609b89a7cc2SEnji Cooper 
610b89a7cc2SEnji Cooper   // Returns the TestResult for the test that's currently running, or
611b89a7cc2SEnji Cooper   // the TestResult for the ad hoc test if no test is running.
612b89a7cc2SEnji Cooper   TestResult* current_test_result();
613b89a7cc2SEnji Cooper 
614b89a7cc2SEnji Cooper   // Returns the TestResult for the ad hoc test.
ad_hoc_test_result()615b89a7cc2SEnji Cooper   const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; }
616b89a7cc2SEnji Cooper 
617b89a7cc2SEnji Cooper   // Sets the OS stack trace getter.
618b89a7cc2SEnji Cooper   //
619b89a7cc2SEnji Cooper   // Does nothing if the input and the current OS stack trace getter
620b89a7cc2SEnji Cooper   // are the same; otherwise, deletes the old getter and makes the
621b89a7cc2SEnji Cooper   // input the current getter.
622b89a7cc2SEnji Cooper   void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter);
623b89a7cc2SEnji Cooper 
624b89a7cc2SEnji Cooper   // Returns the current OS stack trace getter if it is not NULL;
625b89a7cc2SEnji Cooper   // otherwise, creates an OsStackTraceGetter, makes it the current
626b89a7cc2SEnji Cooper   // getter, and returns it.
627b89a7cc2SEnji Cooper   OsStackTraceGetterInterface* os_stack_trace_getter();
628b89a7cc2SEnji Cooper 
629b89a7cc2SEnji Cooper   // Returns the current OS stack trace as an std::string.
630b89a7cc2SEnji Cooper   //
631b89a7cc2SEnji Cooper   // The maximum number of stack frames to be included is specified by
632b89a7cc2SEnji Cooper   // the gtest_stack_trace_depth flag.  The skip_count parameter
633b89a7cc2SEnji Cooper   // specifies the number of top frames to be skipped, which doesn't
634b89a7cc2SEnji Cooper   // count against the number of frames to be included.
635b89a7cc2SEnji Cooper   //
636b89a7cc2SEnji Cooper   // For example, if Foo() calls Bar(), which in turn calls
637b89a7cc2SEnji Cooper   // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
638b89a7cc2SEnji Cooper   // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
63928f6c2f2SEnji Cooper   std::string CurrentOsStackTraceExceptTop(int skip_count)
64028f6c2f2SEnji Cooper       GTEST_NO_INLINE_ GTEST_NO_TAIL_CALL_;
641b89a7cc2SEnji Cooper 
64228f6c2f2SEnji Cooper   // Finds and returns a TestSuite with the given name.  If one doesn't
643b89a7cc2SEnji Cooper   // exist, creates one and returns it.
644b89a7cc2SEnji Cooper   //
645b89a7cc2SEnji Cooper   // Arguments:
646b89a7cc2SEnji Cooper   //
64728f6c2f2SEnji Cooper   //   test_suite_name: name of the test suite
648b89a7cc2SEnji Cooper   //   type_param:      the name of the test's type parameter, or NULL if
649b89a7cc2SEnji Cooper   //                    this is not a typed or a type-parameterized test.
65028f6c2f2SEnji Cooper   //   set_up_tc:       pointer to the function that sets up the test suite
65128f6c2f2SEnji Cooper   //   tear_down_tc:    pointer to the function that tears down the test suite
65228f6c2f2SEnji Cooper   TestSuite* GetTestSuite(const char* test_suite_name, const char* type_param,
65328f6c2f2SEnji Cooper                           internal::SetUpTestSuiteFunc set_up_tc,
65428f6c2f2SEnji Cooper                           internal::TearDownTestSuiteFunc tear_down_tc);
65528f6c2f2SEnji Cooper 
65628f6c2f2SEnji Cooper //  Legacy API is deprecated but still available
65728f6c2f2SEnji Cooper #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
GetTestCase(const char * test_case_name,const char * type_param,internal::SetUpTestSuiteFunc set_up_tc,internal::TearDownTestSuiteFunc tear_down_tc)65828f6c2f2SEnji Cooper   TestCase* GetTestCase(const char* test_case_name, const char* type_param,
65928f6c2f2SEnji Cooper                         internal::SetUpTestSuiteFunc set_up_tc,
66028f6c2f2SEnji Cooper                         internal::TearDownTestSuiteFunc tear_down_tc) {
66128f6c2f2SEnji Cooper     return GetTestSuite(test_case_name, type_param, set_up_tc, tear_down_tc);
66228f6c2f2SEnji Cooper   }
66328f6c2f2SEnji Cooper #endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI_
664b89a7cc2SEnji Cooper 
665b89a7cc2SEnji Cooper   // Adds a TestInfo to the unit test.
666b89a7cc2SEnji Cooper   //
667b89a7cc2SEnji Cooper   // Arguments:
668b89a7cc2SEnji Cooper   //
66928f6c2f2SEnji Cooper   //   set_up_tc:    pointer to the function that sets up the test suite
67028f6c2f2SEnji Cooper   //   tear_down_tc: pointer to the function that tears down the test suite
671b89a7cc2SEnji Cooper   //   test_info:    the TestInfo object
AddTestInfo(internal::SetUpTestSuiteFunc set_up_tc,internal::TearDownTestSuiteFunc tear_down_tc,TestInfo * test_info)67228f6c2f2SEnji Cooper   void AddTestInfo(internal::SetUpTestSuiteFunc set_up_tc,
67328f6c2f2SEnji Cooper                    internal::TearDownTestSuiteFunc tear_down_tc,
674b89a7cc2SEnji Cooper                    TestInfo* test_info) {
67528f6c2f2SEnji Cooper #if GTEST_HAS_FILE_SYSTEM
676b89a7cc2SEnji Cooper     // In order to support thread-safe death tests, we need to
677b89a7cc2SEnji Cooper     // remember the original working directory when the test program
678b89a7cc2SEnji Cooper     // was first invoked.  We cannot do this in RUN_ALL_TESTS(), as
679b89a7cc2SEnji Cooper     // the user may have changed the current directory before calling
680b89a7cc2SEnji Cooper     // RUN_ALL_TESTS().  Therefore we capture the current directory in
681b89a7cc2SEnji Cooper     // AddTestInfo(), which is called to register a TEST or TEST_F
682b89a7cc2SEnji Cooper     // before main() is reached.
683b89a7cc2SEnji Cooper     if (original_working_dir_.IsEmpty()) {
684b89a7cc2SEnji Cooper       original_working_dir_.Set(FilePath::GetCurrentDir());
685b89a7cc2SEnji Cooper       GTEST_CHECK_(!original_working_dir_.IsEmpty())
686b89a7cc2SEnji Cooper           << "Failed to get the current working directory.";
687b89a7cc2SEnji Cooper     }
68828f6c2f2SEnji Cooper #endif  // GTEST_HAS_FILE_SYSTEM
689b89a7cc2SEnji Cooper 
69028f6c2f2SEnji Cooper     GetTestSuite(test_info->test_suite_name(), test_info->type_param(),
69128f6c2f2SEnji Cooper                  set_up_tc, tear_down_tc)
69228f6c2f2SEnji Cooper         ->AddTestInfo(test_info);
693b89a7cc2SEnji Cooper   }
694b89a7cc2SEnji Cooper 
69528f6c2f2SEnji Cooper   // Returns ParameterizedTestSuiteRegistry object used to keep track of
696b89a7cc2SEnji Cooper   // value-parameterized tests and instantiate and register them.
parameterized_test_registry()69728f6c2f2SEnji Cooper   internal::ParameterizedTestSuiteRegistry& parameterized_test_registry() {
698b89a7cc2SEnji Cooper     return parameterized_test_registry_;
699b89a7cc2SEnji Cooper   }
700b89a7cc2SEnji Cooper 
ignored_parameterized_test_suites()70128f6c2f2SEnji Cooper   std::set<std::string>* ignored_parameterized_test_suites() {
70228f6c2f2SEnji Cooper     return &ignored_parameterized_test_suites_;
70328f6c2f2SEnji Cooper   }
70428f6c2f2SEnji Cooper 
70528f6c2f2SEnji Cooper   // Returns TypeParameterizedTestSuiteRegistry object used to keep track of
70628f6c2f2SEnji Cooper   // type-parameterized tests and instantiations of them.
70728f6c2f2SEnji Cooper   internal::TypeParameterizedTestSuiteRegistry&
type_parameterized_test_registry()70828f6c2f2SEnji Cooper   type_parameterized_test_registry() {
70928f6c2f2SEnji Cooper     return type_parameterized_test_registry_;
71028f6c2f2SEnji Cooper   }
71128f6c2f2SEnji Cooper 
71228f6c2f2SEnji Cooper   // Sets the TestSuite object for the test that's currently running.
set_current_test_suite(TestSuite * a_current_test_suite)71328f6c2f2SEnji Cooper   void set_current_test_suite(TestSuite* a_current_test_suite) {
71428f6c2f2SEnji Cooper     current_test_suite_ = a_current_test_suite;
715b89a7cc2SEnji Cooper   }
716b89a7cc2SEnji Cooper 
717b89a7cc2SEnji Cooper   // Sets the TestInfo object for the test that's currently running.  If
718b89a7cc2SEnji Cooper   // current_test_info is NULL, the assertion results will be stored in
719b89a7cc2SEnji Cooper   // ad_hoc_test_result_.
set_current_test_info(TestInfo * a_current_test_info)720b89a7cc2SEnji Cooper   void set_current_test_info(TestInfo* a_current_test_info) {
721b89a7cc2SEnji Cooper     current_test_info_ = a_current_test_info;
722b89a7cc2SEnji Cooper   }
723b89a7cc2SEnji Cooper 
724b89a7cc2SEnji Cooper   // Registers all parameterized tests defined using TEST_P and
72528f6c2f2SEnji Cooper   // INSTANTIATE_TEST_SUITE_P, creating regular tests for each test/parameter
726b89a7cc2SEnji Cooper   // combination. This method can be called more then once; it has guards
727b89a7cc2SEnji Cooper   // protecting from registering the tests more then once.  If
728b89a7cc2SEnji Cooper   // value-parameterized tests are disabled, RegisterParameterizedTests is
729b89a7cc2SEnji Cooper   // present but does nothing.
730b89a7cc2SEnji Cooper   void RegisterParameterizedTests();
731b89a7cc2SEnji Cooper 
732b89a7cc2SEnji Cooper   // Runs all tests in this UnitTest object, prints the result, and
733b89a7cc2SEnji Cooper   // returns true if all tests are successful.  If any exception is
734b89a7cc2SEnji Cooper   // thrown during a test, this test is considered to be failed, but
735b89a7cc2SEnji Cooper   // the rest of the tests will still be run.
736b89a7cc2SEnji Cooper   bool RunAllTests();
737b89a7cc2SEnji Cooper 
738b89a7cc2SEnji Cooper   // Clears the results of all tests, except the ad hoc tests.
ClearNonAdHocTestResult()739b89a7cc2SEnji Cooper   void ClearNonAdHocTestResult() {
74028f6c2f2SEnji Cooper     ForEach(test_suites_, TestSuite::ClearTestSuiteResult);
741b89a7cc2SEnji Cooper   }
742b89a7cc2SEnji Cooper 
743b89a7cc2SEnji Cooper   // Clears the results of ad-hoc test assertions.
ClearAdHocTestResult()74428f6c2f2SEnji Cooper   void ClearAdHocTestResult() { ad_hoc_test_result_.Clear(); }
745b89a7cc2SEnji Cooper 
746b89a7cc2SEnji Cooper   // Adds a TestProperty to the current TestResult object when invoked in a
74728f6c2f2SEnji Cooper   // context of a test or a test suite, or to the global property set. If the
748b89a7cc2SEnji Cooper   // result already contains a property with the same key, the value will be
749b89a7cc2SEnji Cooper   // updated.
750b89a7cc2SEnji Cooper   void RecordProperty(const TestProperty& test_property);
751b89a7cc2SEnji Cooper 
75228f6c2f2SEnji Cooper   enum ReactionToSharding { HONOR_SHARDING_PROTOCOL, IGNORE_SHARDING_PROTOCOL };
753b89a7cc2SEnji Cooper 
754b89a7cc2SEnji Cooper   // Matches the full name of each test against the user-specified
755b89a7cc2SEnji Cooper   // filter to decide whether the test should run, then records the
75628f6c2f2SEnji Cooper   // result in each TestSuite and TestInfo object.
757b89a7cc2SEnji Cooper   // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests
758b89a7cc2SEnji Cooper   // based on sharding variables in the environment.
759b89a7cc2SEnji Cooper   // Returns the number of tests that should run.
760b89a7cc2SEnji Cooper   int FilterTests(ReactionToSharding shard_tests);
761b89a7cc2SEnji Cooper 
762b89a7cc2SEnji Cooper   // Prints the names of the tests matching the user-specified filter flag.
763b89a7cc2SEnji Cooper   void ListTestsMatchingFilter();
764b89a7cc2SEnji Cooper 
current_test_suite()76528f6c2f2SEnji Cooper   const TestSuite* current_test_suite() const { return current_test_suite_; }
current_test_info()766b89a7cc2SEnji Cooper   TestInfo* current_test_info() { return current_test_info_; }
current_test_info()767b89a7cc2SEnji Cooper   const TestInfo* current_test_info() const { return current_test_info_; }
768b89a7cc2SEnji Cooper 
769b89a7cc2SEnji Cooper   // Returns the vector of environments that need to be set-up/torn-down
770b89a7cc2SEnji Cooper   // before/after the tests are run.
environments()771b89a7cc2SEnji Cooper   std::vector<Environment*>& environments() { return environments_; }
772b89a7cc2SEnji Cooper 
773b89a7cc2SEnji Cooper   // Getters for the per-thread Google Test trace stack.
gtest_trace_stack()774b89a7cc2SEnji Cooper   std::vector<TraceInfo>& gtest_trace_stack() {
775b89a7cc2SEnji Cooper     return *(gtest_trace_stack_.pointer());
776b89a7cc2SEnji Cooper   }
gtest_trace_stack()777b89a7cc2SEnji Cooper   const std::vector<TraceInfo>& gtest_trace_stack() const {
778b89a7cc2SEnji Cooper     return gtest_trace_stack_.get();
779b89a7cc2SEnji Cooper   }
780b89a7cc2SEnji Cooper 
78128f6c2f2SEnji Cooper #ifdef GTEST_HAS_DEATH_TEST
InitDeathTestSubprocessControlInfo()782b89a7cc2SEnji Cooper   void InitDeathTestSubprocessControlInfo() {
783b89a7cc2SEnji Cooper     internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());
784b89a7cc2SEnji Cooper   }
785b89a7cc2SEnji Cooper   // Returns a pointer to the parsed --gtest_internal_run_death_test
786b89a7cc2SEnji Cooper   // flag, or NULL if that flag was not specified.
787b89a7cc2SEnji Cooper   // This information is useful only in a death test child process.
788b89a7cc2SEnji Cooper   // Must not be called before a call to InitGoogleTest.
internal_run_death_test_flag()789b89a7cc2SEnji Cooper   const InternalRunDeathTestFlag* internal_run_death_test_flag() const {
790b89a7cc2SEnji Cooper     return internal_run_death_test_flag_.get();
791b89a7cc2SEnji Cooper   }
792b89a7cc2SEnji Cooper 
793b89a7cc2SEnji Cooper   // Returns a pointer to the current death test factory.
death_test_factory()794b89a7cc2SEnji Cooper   internal::DeathTestFactory* death_test_factory() {
795b89a7cc2SEnji Cooper     return death_test_factory_.get();
796b89a7cc2SEnji Cooper   }
797b89a7cc2SEnji Cooper 
798b89a7cc2SEnji Cooper   void SuppressTestEventsIfInSubprocess();
799b89a7cc2SEnji Cooper 
800b89a7cc2SEnji Cooper   friend class ReplaceDeathTestFactory;
801b89a7cc2SEnji Cooper #endif  // GTEST_HAS_DEATH_TEST
802b89a7cc2SEnji Cooper 
803b89a7cc2SEnji Cooper   // Initializes the event listener performing XML output as specified by
804b89a7cc2SEnji Cooper   // UnitTestOptions. Must not be called before InitGoogleTest.
805b89a7cc2SEnji Cooper   void ConfigureXmlOutput();
806b89a7cc2SEnji Cooper 
807b89a7cc2SEnji Cooper #if GTEST_CAN_STREAM_RESULTS_
808b89a7cc2SEnji Cooper   // Initializes the event listener for streaming test results to a socket.
809b89a7cc2SEnji Cooper   // Must not be called before InitGoogleTest.
810b89a7cc2SEnji Cooper   void ConfigureStreamingOutput();
811b89a7cc2SEnji Cooper #endif
812b89a7cc2SEnji Cooper 
813b89a7cc2SEnji Cooper   // Performs initialization dependent upon flag values obtained in
814b89a7cc2SEnji Cooper   // ParseGoogleTestFlagsOnly.  Is called from InitGoogleTest after the call to
815b89a7cc2SEnji Cooper   // ParseGoogleTestFlagsOnly.  In case a user neglects to call InitGoogleTest
816b89a7cc2SEnji Cooper   // this function is also called from RunAllTests.  Since this function can be
817b89a7cc2SEnji Cooper   // called more than once, it has to be idempotent.
818b89a7cc2SEnji Cooper   void PostFlagParsingInit();
819b89a7cc2SEnji Cooper 
820b89a7cc2SEnji Cooper   // Gets the random seed used at the start of the current test iteration.
random_seed()821b89a7cc2SEnji Cooper   int random_seed() const { return random_seed_; }
822b89a7cc2SEnji Cooper 
823b89a7cc2SEnji Cooper   // Gets the random number generator.
random()824b89a7cc2SEnji Cooper   internal::Random* random() { return &random_; }
825b89a7cc2SEnji Cooper 
82628f6c2f2SEnji Cooper   // Shuffles all test suites, and the tests within each test suite,
827b89a7cc2SEnji Cooper   // making sure that death tests are still run first.
828b89a7cc2SEnji Cooper   void ShuffleTests();
829b89a7cc2SEnji Cooper 
83028f6c2f2SEnji Cooper   // Restores the test suites and tests to their order before the first shuffle.
831b89a7cc2SEnji Cooper   void UnshuffleTests();
832b89a7cc2SEnji Cooper 
833b89a7cc2SEnji Cooper   // Returns the value of GTEST_FLAG(catch_exceptions) at the moment
834b89a7cc2SEnji Cooper   // UnitTest::Run() starts.
catch_exceptions()835b89a7cc2SEnji Cooper   bool catch_exceptions() const { return catch_exceptions_; }
836b89a7cc2SEnji Cooper 
837b89a7cc2SEnji Cooper  private:
838b89a7cc2SEnji Cooper   friend class ::testing::UnitTest;
839b89a7cc2SEnji Cooper 
840b89a7cc2SEnji Cooper   // Used by UnitTest::Run() to capture the state of
841b89a7cc2SEnji Cooper   // GTEST_FLAG(catch_exceptions) at the moment it starts.
set_catch_exceptions(bool value)842b89a7cc2SEnji Cooper   void set_catch_exceptions(bool value) { catch_exceptions_ = value; }
843b89a7cc2SEnji Cooper 
844b89a7cc2SEnji Cooper   // The UnitTest object that owns this implementation object.
845b89a7cc2SEnji Cooper   UnitTest* const parent_;
846b89a7cc2SEnji Cooper 
84728f6c2f2SEnji Cooper #if GTEST_HAS_FILE_SYSTEM
848b89a7cc2SEnji Cooper   // The working directory when the first TEST() or TEST_F() was
849b89a7cc2SEnji Cooper   // executed.
850b89a7cc2SEnji Cooper   internal::FilePath original_working_dir_;
85128f6c2f2SEnji Cooper #endif  // GTEST_HAS_FILE_SYSTEM
852b89a7cc2SEnji Cooper 
853b89a7cc2SEnji Cooper   // The default test part result reporters.
854b89a7cc2SEnji Cooper   DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_;
855b89a7cc2SEnji Cooper   DefaultPerThreadTestPartResultReporter
856b89a7cc2SEnji Cooper       default_per_thread_test_part_result_reporter_;
857b89a7cc2SEnji Cooper 
858b89a7cc2SEnji Cooper   // Points to (but doesn't own) the global test part result reporter.
85928f6c2f2SEnji Cooper   TestPartResultReporterInterface* global_test_part_result_reporter_;
860b89a7cc2SEnji Cooper 
861b89a7cc2SEnji Cooper   // Protects read and write access to global_test_part_result_reporter_.
862b89a7cc2SEnji Cooper   internal::Mutex global_test_part_result_reporter_mutex_;
863b89a7cc2SEnji Cooper 
864b89a7cc2SEnji Cooper   // Points to (but doesn't own) the per-thread test part result reporter.
865b89a7cc2SEnji Cooper   internal::ThreadLocal<TestPartResultReporterInterface*>
866b89a7cc2SEnji Cooper       per_thread_test_part_result_reporter_;
867b89a7cc2SEnji Cooper 
868b89a7cc2SEnji Cooper   // The vector of environments that need to be set-up/torn-down
869b89a7cc2SEnji Cooper   // before/after the tests are run.
870b89a7cc2SEnji Cooper   std::vector<Environment*> environments_;
871b89a7cc2SEnji Cooper 
87228f6c2f2SEnji Cooper   // The vector of TestSuites in their original order.  It owns the
873b89a7cc2SEnji Cooper   // elements in the vector.
87428f6c2f2SEnji Cooper   std::vector<TestSuite*> test_suites_;
875b89a7cc2SEnji Cooper 
87628f6c2f2SEnji Cooper   // Provides a level of indirection for the test suite list to allow
87728f6c2f2SEnji Cooper   // easy shuffling and restoring the test suite order.  The i-th
87828f6c2f2SEnji Cooper   // element of this vector is the index of the i-th test suite in the
879b89a7cc2SEnji Cooper   // shuffled order.
88028f6c2f2SEnji Cooper   std::vector<int> test_suite_indices_;
881b89a7cc2SEnji Cooper 
882b89a7cc2SEnji Cooper   // ParameterizedTestRegistry object used to register value-parameterized
883b89a7cc2SEnji Cooper   // tests.
88428f6c2f2SEnji Cooper   internal::ParameterizedTestSuiteRegistry parameterized_test_registry_;
88528f6c2f2SEnji Cooper   internal::TypeParameterizedTestSuiteRegistry
88628f6c2f2SEnji Cooper       type_parameterized_test_registry_;
88728f6c2f2SEnji Cooper 
88828f6c2f2SEnji Cooper   // The set holding the name of parameterized
88928f6c2f2SEnji Cooper   // test suites that may go uninstantiated.
89028f6c2f2SEnji Cooper   std::set<std::string> ignored_parameterized_test_suites_;
891b89a7cc2SEnji Cooper 
892b89a7cc2SEnji Cooper   // Indicates whether RegisterParameterizedTests() has been called already.
893b89a7cc2SEnji Cooper   bool parameterized_tests_registered_;
894b89a7cc2SEnji Cooper 
89528f6c2f2SEnji Cooper   // Index of the last death test suite registered.  Initially -1.
89628f6c2f2SEnji Cooper   int last_death_test_suite_;
897b89a7cc2SEnji Cooper 
89828f6c2f2SEnji Cooper   // This points to the TestSuite for the currently running test.  It
89928f6c2f2SEnji Cooper   // changes as Google Test goes through one test suite after another.
900b89a7cc2SEnji Cooper   // When no test is running, this is set to NULL and Google Test
901b89a7cc2SEnji Cooper   // stores assertion results in ad_hoc_test_result_.  Initially NULL.
90228f6c2f2SEnji Cooper   TestSuite* current_test_suite_;
903b89a7cc2SEnji Cooper 
904b89a7cc2SEnji Cooper   // This points to the TestInfo for the currently running test.  It
905b89a7cc2SEnji Cooper   // changes as Google Test goes through one test after another.  When
906b89a7cc2SEnji Cooper   // no test is running, this is set to NULL and Google Test stores
907b89a7cc2SEnji Cooper   // assertion results in ad_hoc_test_result_.  Initially NULL.
908b89a7cc2SEnji Cooper   TestInfo* current_test_info_;
909b89a7cc2SEnji Cooper 
910b89a7cc2SEnji Cooper   // Normally, a user only writes assertions inside a TEST or TEST_F,
911b89a7cc2SEnji Cooper   // or inside a function called by a TEST or TEST_F.  Since Google
912b89a7cc2SEnji Cooper   // Test keeps track of which test is current running, it can
913b89a7cc2SEnji Cooper   // associate such an assertion with the test it belongs to.
914b89a7cc2SEnji Cooper   //
915b89a7cc2SEnji Cooper   // If an assertion is encountered when no TEST or TEST_F is running,
916b89a7cc2SEnji Cooper   // Google Test attributes the assertion result to an imaginary "ad hoc"
917b89a7cc2SEnji Cooper   // test, and records the result in ad_hoc_test_result_.
918b89a7cc2SEnji Cooper   TestResult ad_hoc_test_result_;
919b89a7cc2SEnji Cooper 
920b89a7cc2SEnji Cooper   // The list of event listeners that can be used to track events inside
921b89a7cc2SEnji Cooper   // Google Test.
922b89a7cc2SEnji Cooper   TestEventListeners listeners_;
923b89a7cc2SEnji Cooper 
924b89a7cc2SEnji Cooper   // The OS stack trace getter.  Will be deleted when the UnitTest
925b89a7cc2SEnji Cooper   // object is destructed.  By default, an OsStackTraceGetter is used,
926b89a7cc2SEnji Cooper   // but the user can set this field to use a custom getter if that is
927b89a7cc2SEnji Cooper   // desired.
928b89a7cc2SEnji Cooper   OsStackTraceGetterInterface* os_stack_trace_getter_;
929b89a7cc2SEnji Cooper 
93028f6c2f2SEnji Cooper   // True if and only if PostFlagParsingInit() has been called.
931b89a7cc2SEnji Cooper   bool post_flag_parse_init_performed_;
932b89a7cc2SEnji Cooper 
933b89a7cc2SEnji Cooper   // The random number seed used at the beginning of the test run.
934b89a7cc2SEnji Cooper   int random_seed_;
935b89a7cc2SEnji Cooper 
936b89a7cc2SEnji Cooper   // Our random number generator.
937b89a7cc2SEnji Cooper   internal::Random random_;
938b89a7cc2SEnji Cooper 
939b89a7cc2SEnji Cooper   // The time of the test program start, in ms from the start of the
940b89a7cc2SEnji Cooper   // UNIX epoch.
941b89a7cc2SEnji Cooper   TimeInMillis start_timestamp_;
942b89a7cc2SEnji Cooper 
943b89a7cc2SEnji Cooper   // How long the test took to run, in milliseconds.
944b89a7cc2SEnji Cooper   TimeInMillis elapsed_time_;
945b89a7cc2SEnji Cooper 
94628f6c2f2SEnji Cooper #ifdef GTEST_HAS_DEATH_TEST
947b89a7cc2SEnji Cooper   // The decomposed components of the gtest_internal_run_death_test flag,
948b89a7cc2SEnji Cooper   // parsed when RUN_ALL_TESTS is called.
94928f6c2f2SEnji Cooper   std::unique_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;
95028f6c2f2SEnji Cooper   std::unique_ptr<internal::DeathTestFactory> death_test_factory_;
951b89a7cc2SEnji Cooper #endif  // GTEST_HAS_DEATH_TEST
952b89a7cc2SEnji Cooper 
953b89a7cc2SEnji Cooper   // A per-thread stack of traces created by the SCOPED_TRACE() macro.
954b89a7cc2SEnji Cooper   internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_;
955b89a7cc2SEnji Cooper 
956b89a7cc2SEnji Cooper   // The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests()
957b89a7cc2SEnji Cooper   // starts.
958b89a7cc2SEnji Cooper   bool catch_exceptions_;
959b89a7cc2SEnji Cooper 
96028f6c2f2SEnji Cooper   UnitTestImpl(const UnitTestImpl&) = delete;
96128f6c2f2SEnji Cooper   UnitTestImpl& operator=(const UnitTestImpl&) = delete;
962b89a7cc2SEnji Cooper };  // class UnitTestImpl
963b89a7cc2SEnji Cooper 
964b89a7cc2SEnji Cooper // Convenience function for accessing the global UnitTest
965b89a7cc2SEnji Cooper // implementation object.
GetUnitTestImpl()966b89a7cc2SEnji Cooper inline UnitTestImpl* GetUnitTestImpl() {
967b89a7cc2SEnji Cooper   return UnitTest::GetInstance()->impl();
968b89a7cc2SEnji Cooper }
969b89a7cc2SEnji Cooper 
97028f6c2f2SEnji Cooper #ifdef GTEST_USES_SIMPLE_RE
971b89a7cc2SEnji Cooper 
972b89a7cc2SEnji Cooper // Internal helper functions for implementing the simple regular
973b89a7cc2SEnji Cooper // expression matcher.
974b89a7cc2SEnji Cooper GTEST_API_ bool IsInSet(char ch, const char* str);
975b89a7cc2SEnji Cooper GTEST_API_ bool IsAsciiDigit(char ch);
976b89a7cc2SEnji Cooper GTEST_API_ bool IsAsciiPunct(char ch);
977b89a7cc2SEnji Cooper GTEST_API_ bool IsRepeat(char ch);
978b89a7cc2SEnji Cooper GTEST_API_ bool IsAsciiWhiteSpace(char ch);
979b89a7cc2SEnji Cooper GTEST_API_ bool IsAsciiWordChar(char ch);
980b89a7cc2SEnji Cooper GTEST_API_ bool IsValidEscape(char ch);
981b89a7cc2SEnji Cooper GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch);
982b89a7cc2SEnji Cooper GTEST_API_ bool ValidateRegex(const char* regex);
983b89a7cc2SEnji Cooper GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str);
98428f6c2f2SEnji Cooper GTEST_API_ bool MatchRepetitionAndRegexAtHead(bool escaped, char ch,
98528f6c2f2SEnji Cooper                                               char repeat, const char* regex,
98628f6c2f2SEnji Cooper                                               const char* str);
987b89a7cc2SEnji Cooper GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str);
988b89a7cc2SEnji Cooper 
989b89a7cc2SEnji Cooper #endif  // GTEST_USES_SIMPLE_RE
990b89a7cc2SEnji Cooper 
991b89a7cc2SEnji Cooper // Parses the command line for Google Test flags, without initializing
992b89a7cc2SEnji Cooper // other parts of Google Test.
993b89a7cc2SEnji Cooper GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv);
994b89a7cc2SEnji Cooper GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv);
995b89a7cc2SEnji Cooper 
99628f6c2f2SEnji Cooper #ifdef GTEST_HAS_DEATH_TEST
997b89a7cc2SEnji Cooper 
998b89a7cc2SEnji Cooper // Returns the message describing the last system error, regardless of the
999b89a7cc2SEnji Cooper // platform.
1000b89a7cc2SEnji Cooper GTEST_API_ std::string GetLastErrnoDescription();
1001b89a7cc2SEnji Cooper 
1002b89a7cc2SEnji Cooper // Attempts to parse a string into a positive integer pointed to by the
1003b89a7cc2SEnji Cooper // number parameter.  Returns true if that is possible.
1004b89a7cc2SEnji Cooper // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use
1005b89a7cc2SEnji Cooper // it here.
1006b89a7cc2SEnji Cooper template <typename Integer>
ParseNaturalNumber(const::std::string & str,Integer * number)1007b89a7cc2SEnji Cooper bool ParseNaturalNumber(const ::std::string& str, Integer* number) {
1008b89a7cc2SEnji Cooper   // Fail fast if the given string does not begin with a digit;
1009b89a7cc2SEnji Cooper   // this bypasses strtoXXX's "optional leading whitespace and plus
1010b89a7cc2SEnji Cooper   // or minus sign" semantics, which are undesirable here.
1011b89a7cc2SEnji Cooper   if (str.empty() || !IsDigit(str[0])) {
1012b89a7cc2SEnji Cooper     return false;
1013b89a7cc2SEnji Cooper   }
1014b89a7cc2SEnji Cooper   errno = 0;
1015b89a7cc2SEnji Cooper 
1016b89a7cc2SEnji Cooper   char* end;
1017b89a7cc2SEnji Cooper   // BiggestConvertible is the largest integer type that system-provided
1018b89a7cc2SEnji Cooper   // string-to-number conversion routines can return.
101928f6c2f2SEnji Cooper   using BiggestConvertible = unsigned long long;  // NOLINT
1020b89a7cc2SEnji Cooper 
102128f6c2f2SEnji Cooper   const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10);  // NOLINT
1022b89a7cc2SEnji Cooper   const bool parse_success = *end == '\0' && errno == 0;
1023b89a7cc2SEnji Cooper 
1024b89a7cc2SEnji Cooper   GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed));
1025b89a7cc2SEnji Cooper 
1026b89a7cc2SEnji Cooper   const Integer result = static_cast<Integer>(parsed);
1027b89a7cc2SEnji Cooper   if (parse_success && static_cast<BiggestConvertible>(result) == parsed) {
1028b89a7cc2SEnji Cooper     *number = result;
1029b89a7cc2SEnji Cooper     return true;
1030b89a7cc2SEnji Cooper   }
1031b89a7cc2SEnji Cooper   return false;
1032b89a7cc2SEnji Cooper }
1033b89a7cc2SEnji Cooper #endif  // GTEST_HAS_DEATH_TEST
1034b89a7cc2SEnji Cooper 
1035b89a7cc2SEnji Cooper // TestResult contains some private methods that should be hidden from
1036b89a7cc2SEnji Cooper // Google Test user but are required for testing. This class allow our tests
1037b89a7cc2SEnji Cooper // to access them.
1038b89a7cc2SEnji Cooper //
1039b89a7cc2SEnji Cooper // This class is supplied only for the purpose of testing Google Test's own
1040b89a7cc2SEnji Cooper // constructs. Do not use it in user tests, either directly or indirectly.
1041b89a7cc2SEnji Cooper class TestResultAccessor {
1042b89a7cc2SEnji Cooper  public:
RecordProperty(TestResult * test_result,const std::string & xml_element,const TestProperty & property)1043b89a7cc2SEnji Cooper   static void RecordProperty(TestResult* test_result,
1044b89a7cc2SEnji Cooper                              const std::string& xml_element,
1045b89a7cc2SEnji Cooper                              const TestProperty& property) {
1046b89a7cc2SEnji Cooper     test_result->RecordProperty(xml_element, property);
1047b89a7cc2SEnji Cooper   }
1048b89a7cc2SEnji Cooper 
ClearTestPartResults(TestResult * test_result)1049b89a7cc2SEnji Cooper   static void ClearTestPartResults(TestResult* test_result) {
1050b89a7cc2SEnji Cooper     test_result->ClearTestPartResults();
1051b89a7cc2SEnji Cooper   }
1052b89a7cc2SEnji Cooper 
test_part_results(const TestResult & test_result)1053b89a7cc2SEnji Cooper   static const std::vector<testing::TestPartResult>& test_part_results(
1054b89a7cc2SEnji Cooper       const TestResult& test_result) {
1055b89a7cc2SEnji Cooper     return test_result.test_part_results();
1056b89a7cc2SEnji Cooper   }
1057b89a7cc2SEnji Cooper };
1058b89a7cc2SEnji Cooper 
1059b89a7cc2SEnji Cooper #if GTEST_CAN_STREAM_RESULTS_
1060b89a7cc2SEnji Cooper 
1061b89a7cc2SEnji Cooper // Streams test results to the given port on the given host machine.
1062b89a7cc2SEnji Cooper class StreamingListener : public EmptyTestEventListener {
1063b89a7cc2SEnji Cooper  public:
1064b89a7cc2SEnji Cooper   // Abstract base class for writing strings to a socket.
1065b89a7cc2SEnji Cooper   class AbstractSocketWriter {
1066b89a7cc2SEnji Cooper    public:
106728f6c2f2SEnji Cooper     virtual ~AbstractSocketWriter() = default;
1068b89a7cc2SEnji Cooper 
1069b89a7cc2SEnji Cooper     // Sends a string to the socket.
1070b89a7cc2SEnji Cooper     virtual void Send(const std::string& message) = 0;
1071b89a7cc2SEnji Cooper 
1072b89a7cc2SEnji Cooper     // Closes the socket.
CloseConnection()1073b89a7cc2SEnji Cooper     virtual void CloseConnection() {}
1074b89a7cc2SEnji Cooper 
1075b89a7cc2SEnji Cooper     // Sends a string and a newline to the socket.
SendLn(const std::string & message)1076b89a7cc2SEnji Cooper     void SendLn(const std::string& message) { Send(message + "\n"); }
1077b89a7cc2SEnji Cooper   };
1078b89a7cc2SEnji Cooper 
1079b89a7cc2SEnji Cooper   // Concrete class for actually writing strings to a socket.
1080b89a7cc2SEnji Cooper   class SocketWriter : public AbstractSocketWriter {
1081b89a7cc2SEnji Cooper    public:
SocketWriter(const std::string & host,const std::string & port)1082b89a7cc2SEnji Cooper     SocketWriter(const std::string& host, const std::string& port)
1083b89a7cc2SEnji Cooper         : sockfd_(-1), host_name_(host), port_num_(port) {
1084b89a7cc2SEnji Cooper       MakeConnection();
1085b89a7cc2SEnji Cooper     }
1086b89a7cc2SEnji Cooper 
~SocketWriter()108728f6c2f2SEnji Cooper     ~SocketWriter() override {
108828f6c2f2SEnji Cooper       if (sockfd_ != -1) CloseConnection();
1089b89a7cc2SEnji Cooper     }
1090b89a7cc2SEnji Cooper 
1091b89a7cc2SEnji Cooper     // Sends a string to the socket.
Send(const std::string & message)109228f6c2f2SEnji Cooper     void Send(const std::string& message) override {
1093b89a7cc2SEnji Cooper       GTEST_CHECK_(sockfd_ != -1)
1094b89a7cc2SEnji Cooper           << "Send() can be called only when there is a connection.";
1095b89a7cc2SEnji Cooper 
109628f6c2f2SEnji Cooper       const auto len = static_cast<size_t>(message.length());
109728f6c2f2SEnji Cooper       if (write(sockfd_, message.c_str(), len) != static_cast<ssize_t>(len)) {
109828f6c2f2SEnji Cooper         GTEST_LOG_(WARNING) << "stream_result_to: failed to stream to "
1099b89a7cc2SEnji Cooper                             << host_name_ << ":" << port_num_;
1100b89a7cc2SEnji Cooper       }
1101b89a7cc2SEnji Cooper     }
1102b89a7cc2SEnji Cooper 
1103b89a7cc2SEnji Cooper    private:
1104b89a7cc2SEnji Cooper     // Creates a client socket and connects to the server.
1105b89a7cc2SEnji Cooper     void MakeConnection();
1106b89a7cc2SEnji Cooper 
1107b89a7cc2SEnji Cooper     // Closes the socket.
CloseConnection()110828f6c2f2SEnji Cooper     void CloseConnection() override {
1109b89a7cc2SEnji Cooper       GTEST_CHECK_(sockfd_ != -1)
1110b89a7cc2SEnji Cooper           << "CloseConnection() can be called only when there is a connection.";
1111b89a7cc2SEnji Cooper 
1112b89a7cc2SEnji Cooper       close(sockfd_);
1113b89a7cc2SEnji Cooper       sockfd_ = -1;
1114b89a7cc2SEnji Cooper     }
1115b89a7cc2SEnji Cooper 
1116b89a7cc2SEnji Cooper     int sockfd_;  // socket file descriptor
1117b89a7cc2SEnji Cooper     const std::string host_name_;
1118b89a7cc2SEnji Cooper     const std::string port_num_;
1119b89a7cc2SEnji Cooper 
112028f6c2f2SEnji Cooper     SocketWriter(const SocketWriter&) = delete;
112128f6c2f2SEnji Cooper     SocketWriter& operator=(const SocketWriter&) = delete;
1122b89a7cc2SEnji Cooper   };  // class SocketWriter
1123b89a7cc2SEnji Cooper 
1124b89a7cc2SEnji Cooper   // Escapes '=', '&', '%', and '\n' characters in str as "%xx".
1125b89a7cc2SEnji Cooper   static std::string UrlEncode(const char* str);
1126b89a7cc2SEnji Cooper 
StreamingListener(const std::string & host,const std::string & port)1127b89a7cc2SEnji Cooper   StreamingListener(const std::string& host, const std::string& port)
1128b89a7cc2SEnji Cooper       : socket_writer_(new SocketWriter(host, port)) {
1129b89a7cc2SEnji Cooper     Start();
1130b89a7cc2SEnji Cooper   }
1131b89a7cc2SEnji Cooper 
StreamingListener(AbstractSocketWriter * socket_writer)1132b89a7cc2SEnji Cooper   explicit StreamingListener(AbstractSocketWriter* socket_writer)
113328f6c2f2SEnji Cooper       : socket_writer_(socket_writer) {
113428f6c2f2SEnji Cooper     Start();
113528f6c2f2SEnji Cooper   }
1136b89a7cc2SEnji Cooper 
OnTestProgramStart(const UnitTest &)113728f6c2f2SEnji Cooper   void OnTestProgramStart(const UnitTest& /* unit_test */) override {
1138b89a7cc2SEnji Cooper     SendLn("event=TestProgramStart");
1139b89a7cc2SEnji Cooper   }
1140b89a7cc2SEnji Cooper 
OnTestProgramEnd(const UnitTest & unit_test)114128f6c2f2SEnji Cooper   void OnTestProgramEnd(const UnitTest& unit_test) override {
1142b89a7cc2SEnji Cooper     // Note that Google Test current only report elapsed time for each
1143b89a7cc2SEnji Cooper     // test iteration, not for the entire test program.
1144b89a7cc2SEnji Cooper     SendLn("event=TestProgramEnd&passed=" + FormatBool(unit_test.Passed()));
1145b89a7cc2SEnji Cooper 
1146b89a7cc2SEnji Cooper     // Notify the streaming server to stop.
1147b89a7cc2SEnji Cooper     socket_writer_->CloseConnection();
1148b89a7cc2SEnji Cooper   }
1149b89a7cc2SEnji Cooper 
OnTestIterationStart(const UnitTest &,int iteration)115028f6c2f2SEnji Cooper   void OnTestIterationStart(const UnitTest& /* unit_test */,
115128f6c2f2SEnji Cooper                             int iteration) override {
1152b89a7cc2SEnji Cooper     SendLn("event=TestIterationStart&iteration=" +
1153b89a7cc2SEnji Cooper            StreamableToString(iteration));
1154b89a7cc2SEnji Cooper   }
1155b89a7cc2SEnji Cooper 
OnTestIterationEnd(const UnitTest & unit_test,int)115628f6c2f2SEnji Cooper   void OnTestIterationEnd(const UnitTest& unit_test,
115728f6c2f2SEnji Cooper                           int /* iteration */) override {
115828f6c2f2SEnji Cooper     SendLn("event=TestIterationEnd&passed=" + FormatBool(unit_test.Passed()) +
115928f6c2f2SEnji Cooper            "&elapsed_time=" + StreamableToString(unit_test.elapsed_time()) +
116028f6c2f2SEnji Cooper            "ms");
1161b89a7cc2SEnji Cooper   }
1162b89a7cc2SEnji Cooper 
116328f6c2f2SEnji Cooper   // Note that "event=TestCaseStart" is a wire format and has to remain
116428f6c2f2SEnji Cooper   // "case" for compatibility
OnTestSuiteStart(const TestSuite & test_suite)116528f6c2f2SEnji Cooper   void OnTestSuiteStart(const TestSuite& test_suite) override {
116628f6c2f2SEnji Cooper     SendLn(std::string("event=TestCaseStart&name=") + test_suite.name());
1167b89a7cc2SEnji Cooper   }
1168b89a7cc2SEnji Cooper 
116928f6c2f2SEnji Cooper   // Note that "event=TestCaseEnd" is a wire format and has to remain
117028f6c2f2SEnji Cooper   // "case" for compatibility
OnTestSuiteEnd(const TestSuite & test_suite)117128f6c2f2SEnji Cooper   void OnTestSuiteEnd(const TestSuite& test_suite) override {
117228f6c2f2SEnji Cooper     SendLn("event=TestCaseEnd&passed=" + FormatBool(test_suite.Passed()) +
117328f6c2f2SEnji Cooper            "&elapsed_time=" + StreamableToString(test_suite.elapsed_time()) +
117428f6c2f2SEnji Cooper            "ms");
1175b89a7cc2SEnji Cooper   }
1176b89a7cc2SEnji Cooper 
OnTestStart(const TestInfo & test_info)117728f6c2f2SEnji Cooper   void OnTestStart(const TestInfo& test_info) override {
1178b89a7cc2SEnji Cooper     SendLn(std::string("event=TestStart&name=") + test_info.name());
1179b89a7cc2SEnji Cooper   }
1180b89a7cc2SEnji Cooper 
OnTestEnd(const TestInfo & test_info)118128f6c2f2SEnji Cooper   void OnTestEnd(const TestInfo& test_info) override {
1182b89a7cc2SEnji Cooper     SendLn("event=TestEnd&passed=" +
118328f6c2f2SEnji Cooper            FormatBool((test_info.result())->Passed()) + "&elapsed_time=" +
1184b89a7cc2SEnji Cooper            StreamableToString((test_info.result())->elapsed_time()) + "ms");
1185b89a7cc2SEnji Cooper   }
1186b89a7cc2SEnji Cooper 
OnTestPartResult(const TestPartResult & test_part_result)118728f6c2f2SEnji Cooper   void OnTestPartResult(const TestPartResult& test_part_result) override {
1188b89a7cc2SEnji Cooper     const char* file_name = test_part_result.file_name();
118928f6c2f2SEnji Cooper     if (file_name == nullptr) file_name = "";
1190b89a7cc2SEnji Cooper     SendLn("event=TestPartResult&file=" + UrlEncode(file_name) +
1191b89a7cc2SEnji Cooper            "&line=" + StreamableToString(test_part_result.line_number()) +
1192b89a7cc2SEnji Cooper            "&message=" + UrlEncode(test_part_result.message()));
1193b89a7cc2SEnji Cooper   }
1194b89a7cc2SEnji Cooper 
1195b89a7cc2SEnji Cooper  private:
1196b89a7cc2SEnji Cooper   // Sends the given message and a newline to the socket.
SendLn(const std::string & message)1197b89a7cc2SEnji Cooper   void SendLn(const std::string& message) { socket_writer_->SendLn(message); }
1198b89a7cc2SEnji Cooper 
1199b89a7cc2SEnji Cooper   // Called at the start of streaming to notify the receiver what
1200b89a7cc2SEnji Cooper   // protocol we are using.
Start()1201b89a7cc2SEnji Cooper   void Start() { SendLn("gtest_streaming_protocol_version=1.0"); }
1202b89a7cc2SEnji Cooper 
FormatBool(bool value)1203b89a7cc2SEnji Cooper   std::string FormatBool(bool value) { return value ? "1" : "0"; }
1204b89a7cc2SEnji Cooper 
120528f6c2f2SEnji Cooper   const std::unique_ptr<AbstractSocketWriter> socket_writer_;
1206b89a7cc2SEnji Cooper 
120728f6c2f2SEnji Cooper   StreamingListener(const StreamingListener&) = delete;
120828f6c2f2SEnji Cooper   StreamingListener& operator=(const StreamingListener&) = delete;
1209b89a7cc2SEnji Cooper };  // class StreamingListener
1210b89a7cc2SEnji Cooper 
1211b89a7cc2SEnji Cooper #endif  // GTEST_CAN_STREAM_RESULTS_
1212b89a7cc2SEnji Cooper 
1213b89a7cc2SEnji Cooper }  // namespace internal
1214b89a7cc2SEnji Cooper }  // namespace testing
1215b89a7cc2SEnji Cooper 
1216b89a7cc2SEnji Cooper GTEST_DISABLE_MSC_WARNINGS_POP_()  //  4251
1217b89a7cc2SEnji Cooper 
121828f6c2f2SEnji Cooper #endif  // GOOGLETEST_SRC_GTEST_INTERNAL_INL_H_
1219