blob: 6554cfc07e619a79971822f7c6693e8fedaf4281 [file] [log] [blame]
Misha Brukmanc89aba32008-12-31 17:34:06 +00001// 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
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +000040// GTEST_IMPLEMENTATION_ is defined to 1 iff the current translation unit is
Benjamin Kramerf2f40202010-06-02 22:01:25 +000041// part of Google Test's implementation; otherwise it's undefined.
42#if !GTEST_IMPLEMENTATION_
Misha Brukmanc89aba32008-12-31 17:34:06 +000043// A user is trying to include this from his code - just say no.
Jay Foad22a83d62011-07-27 09:25:14 +000044# error "gtest-internal-inl.h is part of Google Test's internal implementation."
45# error "It must not be included except by Google Test itself."
Benjamin Kramerf2f40202010-06-02 22:01:25 +000046#endif // GTEST_IMPLEMENTATION_
Misha Brukmanc89aba32008-12-31 17:34:06 +000047
Benjamin Kramer78b6a292010-06-02 22:02:11 +000048#ifndef _WIN32_WCE
Jay Foad22a83d62011-07-27 09:25:14 +000049# include <errno.h>
Benjamin Kramer78b6a292010-06-02 22:02:11 +000050#endif // !_WIN32_WCE
Misha Brukmanc89aba32008-12-31 17:34:06 +000051#include <stddef.h>
Benjamin Kramer78b6a292010-06-02 22:02:11 +000052#include <stdlib.h> // For strtoll/_strtoul64/malloc/free.
53#include <string.h> // For memmove.
Benjamin Kramerf2f40202010-06-02 22:01:25 +000054
Benjamin Kramerbfb492d2010-06-02 22:02:30 +000055#include <algorithm>
Benjamin Kramerf2f40202010-06-02 22:01:25 +000056#include <string>
Benjamin Kramerbfb492d2010-06-02 22:02:30 +000057#include <vector>
Misha Brukmanc89aba32008-12-31 17:34:06 +000058
Jay Foad22a83d62011-07-27 09:25:14 +000059#include "gtest/internal/gtest-port.h"
Misha Brukmanc89aba32008-12-31 17:34:06 +000060
Benjamin Kramerf2f40202010-06-02 22:01:25 +000061#if GTEST_OS_WINDOWS
Jay Foad22a83d62011-07-27 09:25:14 +000062# include <windows.h> // NOLINT
Misha Brukmanc89aba32008-12-31 17:34:06 +000063#endif // GTEST_OS_WINDOWS
64
Jay Foad22a83d62011-07-27 09:25:14 +000065#include "gtest/gtest.h" // NOLINT
66#include "gtest/gtest-spi.h"
Misha Brukmanc89aba32008-12-31 17:34:06 +000067
68namespace testing {
69
70// Declares the flags.
71//
Benjamin Kramerf2f40202010-06-02 22:01:25 +000072// We don't want the users to modify this flag in the code, but want
73// Google Test's own unit tests to be able to access it. Therefore we
74// declare it here as opposed to in gtest.h.
75GTEST_DECLARE_bool_(death_test_use_fork);
Misha Brukmanc89aba32008-12-31 17:34:06 +000076
77namespace internal {
78
79// The value of GetTestTypeId() as seen from within the Google Test
80// library. This is solely for testing GetTestTypeId().
Benjamin Kramerbfb492d2010-06-02 22:02:30 +000081GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest;
Misha Brukmanc89aba32008-12-31 17:34:06 +000082
83// Names of the flags (needed for parsing Google Test flags).
Benjamin Kramerf2f40202010-06-02 22:01:25 +000084const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests";
Misha Brukmanc89aba32008-12-31 17:34:06 +000085const char kBreakOnFailureFlag[] = "break_on_failure";
86const char kCatchExceptionsFlag[] = "catch_exceptions";
87const char kColorFlag[] = "color";
88const char kFilterFlag[] = "filter";
89const char kListTestsFlag[] = "list_tests";
90const char kOutputFlag[] = "output";
91const char kPrintTimeFlag[] = "print_time";
Benjamin Kramer78b6a292010-06-02 22:02:11 +000092const char kRandomSeedFlag[] = "random_seed";
Misha Brukmanc89aba32008-12-31 17:34:06 +000093const char kRepeatFlag[] = "repeat";
Benjamin Kramer78b6a292010-06-02 22:02:11 +000094const char kShuffleFlag[] = "shuffle";
Benjamin Kramerbfb492d2010-06-02 22:02:30 +000095const char kStackTraceDepthFlag[] = "stack_trace_depth";
Jay Foad22a83d62011-07-27 09:25:14 +000096const char kStreamResultToFlag[] = "stream_result_to";
Benjamin Kramerf2f40202010-06-02 22:01:25 +000097const char kThrowOnFailureFlag[] = "throw_on_failure";
Misha Brukmanc89aba32008-12-31 17:34:06 +000098
Benjamin Kramer78b6a292010-06-02 22:02:11 +000099// A valid random seed must be in [1, kMaxRandomSeed].
100const int kMaxRandomSeed = 99999;
101
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000102// g_help_flag is true iff the --help flag or an equivalent form is
Benjamin Kramerbfb492d2010-06-02 22:02:30 +0000103// specified on the command line.
104GTEST_API_ extern bool g_help_flag;
105
Benjamin Kramer78b6a292010-06-02 22:02:11 +0000106// Returns the current time in milliseconds.
Benjamin Kramerbfb492d2010-06-02 22:02:30 +0000107GTEST_API_ TimeInMillis GetTimeInMillis();
108
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000109// Returns true iff Google Test should use colors in the output.
Benjamin Kramerbfb492d2010-06-02 22:02:30 +0000110GTEST_API_ bool ShouldUseColor(bool stdout_is_tty);
111
112// Formats the given time in milliseconds as seconds.
113GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms);
114
115// Parses a string for an Int32 flag, in the form of "--flag=value".
116//
117// On success, stores the value of the flag in *value, and returns
118// true. On failure, returns false without changing *value.
119GTEST_API_ bool ParseInt32Flag(
120 const char* str, const char* flag, Int32* value);
Benjamin Kramer78b6a292010-06-02 22:02:11 +0000121
122// Returns a random seed in range [1, kMaxRandomSeed] based on the
123// given --gtest_random_seed flag value.
124inline int GetRandomSeedFromFlag(Int32 random_seed_flag) {
125 const unsigned int raw_seed = (random_seed_flag == 0) ?
126 static_cast<unsigned int>(GetTimeInMillis()) :
127 static_cast<unsigned int>(random_seed_flag);
128
129 // Normalizes the actual seed to range [1, kMaxRandomSeed] such that
130 // it's easy to type.
131 const int normalized_seed =
132 static_cast<int>((raw_seed - 1U) %
133 static_cast<unsigned int>(kMaxRandomSeed)) + 1;
134 return normalized_seed;
135}
136
137// Returns the first valid random seed after 'seed'. The behavior is
138// undefined if 'seed' is invalid. The seed after kMaxRandomSeed is
139// considered to be 1.
140inline int GetNextRandomSeed(int seed) {
141 GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed)
142 << "Invalid random seed " << seed << " - must be in [1, "
143 << kMaxRandomSeed << "].";
144 const int next_seed = seed + 1;
145 return (next_seed > kMaxRandomSeed) ? 1 : next_seed;
146}
147
Misha Brukmanc89aba32008-12-31 17:34:06 +0000148// This class saves the values of all Google Test flags in its c'tor, and
149// restores them in its d'tor.
150class GTestFlagSaver {
151 public:
152 // The c'tor.
153 GTestFlagSaver() {
Benjamin Kramerf2f40202010-06-02 22:01:25 +0000154 also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests);
Misha Brukmanc89aba32008-12-31 17:34:06 +0000155 break_on_failure_ = GTEST_FLAG(break_on_failure);
156 catch_exceptions_ = GTEST_FLAG(catch_exceptions);
157 color_ = GTEST_FLAG(color);
158 death_test_style_ = GTEST_FLAG(death_test_style);
Benjamin Kramerf2f40202010-06-02 22:01:25 +0000159 death_test_use_fork_ = GTEST_FLAG(death_test_use_fork);
Misha Brukmanc89aba32008-12-31 17:34:06 +0000160 filter_ = GTEST_FLAG(filter);
161 internal_run_death_test_ = GTEST_FLAG(internal_run_death_test);
162 list_tests_ = GTEST_FLAG(list_tests);
163 output_ = GTEST_FLAG(output);
164 print_time_ = GTEST_FLAG(print_time);
Benjamin Kramer78b6a292010-06-02 22:02:11 +0000165 random_seed_ = GTEST_FLAG(random_seed);
Misha Brukmanc89aba32008-12-31 17:34:06 +0000166 repeat_ = GTEST_FLAG(repeat);
Benjamin Kramer78b6a292010-06-02 22:02:11 +0000167 shuffle_ = GTEST_FLAG(shuffle);
Benjamin Kramerbfb492d2010-06-02 22:02:30 +0000168 stack_trace_depth_ = GTEST_FLAG(stack_trace_depth);
Jay Foad22a83d62011-07-27 09:25:14 +0000169 stream_result_to_ = GTEST_FLAG(stream_result_to);
Benjamin Kramerf2f40202010-06-02 22:01:25 +0000170 throw_on_failure_ = GTEST_FLAG(throw_on_failure);
Misha Brukmanc89aba32008-12-31 17:34:06 +0000171 }
172
173 // The d'tor is not virtual. DO NOT INHERIT FROM THIS CLASS.
174 ~GTestFlagSaver() {
Benjamin Kramerf2f40202010-06-02 22:01:25 +0000175 GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_;
Misha Brukmanc89aba32008-12-31 17:34:06 +0000176 GTEST_FLAG(break_on_failure) = break_on_failure_;
177 GTEST_FLAG(catch_exceptions) = catch_exceptions_;
178 GTEST_FLAG(color) = color_;
179 GTEST_FLAG(death_test_style) = death_test_style_;
Benjamin Kramerf2f40202010-06-02 22:01:25 +0000180 GTEST_FLAG(death_test_use_fork) = death_test_use_fork_;
Misha Brukmanc89aba32008-12-31 17:34:06 +0000181 GTEST_FLAG(filter) = filter_;
182 GTEST_FLAG(internal_run_death_test) = internal_run_death_test_;
183 GTEST_FLAG(list_tests) = list_tests_;
184 GTEST_FLAG(output) = output_;
185 GTEST_FLAG(print_time) = print_time_;
Benjamin Kramer78b6a292010-06-02 22:02:11 +0000186 GTEST_FLAG(random_seed) = random_seed_;
Misha Brukmanc89aba32008-12-31 17:34:06 +0000187 GTEST_FLAG(repeat) = repeat_;
Benjamin Kramer78b6a292010-06-02 22:02:11 +0000188 GTEST_FLAG(shuffle) = shuffle_;
Benjamin Kramerbfb492d2010-06-02 22:02:30 +0000189 GTEST_FLAG(stack_trace_depth) = stack_trace_depth_;
Jay Foad22a83d62011-07-27 09:25:14 +0000190 GTEST_FLAG(stream_result_to) = stream_result_to_;
Benjamin Kramerf2f40202010-06-02 22:01:25 +0000191 GTEST_FLAG(throw_on_failure) = throw_on_failure_;
Misha Brukmanc89aba32008-12-31 17:34:06 +0000192 }
193 private:
194 // Fields for saving the original values of flags.
Benjamin Kramerf2f40202010-06-02 22:01:25 +0000195 bool also_run_disabled_tests_;
Misha Brukmanc89aba32008-12-31 17:34:06 +0000196 bool break_on_failure_;
197 bool catch_exceptions_;
198 String color_;
199 String death_test_style_;
Benjamin Kramerf2f40202010-06-02 22:01:25 +0000200 bool death_test_use_fork_;
Misha Brukmanc89aba32008-12-31 17:34:06 +0000201 String filter_;
202 String internal_run_death_test_;
203 bool list_tests_;
204 String output_;
205 bool print_time_;
Benjamin Kramer78b6a292010-06-02 22:02:11 +0000206 internal::Int32 random_seed_;
Misha Brukmanc89aba32008-12-31 17:34:06 +0000207 internal::Int32 repeat_;
Benjamin Kramer78b6a292010-06-02 22:02:11 +0000208 bool shuffle_;
Benjamin Kramerbfb492d2010-06-02 22:02:30 +0000209 internal::Int32 stack_trace_depth_;
Jay Foad22a83d62011-07-27 09:25:14 +0000210 String stream_result_to_;
Benjamin Kramerf2f40202010-06-02 22:01:25 +0000211 bool throw_on_failure_;
Misha Brukmanc89aba32008-12-31 17:34:06 +0000212} GTEST_ATTRIBUTE_UNUSED_;
213
214// Converts a Unicode code point to a narrow string in UTF-8 encoding.
215// code_point parameter is of type UInt32 because wchar_t may not be
216// wide enough to contain a code point.
217// The output buffer str must containt at least 32 characters.
218// The function returns the address of the output buffer.
219// If the code_point is not a valid Unicode code point
220// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be output
221// as '(Invalid Unicode 0xXXXXXXXX)'.
Benjamin Kramerbfb492d2010-06-02 22:02:30 +0000222GTEST_API_ char* CodePointToUtf8(UInt32 code_point, char* str);
Misha Brukmanc89aba32008-12-31 17:34:06 +0000223
224// Converts a wide string to a narrow string in UTF-8 encoding.
225// The wide string is assumed to have the following encoding:
226// UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
227// UTF-32 if sizeof(wchar_t) == 4 (on Linux)
228// Parameter str points to a null-terminated wide string.
229// Parameter num_chars may additionally limit the number
230// of wchar_t characters processed. -1 is used when the entire string
231// should be processed.
232// If the string contains code points that are not valid Unicode code points
233// (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
234// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
235// and contains invalid UTF-16 surrogate pairs, values in those pairs
236// will be encoded as individual Unicode characters from Basic Normal Plane.
Benjamin Kramerbfb492d2010-06-02 22:02:30 +0000237GTEST_API_ String WideStringToUtf8(const wchar_t* str, int num_chars);
Misha Brukmanc89aba32008-12-31 17:34:06 +0000238
Benjamin Kramerf2f40202010-06-02 22:01:25 +0000239// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
240// if the variable is present. If a file already exists at this location, this
241// function will write over it. If the variable is present, but the file cannot
242// be created, prints an error and exits.
243void WriteToShardStatusFileIfNeeded();
244
245// Checks whether sharding is enabled by examining the relevant
246// environment variable values. If the variables are present,
247// but inconsistent (e.g., shard_index >= total_shards), prints
248// an error and exits. If in_subprocess_for_death_test, sharding is
249// disabled because it must only be applied to the original test
250// process. Otherwise, we could filter out death tests we intended to execute.
Benjamin Kramerbfb492d2010-06-02 22:02:30 +0000251GTEST_API_ bool ShouldShard(const char* total_shards_str,
252 const char* shard_index_str,
253 bool in_subprocess_for_death_test);
Benjamin Kramerf2f40202010-06-02 22:01:25 +0000254
255// Parses the environment variable var as an Int32. If it is unset,
256// returns default_val. If it is not an Int32, prints an error and
257// and aborts.
Benjamin Kramerbfb492d2010-06-02 22:02:30 +0000258GTEST_API_ Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val);
Benjamin Kramerf2f40202010-06-02 22:01:25 +0000259
260// Given the total number of shards, the shard index, and the test id,
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000261// returns true iff the test should be run on this shard. The test id is
Benjamin Kramerf2f40202010-06-02 22:01:25 +0000262// some arbitrary but unique non-negative integer assigned to each test
263// method. Assumes that 0 <= shard_index < total_shards.
Benjamin Kramerbfb492d2010-06-02 22:02:30 +0000264GTEST_API_ bool ShouldRunTestOnShard(
265 int total_shards, int shard_index, int test_id);
Benjamin Kramerf2f40202010-06-02 22:01:25 +0000266
Benjamin Kramerbfb492d2010-06-02 22:02:30 +0000267// STL container utilities.
Misha Brukmanc89aba32008-12-31 17:34:06 +0000268
Benjamin Kramerbfb492d2010-06-02 22:02:30 +0000269// Returns the number of elements in the given container that satisfy
270// the given predicate.
271template <class Container, typename Predicate>
272inline int CountIf(const Container& c, Predicate predicate) {
Jay Foad22a83d62011-07-27 09:25:14 +0000273 // Implemented as an explicit loop since std::count_if() in libCstd on
274 // Solaris has a non-standard signature.
275 int count = 0;
276 for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) {
277 if (predicate(*it))
278 ++count;
279 }
280 return count;
Benjamin Kramerbfb492d2010-06-02 22:02:30 +0000281}
Misha Brukmanc89aba32008-12-31 17:34:06 +0000282
Benjamin Kramerbfb492d2010-06-02 22:02:30 +0000283// Applies a function/functor to each element in the container.
284template <class Container, typename Functor>
285void ForEach(const Container& c, Functor functor) {
286 std::for_each(c.begin(), c.end(), functor);
287}
Misha Brukmanc89aba32008-12-31 17:34:06 +0000288
Benjamin Kramerbfb492d2010-06-02 22:02:30 +0000289// Returns the i-th element of the vector, or default_value if i is not
290// in range [0, v.size()).
291template <typename E>
292inline E GetElementOr(const std::vector<E>& v, int i, E default_value) {
293 return (i < 0 || i >= static_cast<int>(v.size())) ? default_value : v[i];
294}
295
296// Performs an in-place shuffle of a range of the vector's elements.
297// 'begin' and 'end' are element indices as an STL-style range;
298// i.e. [begin, end) are shuffled, where 'end' == size() means to
299// shuffle to the end of the vector.
300template <typename E>
301void ShuffleRange(internal::Random* random, int begin, int end,
302 std::vector<E>* v) {
303 const int size = static_cast<int>(v->size());
304 GTEST_CHECK_(0 <= begin && begin <= size)
305 << "Invalid shuffle range start " << begin << ": must be in range [0, "
306 << size << "].";
307 GTEST_CHECK_(begin <= end && end <= size)
308 << "Invalid shuffle range finish " << end << ": must be in range ["
309 << begin << ", " << size << "].";
310
311 // Fisher-Yates shuffle, from
312 // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
313 for (int range_width = end - begin; range_width >= 2; range_width--) {
314 const int last_in_range = begin + range_width - 1;
315 const int selected = begin + random->Generate(range_width);
316 std::swap((*v)[selected], (*v)[last_in_range]);
Misha Brukmanc89aba32008-12-31 17:34:06 +0000317 }
Benjamin Kramerbfb492d2010-06-02 22:02:30 +0000318}
Misha Brukmanc89aba32008-12-31 17:34:06 +0000319
Benjamin Kramerbfb492d2010-06-02 22:02:30 +0000320// Performs an in-place shuffle of the vector's elements.
321template <typename E>
322inline void Shuffle(internal::Random* random, std::vector<E>* v) {
323 ShuffleRange(random, 0, static_cast<int>(v->size()), v);
324}
Misha Brukmanc89aba32008-12-31 17:34:06 +0000325
326// A function for deleting an object. Handy for being used as a
327// functor.
328template <typename T>
Benjamin Kramerbfb492d2010-06-02 22:02:30 +0000329static void Delete(T* x) {
Misha Brukmanc89aba32008-12-31 17:34:06 +0000330 delete x;
331}
332
Misha Brukmanc89aba32008-12-31 17:34:06 +0000333// A predicate that checks the key of a TestProperty against a known key.
334//
335// TestPropertyKeyIs is copyable.
336class TestPropertyKeyIs {
337 public:
338 // Constructor.
339 //
340 // TestPropertyKeyIs has NO default constructor.
341 explicit TestPropertyKeyIs(const char* key)
342 : key_(key) {}
343
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000344 // Returns true iff the test name of test property matches on key_.
Misha Brukmanc89aba32008-12-31 17:34:06 +0000345 bool operator()(const TestProperty& test_property) const {
346 return String(test_property.key()).Compare(key_) == 0;
347 }
348
349 private:
350 String key_;
351};
352
Misha Brukmanc89aba32008-12-31 17:34:06 +0000353// Class UnitTestOptions.
354//
355// This class contains functions for processing options the user
356// specifies when running the tests. It has only static members.
357//
358// In most cases, the user can specify an option using either an
359// environment variable or a command line flag. E.g. you can set the
360// test filter using either GTEST_FILTER or --gtest_filter. If both
361// the variable and the flag are present, the latter overrides the
362// former.
Benjamin Kramerbfb492d2010-06-02 22:02:30 +0000363class GTEST_API_ UnitTestOptions {
Misha Brukmanc89aba32008-12-31 17:34:06 +0000364 public:
365 // Functions for processing the gtest_output flag.
366
367 // Returns the output format, or "" for normal printed output.
368 static String GetOutputFormat();
369
Benjamin Kramerf2f40202010-06-02 22:01:25 +0000370 // Returns the absolute path of the requested output file, or the
371 // default (test_detail.xml in the original working directory) if
372 // none was explicitly specified.
373 static String GetAbsolutePathToOutputFile();
Misha Brukmanc89aba32008-12-31 17:34:06 +0000374
375 // Functions for processing the gtest_filter flag.
376
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000377 // Returns true iff the wildcard pattern matches the string. The
Misha Brukmanc89aba32008-12-31 17:34:06 +0000378 // first ':' or '\0' character in pattern marks the end of it.
379 //
380 // This recursive algorithm isn't very efficient, but is clear and
381 // works well enough for matching test names, which are short.
382 static bool PatternMatchesString(const char *pattern, const char *str);
383
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000384 // Returns true iff the user-specified filter matches the test case
Misha Brukmanc89aba32008-12-31 17:34:06 +0000385 // name and the test name.
386 static bool FilterMatchesTest(const String &test_case_name,
387 const String &test_name);
388
Benjamin Kramerf2f40202010-06-02 22:01:25 +0000389#if GTEST_OS_WINDOWS
Misha Brukmanc89aba32008-12-31 17:34:06 +0000390 // Function for supporting the gtest_catch_exception flag.
391
392 // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
393 // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
394 // This function is useful as an __except condition.
395 static int GTestShouldProcessSEH(DWORD exception_code);
396#endif // GTEST_OS_WINDOWS
397
398 // Returns true if "name" matches the ':' separated list of glob-style
399 // filters in "filter".
400 static bool MatchesFilter(const String& name, const char* filter);
401};
402
403// Returns the current application's name, removing directory path if that
404// is present. Used by UnitTestOptions::GetOutputFile.
Benjamin Kramerbfb492d2010-06-02 22:02:30 +0000405GTEST_API_ FilePath GetCurrentExecutableName();
Misha Brukmanc89aba32008-12-31 17:34:06 +0000406
407// The role interface for getting the OS stack trace as a string.
408class OsStackTraceGetterInterface {
409 public:
410 OsStackTraceGetterInterface() {}
Alexey Samsonov49109a22013-11-18 09:31:53 +0000411 virtual ~OsStackTraceGetterInterface() {}
Misha Brukmanc89aba32008-12-31 17:34:06 +0000412
413 // Returns the current OS stack trace as a String. Parameters:
414 //
415 // max_depth - the maximum number of stack frames to be included
416 // in the trace.
417 // skip_count - the number of top frames to be skipped; doesn't count
418 // against max_depth.
419 virtual String CurrentStackTrace(int max_depth, int skip_count) = 0;
420
421 // UponLeavingGTest() should be called immediately before Google Test calls
422 // user code. It saves some information about the current stack that
423 // CurrentStackTrace() will use to find and hide Google Test stack frames.
424 virtual void UponLeavingGTest() = 0;
425
426 private:
427 GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface);
428};
429
430// A working implementation of the OsStackTraceGetterInterface interface.
431class OsStackTraceGetter : public OsStackTraceGetterInterface {
432 public:
Benjamin Kramer78b6a292010-06-02 22:02:11 +0000433 OsStackTraceGetter() : caller_frame_(NULL) {}
Misha Brukmanc89aba32008-12-31 17:34:06 +0000434 virtual String CurrentStackTrace(int max_depth, int skip_count);
435 virtual void UponLeavingGTest();
436
437 // This string is inserted in place of stack frames that are part of
438 // Google Test's implementation.
439 static const char* const kElidedFramesMarker;
440
441 private:
442 Mutex mutex_; // protects all internal state
443
444 // We save the stack frame below the frame that calls user code.
445 // We do this because the address of the frame immediately below
446 // the user code changes between the call to UponLeavingGTest()
447 // and any calls to CurrentStackTrace() from within the user code.
448 void* caller_frame_;
449
450 GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter);
451};
452
453// Information about a Google Test trace point.
454struct TraceInfo {
455 const char* file;
456 int line;
457 String message;
458};
459
460// This is the default global test part result reporter used in UnitTestImpl.
461// This class should only be used by UnitTestImpl.
462class DefaultGlobalTestPartResultReporter
463 : public TestPartResultReporterInterface {
464 public:
465 explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test);
466 // Implements the TestPartResultReporterInterface. Reports the test part
467 // result in the current test.
468 virtual void ReportTestPartResult(const TestPartResult& result);
469
470 private:
471 UnitTestImpl* const unit_test_;
Benjamin Kramerf2f40202010-06-02 22:01:25 +0000472
473 GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter);
Misha Brukmanc89aba32008-12-31 17:34:06 +0000474};
475
476// This is the default per thread test part result reporter used in
477// UnitTestImpl. This class should only be used by UnitTestImpl.
478class DefaultPerThreadTestPartResultReporter
479 : public TestPartResultReporterInterface {
480 public:
481 explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test);
482 // Implements the TestPartResultReporterInterface. The implementation just
483 // delegates to the current global test part result reporter of *unit_test_.
484 virtual void ReportTestPartResult(const TestPartResult& result);
485
486 private:
487 UnitTestImpl* const unit_test_;
Benjamin Kramerf2f40202010-06-02 22:01:25 +0000488
489 GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter);
Misha Brukmanc89aba32008-12-31 17:34:06 +0000490};
491
492// The private implementation of the UnitTest class. We don't protect
493// the methods under a mutex, as this class is not accessible by a
494// user and the UnitTest class that delegates work to this class does
495// proper locking.
Benjamin Kramerbfb492d2010-06-02 22:02:30 +0000496class GTEST_API_ UnitTestImpl {
Misha Brukmanc89aba32008-12-31 17:34:06 +0000497 public:
498 explicit UnitTestImpl(UnitTest* parent);
499 virtual ~UnitTestImpl();
500
501 // There are two different ways to register your own TestPartResultReporter.
502 // You can register your own repoter to listen either only for test results
503 // from the current thread or for results from all threads.
504 // By default, each per-thread test result repoter just passes a new
505 // TestPartResult to the global test result reporter, which registers the
506 // test part result for the currently running test.
507
508 // Returns the global test part result reporter.
509 TestPartResultReporterInterface* GetGlobalTestPartResultReporter();
510
511 // Sets the global test part result reporter.
512 void SetGlobalTestPartResultReporter(
513 TestPartResultReporterInterface* reporter);
514
515 // Returns the test part result reporter for the current thread.
516 TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread();
517
518 // Sets the test part result reporter for the current thread.
519 void SetTestPartResultReporterForCurrentThread(
520 TestPartResultReporterInterface* reporter);
521
522 // Gets the number of successful test cases.
523 int successful_test_case_count() const;
524
525 // Gets the number of failed test cases.
526 int failed_test_case_count() const;
527
528 // Gets the number of all test cases.
529 int total_test_case_count() const;
530
531 // Gets the number of all test cases that contain at least one test
532 // that should run.
533 int test_case_to_run_count() const;
534
535 // Gets the number of successful tests.
536 int successful_test_count() const;
537
538 // Gets the number of failed tests.
539 int failed_test_count() const;
540
541 // Gets the number of disabled tests.
542 int disabled_test_count() const;
543
544 // Gets the number of all tests.
545 int total_test_count() const;
546
547 // Gets the number of tests that should run.
548 int test_to_run_count() const;
549
550 // Gets the elapsed time, in milliseconds.
551 TimeInMillis elapsed_time() const { return elapsed_time_; }
552
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000553 // Returns true iff the unit test passed (i.e. all test cases passed).
Misha Brukmanc89aba32008-12-31 17:34:06 +0000554 bool Passed() const { return !Failed(); }
555
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000556 // Returns true iff the unit test failed (i.e. some test case failed
Misha Brukmanc89aba32008-12-31 17:34:06 +0000557 // or something outside of all tests failed).
558 bool Failed() const {
559 return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed();
560 }
561
Benjamin Kramer78b6a292010-06-02 22:02:11 +0000562 // Gets the i-th test case among all the test cases. i can range from 0 to
563 // total_test_case_count() - 1. If i is not in that range, returns NULL.
564 const TestCase* GetTestCase(int i) const {
Benjamin Kramerbfb492d2010-06-02 22:02:30 +0000565 const int index = GetElementOr(test_case_indices_, i, -1);
566 return index < 0 ? NULL : test_cases_[i];
Misha Brukmanc89aba32008-12-31 17:34:06 +0000567 }
568
Benjamin Kramer78b6a292010-06-02 22:02:11 +0000569 // Gets the i-th test case among all the test cases. i can range from 0 to
570 // total_test_case_count() - 1. If i is not in that range, returns NULL.
571 TestCase* GetMutableTestCase(int i) {
Benjamin Kramerbfb492d2010-06-02 22:02:30 +0000572 const int index = GetElementOr(test_case_indices_, i, -1);
573 return index < 0 ? NULL : test_cases_[index];
Benjamin Kramer78b6a292010-06-02 22:02:11 +0000574 }
Misha Brukmanc89aba32008-12-31 17:34:06 +0000575
Benjamin Kramer78b6a292010-06-02 22:02:11 +0000576 // Provides access to the event listener list.
577 TestEventListeners* listeners() { return &listeners_; }
578
579 // Returns the TestResult for the test that's currently running, or
580 // the TestResult for the ad hoc test if no test is running.
581 TestResult* current_test_result();
582
583 // Returns the TestResult for the ad hoc test.
584 const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; }
Misha Brukmanc89aba32008-12-31 17:34:06 +0000585
586 // Sets the OS stack trace getter.
587 //
588 // Does nothing if the input and the current OS stack trace getter
589 // are the same; otherwise, deletes the old getter and makes the
590 // input the current getter.
591 void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter);
592
593 // Returns the current OS stack trace getter if it is not NULL;
594 // otherwise, creates an OsStackTraceGetter, makes it the current
595 // getter, and returns it.
596 OsStackTraceGetterInterface* os_stack_trace_getter();
597
598 // Returns the current OS stack trace as a String.
599 //
600 // The maximum number of stack frames to be included is specified by
601 // the gtest_stack_trace_depth flag. The skip_count parameter
602 // specifies the number of top frames to be skipped, which doesn't
603 // count against the number of frames to be included.
604 //
605 // For example, if Foo() calls Bar(), which in turn calls
606 // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
607 // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
608 String CurrentOsStackTraceExceptTop(int skip_count);
609
610 // Finds and returns a TestCase with the given name. If one doesn't
611 // exist, creates one and returns it.
612 //
613 // Arguments:
614 //
615 // test_case_name: name of the test case
Jay Foad22a83d62011-07-27 09:25:14 +0000616 // type_param: the name of the test's type parameter, or NULL if
617 // this is not a typed or a type-parameterized test.
Misha Brukmanc89aba32008-12-31 17:34:06 +0000618 // set_up_tc: pointer to the function that sets up the test case
619 // tear_down_tc: pointer to the function that tears down the test case
620 TestCase* GetTestCase(const char* test_case_name,
Jay Foad22a83d62011-07-27 09:25:14 +0000621 const char* type_param,
Misha Brukmanc89aba32008-12-31 17:34:06 +0000622 Test::SetUpTestCaseFunc set_up_tc,
623 Test::TearDownTestCaseFunc tear_down_tc);
624
625 // Adds a TestInfo to the unit test.
626 //
627 // Arguments:
628 //
629 // set_up_tc: pointer to the function that sets up the test case
630 // tear_down_tc: pointer to the function that tears down the test case
631 // test_info: the TestInfo object
632 void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc,
633 Test::TearDownTestCaseFunc tear_down_tc,
Jay Foad22a83d62011-07-27 09:25:14 +0000634 TestInfo* test_info) {
Misha Brukmanc89aba32008-12-31 17:34:06 +0000635 // In order to support thread-safe death tests, we need to
636 // remember the original working directory when the test program
637 // was first invoked. We cannot do this in RUN_ALL_TESTS(), as
638 // the user may have changed the current directory before calling
639 // RUN_ALL_TESTS(). Therefore we capture the current directory in
640 // AddTestInfo(), which is called to register a TEST or TEST_F
641 // before main() is reached.
642 if (original_working_dir_.IsEmpty()) {
643 original_working_dir_.Set(FilePath::GetCurrentDir());
Benjamin Kramer78b6a292010-06-02 22:02:11 +0000644 GTEST_CHECK_(!original_working_dir_.IsEmpty())
645 << "Failed to get the current working directory.";
Misha Brukmanc89aba32008-12-31 17:34:06 +0000646 }
647
648 GetTestCase(test_info->test_case_name(),
Jay Foad22a83d62011-07-27 09:25:14 +0000649 test_info->type_param(),
Misha Brukmanc89aba32008-12-31 17:34:06 +0000650 set_up_tc,
651 tear_down_tc)->AddTestInfo(test_info);
652 }
653
Benjamin Kramerf2f40202010-06-02 22:01:25 +0000654#if GTEST_HAS_PARAM_TEST
Misha Brukmanc89aba32008-12-31 17:34:06 +0000655 // Returns ParameterizedTestCaseRegistry object used to keep track of
656 // value-parameterized tests and instantiate and register them.
657 internal::ParameterizedTestCaseRegistry& parameterized_test_registry() {
658 return parameterized_test_registry_;
659 }
660#endif // GTEST_HAS_PARAM_TEST
661
662 // Sets the TestCase object for the test that's currently running.
Benjamin Kramerbfb492d2010-06-02 22:02:30 +0000663 void set_current_test_case(TestCase* a_current_test_case) {
664 current_test_case_ = a_current_test_case;
Misha Brukmanc89aba32008-12-31 17:34:06 +0000665 }
666
667 // Sets the TestInfo object for the test that's currently running. If
668 // current_test_info is NULL, the assertion results will be stored in
669 // ad_hoc_test_result_.
Benjamin Kramerbfb492d2010-06-02 22:02:30 +0000670 void set_current_test_info(TestInfo* a_current_test_info) {
671 current_test_info_ = a_current_test_info;
Misha Brukmanc89aba32008-12-31 17:34:06 +0000672 }
673
674 // Registers all parameterized tests defined using TEST_P and
Jay Foad22a83d62011-07-27 09:25:14 +0000675 // INSTANTIATE_TEST_CASE_P, creating regular tests for each test/parameter
676 // combination. This method can be called more then once; it has guards
677 // protecting from registering the tests more then once. If
678 // value-parameterized tests are disabled, RegisterParameterizedTests is
679 // present but does nothing.
Misha Brukmanc89aba32008-12-31 17:34:06 +0000680 void RegisterParameterizedTests();
681
682 // Runs all tests in this UnitTest object, prints the result, and
Jay Foad22a83d62011-07-27 09:25:14 +0000683 // returns true if all tests are successful. If any exception is
684 // thrown during a test, this test is considered to be failed, but
685 // the rest of the tests will still be run.
686 bool RunAllTests();
Misha Brukmanc89aba32008-12-31 17:34:06 +0000687
Jay Foad22a83d62011-07-27 09:25:14 +0000688 // Clears the results of all tests, except the ad hoc tests.
689 void ClearNonAdHocTestResult() {
Benjamin Kramerbfb492d2010-06-02 22:02:30 +0000690 ForEach(test_cases_, TestCase::ClearTestCaseResult);
Jay Foad22a83d62011-07-27 09:25:14 +0000691 }
692
693 // Clears the results of ad-hoc test assertions.
694 void ClearAdHocTestResult() {
Misha Brukmanc89aba32008-12-31 17:34:06 +0000695 ad_hoc_test_result_.Clear();
696 }
697
Benjamin Kramerf2f40202010-06-02 22:01:25 +0000698 enum ReactionToSharding {
699 HONOR_SHARDING_PROTOCOL,
700 IGNORE_SHARDING_PROTOCOL
701 };
702
Misha Brukmanc89aba32008-12-31 17:34:06 +0000703 // Matches the full name of each test against the user-specified
704 // filter to decide whether the test should run, then records the
705 // result in each TestCase and TestInfo object.
Benjamin Kramerf2f40202010-06-02 22:01:25 +0000706 // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests
707 // based on sharding variables in the environment.
Misha Brukmanc89aba32008-12-31 17:34:06 +0000708 // Returns the number of tests that should run.
Benjamin Kramerf2f40202010-06-02 22:01:25 +0000709 int FilterTests(ReactionToSharding shard_tests);
Misha Brukmanc89aba32008-12-31 17:34:06 +0000710
Benjamin Kramer78b6a292010-06-02 22:02:11 +0000711 // Prints the names of the tests matching the user-specified filter flag.
712 void ListTestsMatchingFilter();
Misha Brukmanc89aba32008-12-31 17:34:06 +0000713
714 const TestCase* current_test_case() const { return current_test_case_; }
715 TestInfo* current_test_info() { return current_test_info_; }
716 const TestInfo* current_test_info() const { return current_test_info_; }
717
Benjamin Kramer78b6a292010-06-02 22:02:11 +0000718 // Returns the vector of environments that need to be set-up/torn-down
Misha Brukmanc89aba32008-12-31 17:34:06 +0000719 // before/after the tests are run.
Benjamin Kramerbfb492d2010-06-02 22:02:30 +0000720 std::vector<Environment*>& environments() { return environments_; }
Misha Brukmanc89aba32008-12-31 17:34:06 +0000721
Misha Brukmanc89aba32008-12-31 17:34:06 +0000722 // Getters for the per-thread Google Test trace stack.
Benjamin Kramerbfb492d2010-06-02 22:02:30 +0000723 std::vector<TraceInfo>& gtest_trace_stack() {
724 return *(gtest_trace_stack_.pointer());
Misha Brukmanc89aba32008-12-31 17:34:06 +0000725 }
Benjamin Kramerbfb492d2010-06-02 22:02:30 +0000726 const std::vector<TraceInfo>& gtest_trace_stack() const {
727 return gtest_trace_stack_.get();
Misha Brukmanc89aba32008-12-31 17:34:06 +0000728 }
729
Benjamin Kramerf2f40202010-06-02 22:01:25 +0000730#if GTEST_HAS_DEATH_TEST
Benjamin Kramer78b6a292010-06-02 22:02:11 +0000731 void InitDeathTestSubprocessControlInfo() {
732 internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());
733 }
Misha Brukmanc89aba32008-12-31 17:34:06 +0000734 // Returns a pointer to the parsed --gtest_internal_run_death_test
735 // flag, or NULL if that flag was not specified.
736 // This information is useful only in a death test child process.
Benjamin Kramer78b6a292010-06-02 22:02:11 +0000737 // Must not be called before a call to InitGoogleTest.
Misha Brukmanc89aba32008-12-31 17:34:06 +0000738 const InternalRunDeathTestFlag* internal_run_death_test_flag() const {
739 return internal_run_death_test_flag_.get();
740 }
741
742 // Returns a pointer to the current death test factory.
743 internal::DeathTestFactory* death_test_factory() {
744 return death_test_factory_.get();
745 }
746
Benjamin Kramer78b6a292010-06-02 22:02:11 +0000747 void SuppressTestEventsIfInSubprocess();
748
Misha Brukmanc89aba32008-12-31 17:34:06 +0000749 friend class ReplaceDeathTestFactory;
750#endif // GTEST_HAS_DEATH_TEST
751
Benjamin Kramer78b6a292010-06-02 22:02:11 +0000752 // Initializes the event listener performing XML output as specified by
753 // UnitTestOptions. Must not be called before InitGoogleTest.
754 void ConfigureXmlOutput();
755
Jay Foad22a83d62011-07-27 09:25:14 +0000756#if GTEST_CAN_STREAM_RESULTS_
757 // Initializes the event listener for streaming test results to a socket.
758 // Must not be called before InitGoogleTest.
759 void ConfigureStreamingOutput();
760#endif
761
Benjamin Kramer78b6a292010-06-02 22:02:11 +0000762 // Performs initialization dependent upon flag values obtained in
763 // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
764 // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
765 // this function is also called from RunAllTests. Since this function can be
766 // called more than once, it has to be idempotent.
767 void PostFlagParsingInit();
768
769 // Gets the random seed used at the start of the current test iteration.
770 int random_seed() const { return random_seed_; }
771
772 // Gets the random number generator.
773 internal::Random* random() { return &random_; }
774
775 // Shuffles all test cases, and the tests within each test case,
776 // making sure that death tests are still run first.
777 void ShuffleTests();
778
779 // Restores the test cases and tests to their order before the first shuffle.
780 void UnshuffleTests();
781
Jay Foad22a83d62011-07-27 09:25:14 +0000782 // Returns the value of GTEST_FLAG(catch_exceptions) at the moment
783 // UnitTest::Run() starts.
784 bool catch_exceptions() const { return catch_exceptions_; }
785
Misha Brukmanc89aba32008-12-31 17:34:06 +0000786 private:
787 friend class ::testing::UnitTest;
788
Jay Foad22a83d62011-07-27 09:25:14 +0000789 // Used by UnitTest::Run() to capture the state of
790 // GTEST_FLAG(catch_exceptions) at the moment it starts.
791 void set_catch_exceptions(bool value) { catch_exceptions_ = value; }
792
Misha Brukmanc89aba32008-12-31 17:34:06 +0000793 // The UnitTest object that owns this implementation object.
794 UnitTest* const parent_;
795
796 // The working directory when the first TEST() or TEST_F() was
797 // executed.
798 internal::FilePath original_working_dir_;
799
800 // The default test part result reporters.
801 DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_;
802 DefaultPerThreadTestPartResultReporter
803 default_per_thread_test_part_result_reporter_;
804
805 // Points to (but doesn't own) the global test part result reporter.
806 TestPartResultReporterInterface* global_test_part_result_repoter_;
807
808 // Protects read and write access to global_test_part_result_reporter_.
809 internal::Mutex global_test_part_result_reporter_mutex_;
810
811 // Points to (but doesn't own) the per-thread test part result reporter.
812 internal::ThreadLocal<TestPartResultReporterInterface*>
813 per_thread_test_part_result_reporter_;
814
Benjamin Kramer78b6a292010-06-02 22:02:11 +0000815 // The vector of environments that need to be set-up/torn-down
Benjamin Kramerbfb492d2010-06-02 22:02:30 +0000816 // before/after the tests are run.
817 std::vector<Environment*> environments_;
Misha Brukmanc89aba32008-12-31 17:34:06 +0000818
Benjamin Kramer78b6a292010-06-02 22:02:11 +0000819 // The vector of TestCases in their original order. It owns the
820 // elements in the vector.
Benjamin Kramerbfb492d2010-06-02 22:02:30 +0000821 std::vector<TestCase*> test_cases_;
Benjamin Kramer78b6a292010-06-02 22:02:11 +0000822
823 // Provides a level of indirection for the test case list to allow
824 // easy shuffling and restoring the test case order. The i-th
825 // element of this vector is the index of the i-th test case in the
826 // shuffled order.
Benjamin Kramerbfb492d2010-06-02 22:02:30 +0000827 std::vector<int> test_case_indices_;
Misha Brukmanc89aba32008-12-31 17:34:06 +0000828
Benjamin Kramerf2f40202010-06-02 22:01:25 +0000829#if GTEST_HAS_PARAM_TEST
Misha Brukmanc89aba32008-12-31 17:34:06 +0000830 // ParameterizedTestRegistry object used to register value-parameterized
831 // tests.
832 internal::ParameterizedTestCaseRegistry parameterized_test_registry_;
833
834 // Indicates whether RegisterParameterizedTests() has been called already.
835 bool parameterized_tests_registered_;
836#endif // GTEST_HAS_PARAM_TEST
837
Benjamin Kramer78b6a292010-06-02 22:02:11 +0000838 // Index of the last death test case registered. Initially -1.
839 int last_death_test_case_;
Misha Brukmanc89aba32008-12-31 17:34:06 +0000840
841 // This points to the TestCase for the currently running test. It
842 // changes as Google Test goes through one test case after another.
843 // When no test is running, this is set to NULL and Google Test
Benjamin Kramer78b6a292010-06-02 22:02:11 +0000844 // stores assertion results in ad_hoc_test_result_. Initially NULL.
Misha Brukmanc89aba32008-12-31 17:34:06 +0000845 TestCase* current_test_case_;
846
847 // This points to the TestInfo for the currently running test. It
848 // changes as Google Test goes through one test after another. When
849 // no test is running, this is set to NULL and Google Test stores
850 // assertion results in ad_hoc_test_result_. Initially NULL.
851 TestInfo* current_test_info_;
852
853 // Normally, a user only writes assertions inside a TEST or TEST_F,
854 // or inside a function called by a TEST or TEST_F. Since Google
855 // Test keeps track of which test is current running, it can
856 // associate such an assertion with the test it belongs to.
857 //
858 // If an assertion is encountered when no TEST or TEST_F is running,
859 // Google Test attributes the assertion result to an imaginary "ad hoc"
860 // test, and records the result in ad_hoc_test_result_.
Benjamin Kramer78b6a292010-06-02 22:02:11 +0000861 TestResult ad_hoc_test_result_;
Misha Brukmanc89aba32008-12-31 17:34:06 +0000862
Benjamin Kramer78b6a292010-06-02 22:02:11 +0000863 // The list of event listeners that can be used to track events inside
864 // Google Test.
865 TestEventListeners listeners_;
Misha Brukmanc89aba32008-12-31 17:34:06 +0000866
867 // The OS stack trace getter. Will be deleted when the UnitTest
868 // object is destructed. By default, an OsStackTraceGetter is used,
869 // but the user can set this field to use a custom getter if that is
870 // desired.
871 OsStackTraceGetterInterface* os_stack_trace_getter_;
872
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000873 // True iff PostFlagParsingInit() has been called.
Benjamin Kramer78b6a292010-06-02 22:02:11 +0000874 bool post_flag_parse_init_performed_;
875
876 // The random number seed used at the beginning of the test run.
877 int random_seed_;
878
879 // Our random number generator.
880 internal::Random random_;
881
Misha Brukmanc89aba32008-12-31 17:34:06 +0000882 // How long the test took to run, in milliseconds.
883 TimeInMillis elapsed_time_;
884
Benjamin Kramerf2f40202010-06-02 22:01:25 +0000885#if GTEST_HAS_DEATH_TEST
Misha Brukmanc89aba32008-12-31 17:34:06 +0000886 // The decomposed components of the gtest_internal_run_death_test flag,
887 // parsed when RUN_ALL_TESTS is called.
888 internal::scoped_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;
889 internal::scoped_ptr<internal::DeathTestFactory> death_test_factory_;
890#endif // GTEST_HAS_DEATH_TEST
891
892 // A per-thread stack of traces created by the SCOPED_TRACE() macro.
Benjamin Kramerbfb492d2010-06-02 22:02:30 +0000893 internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_;
Misha Brukmanc89aba32008-12-31 17:34:06 +0000894
Jay Foad22a83d62011-07-27 09:25:14 +0000895 // The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests()
896 // starts.
897 bool catch_exceptions_;
898
Misha Brukmanc89aba32008-12-31 17:34:06 +0000899 GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl);
900}; // class UnitTestImpl
901
902// Convenience function for accessing the global UnitTest
903// implementation object.
904inline UnitTestImpl* GetUnitTestImpl() {
905 return UnitTest::GetInstance()->impl();
906}
907
Jay Foad22a83d62011-07-27 09:25:14 +0000908#if GTEST_USES_SIMPLE_RE
909
Benjamin Kramerf2f40202010-06-02 22:01:25 +0000910// Internal helper functions for implementing the simple regular
911// expression matcher.
Benjamin Kramerbfb492d2010-06-02 22:02:30 +0000912GTEST_API_ bool IsInSet(char ch, const char* str);
Jay Foad22a83d62011-07-27 09:25:14 +0000913GTEST_API_ bool IsAsciiDigit(char ch);
914GTEST_API_ bool IsAsciiPunct(char ch);
Benjamin Kramerbfb492d2010-06-02 22:02:30 +0000915GTEST_API_ bool IsRepeat(char ch);
Jay Foad22a83d62011-07-27 09:25:14 +0000916GTEST_API_ bool IsAsciiWhiteSpace(char ch);
917GTEST_API_ bool IsAsciiWordChar(char ch);
Benjamin Kramerbfb492d2010-06-02 22:02:30 +0000918GTEST_API_ bool IsValidEscape(char ch);
919GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch);
920GTEST_API_ bool ValidateRegex(const char* regex);
921GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str);
922GTEST_API_ bool MatchRepetitionAndRegexAtHead(
Benjamin Kramerf2f40202010-06-02 22:01:25 +0000923 bool escaped, char ch, char repeat, const char* regex, const char* str);
Benjamin Kramerbfb492d2010-06-02 22:02:30 +0000924GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str);
Benjamin Kramerf2f40202010-06-02 22:01:25 +0000925
Jay Foad22a83d62011-07-27 09:25:14 +0000926#endif // GTEST_USES_SIMPLE_RE
927
Misha Brukmanc89aba32008-12-31 17:34:06 +0000928// Parses the command line for Google Test flags, without initializing
929// other parts of Google Test.
Benjamin Kramerbfb492d2010-06-02 22:02:30 +0000930GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv);
931GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv);
Misha Brukmanc89aba32008-12-31 17:34:06 +0000932
Benjamin Kramerf2f40202010-06-02 22:01:25 +0000933#if GTEST_HAS_DEATH_TEST
934
935// Returns the message describing the last system error, regardless of the
936// platform.
Jay Foad22a83d62011-07-27 09:25:14 +0000937GTEST_API_ String GetLastErrnoDescription();
Benjamin Kramerf2f40202010-06-02 22:01:25 +0000938
Jay Foad22a83d62011-07-27 09:25:14 +0000939# if GTEST_OS_WINDOWS
Benjamin Kramerf2f40202010-06-02 22:01:25 +0000940// Provides leak-safe Windows kernel handle ownership.
941class AutoHandle {
942 public:
943 AutoHandle() : handle_(INVALID_HANDLE_VALUE) {}
944 explicit AutoHandle(HANDLE handle) : handle_(handle) {}
945
946 ~AutoHandle() { Reset(); }
947
948 HANDLE Get() const { return handle_; }
949 void Reset() { Reset(INVALID_HANDLE_VALUE); }
950 void Reset(HANDLE handle) {
951 if (handle != handle_) {
952 if (handle_ != INVALID_HANDLE_VALUE)
953 ::CloseHandle(handle_);
954 handle_ = handle;
955 }
956 }
957
958 private:
959 HANDLE handle_;
960
961 GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle);
962};
Jay Foad22a83d62011-07-27 09:25:14 +0000963# endif // GTEST_OS_WINDOWS
Benjamin Kramerf2f40202010-06-02 22:01:25 +0000964
965// Attempts to parse a string into a positive integer pointed to by the
966// number parameter. Returns true if that is possible.
967// GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use
968// it here.
969template <typename Integer>
970bool ParseNaturalNumber(const ::std::string& str, Integer* number) {
971 // Fail fast if the given string does not begin with a digit;
972 // this bypasses strtoXXX's "optional leading whitespace and plus
973 // or minus sign" semantics, which are undesirable here.
Jay Foad22a83d62011-07-27 09:25:14 +0000974 if (str.empty() || !IsDigit(str[0])) {
Benjamin Kramerf2f40202010-06-02 22:01:25 +0000975 return false;
976 }
977 errno = 0;
978
979 char* end;
980 // BiggestConvertible is the largest integer type that system-provided
981 // string-to-number conversion routines can return.
Jay Foad22a83d62011-07-27 09:25:14 +0000982
983# if GTEST_OS_WINDOWS && !defined(__GNUC__)
984
Benjamin Kramer78b6a292010-06-02 22:02:11 +0000985 // MSVC and C++ Builder define __int64 instead of the standard long long.
Benjamin Kramerf2f40202010-06-02 22:01:25 +0000986 typedef unsigned __int64 BiggestConvertible;
987 const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10);
Jay Foad22a83d62011-07-27 09:25:14 +0000988
989# else
990
Benjamin Kramerf2f40202010-06-02 22:01:25 +0000991 typedef unsigned long long BiggestConvertible; // NOLINT
992 const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10);
Jay Foad22a83d62011-07-27 09:25:14 +0000993
994# endif // GTEST_OS_WINDOWS && !defined(__GNUC__)
995
Benjamin Kramerf2f40202010-06-02 22:01:25 +0000996 const bool parse_success = *end == '\0' && errno == 0;
997
998 // TODO(vladl@google.com): Convert this to compile time assertion when it is
999 // available.
1000 GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed));
1001
1002 const Integer result = static_cast<Integer>(parsed);
1003 if (parse_success && static_cast<BiggestConvertible>(result) == parsed) {
1004 *number = result;
1005 return true;
1006 }
1007 return false;
1008}
1009#endif // GTEST_HAS_DEATH_TEST
1010
Benjamin Kramer78b6a292010-06-02 22:02:11 +00001011// TestResult contains some private methods that should be hidden from
1012// Google Test user but are required for testing. This class allow our tests
1013// to access them.
Benjamin Kramerbfb492d2010-06-02 22:02:30 +00001014//
1015// This class is supplied only for the purpose of testing Google Test's own
1016// constructs. Do not use it in user tests, either directly or indirectly.
Benjamin Kramer78b6a292010-06-02 22:02:11 +00001017class TestResultAccessor {
1018 public:
1019 static void RecordProperty(TestResult* test_result,
1020 const TestProperty& property) {
1021 test_result->RecordProperty(property);
1022 }
1023
1024 static void ClearTestPartResults(TestResult* test_result) {
1025 test_result->ClearTestPartResults();
1026 }
1027
Benjamin Kramerbfb492d2010-06-02 22:02:30 +00001028 static const std::vector<testing::TestPartResult>& test_part_results(
Benjamin Kramer78b6a292010-06-02 22:02:11 +00001029 const TestResult& test_result) {
1030 return test_result.test_part_results();
1031 }
1032};
1033
Misha Brukmanc89aba32008-12-31 17:34:06 +00001034} // namespace internal
1035} // namespace testing
1036
1037#endif // GTEST_SRC_GTEST_INTERNAL_INL_H_