Path: blob/master/dep/googletest/src/gtest-internal-inl.h
4804 views
// Copyright 2005, Google Inc.1// All rights reserved.2//3// Redistribution and use in source and binary forms, with or without4// modification, are permitted provided that the following conditions are5// met:6//7// * Redistributions of source code must retain the above copyright8// notice, this list of conditions and the following disclaimer.9// * Redistributions in binary form must reproduce the above10// copyright notice, this list of conditions and the following disclaimer11// in the documentation and/or other materials provided with the12// distribution.13// * Neither the name of Google Inc. nor the names of its14// contributors may be used to endorse or promote products derived from15// this software without specific prior written permission.16//17// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS18// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT19// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR20// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT21// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,22// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT23// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,24// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY25// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT26// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE27// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.2829// Utility functions and classes used by the Google C++ testing framework.//30// This file contains purely Google Test's internal implementation. Please31// DO NOT #INCLUDE IT IN A USER PROGRAM.3233#ifndef GOOGLETEST_SRC_GTEST_INTERNAL_INL_H_34#define GOOGLETEST_SRC_GTEST_INTERNAL_INL_H_3536#ifndef _WIN32_WCE37#include <errno.h>38#endif // !_WIN32_WCE39#include <stddef.h>40#include <stdlib.h> // For strtoll/_strtoul64/malloc/free.41#include <string.h> // For memmove.4243#include <algorithm>44#include <cstdint>45#include <memory>46#include <set>47#include <string>48#include <unordered_map>49#include <vector>5051#include "gtest/internal/gtest-port.h"5253#if GTEST_CAN_STREAM_RESULTS_54#include <arpa/inet.h> // NOLINT55#include <netdb.h> // NOLINT56#endif5758#ifdef GTEST_OS_WINDOWS59#include <windows.h> // NOLINT60#endif // GTEST_OS_WINDOWS6162#include "gtest/gtest-spi.h"63#include "gtest/gtest.h"6465GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \66/* class A needs to have dll-interface to be used by clients of class B */)6768// Declares the flags.69//70// We don't want the users to modify this flag in the code, but want71// Google Test's own unit tests to be able to access it. Therefore we72// declare it here as opposed to in gtest.h.73GTEST_DECLARE_bool_(death_test_use_fork);7475namespace testing {76namespace internal {7778// The value of GetTestTypeId() as seen from within the Google Test79// library. This is solely for testing GetTestTypeId().80GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest;8182// A valid random seed must be in [1, kMaxRandomSeed].83const int kMaxRandomSeed = 99999;8485// g_help_flag is true if and only if the --help flag or an equivalent form86// is specified on the command line.87GTEST_API_ extern bool g_help_flag;8889// Returns the current time in milliseconds.90GTEST_API_ TimeInMillis GetTimeInMillis();9192// Returns true if and only if Google Test should use colors in the output.93GTEST_API_ bool ShouldUseColor(bool stdout_is_tty);9495// Formats the given time in milliseconds as seconds. If the input is an exact N96// seconds, the output has a trailing decimal point (e.g., "N." instead of "N").97GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms);9899// Converts the given time in milliseconds to a date string in the ISO 8601100// format, without the timezone information. N.B.: due to the use the101// non-reentrant localtime() function, this function is not thread safe. Do102// not use it in any code that can be called from multiple threads.103GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms);104105// Parses a string for an Int32 flag, in the form of "--flag=value".106//107// On success, stores the value of the flag in *value, and returns108// true. On failure, returns false without changing *value.109GTEST_API_ bool ParseFlag(const char* str, const char* flag, int32_t* value);110111// Returns a random seed in range [1, kMaxRandomSeed] based on the112// given --gtest_random_seed flag value.113inline int GetRandomSeedFromFlag(int32_t random_seed_flag) {114const unsigned int raw_seed =115(random_seed_flag == 0) ? static_cast<unsigned int>(GetTimeInMillis())116: static_cast<unsigned int>(random_seed_flag);117118// Normalizes the actual seed to range [1, kMaxRandomSeed] such that119// it's easy to type.120const int normalized_seed =121static_cast<int>((raw_seed - 1U) %122static_cast<unsigned int>(kMaxRandomSeed)) +1231;124return normalized_seed;125}126127// Returns the first valid random seed after 'seed'. The behavior is128// undefined if 'seed' is invalid. The seed after kMaxRandomSeed is129// considered to be 1.130inline int GetNextRandomSeed(int seed) {131GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed)132<< "Invalid random seed " << seed << " - must be in [1, "133<< kMaxRandomSeed << "].";134const int next_seed = seed + 1;135return (next_seed > kMaxRandomSeed) ? 1 : next_seed;136}137138// This class saves the values of all Google Test flags in its c'tor, and139// restores them in its d'tor.140class GTestFlagSaver {141public:142// The c'tor.143GTestFlagSaver() {144also_run_disabled_tests_ = GTEST_FLAG_GET(also_run_disabled_tests);145break_on_failure_ = GTEST_FLAG_GET(break_on_failure);146catch_exceptions_ = GTEST_FLAG_GET(catch_exceptions);147color_ = GTEST_FLAG_GET(color);148death_test_style_ = GTEST_FLAG_GET(death_test_style);149death_test_use_fork_ = GTEST_FLAG_GET(death_test_use_fork);150fail_fast_ = GTEST_FLAG_GET(fail_fast);151filter_ = GTEST_FLAG_GET(filter);152internal_run_death_test_ = GTEST_FLAG_GET(internal_run_death_test);153list_tests_ = GTEST_FLAG_GET(list_tests);154output_ = GTEST_FLAG_GET(output);155brief_ = GTEST_FLAG_GET(brief);156print_time_ = GTEST_FLAG_GET(print_time);157print_utf8_ = GTEST_FLAG_GET(print_utf8);158random_seed_ = GTEST_FLAG_GET(random_seed);159repeat_ = GTEST_FLAG_GET(repeat);160recreate_environments_when_repeating_ =161GTEST_FLAG_GET(recreate_environments_when_repeating);162shuffle_ = GTEST_FLAG_GET(shuffle);163stack_trace_depth_ = GTEST_FLAG_GET(stack_trace_depth);164stream_result_to_ = GTEST_FLAG_GET(stream_result_to);165throw_on_failure_ = GTEST_FLAG_GET(throw_on_failure);166}167168// The d'tor is not virtual. DO NOT INHERIT FROM THIS CLASS.169~GTestFlagSaver() {170GTEST_FLAG_SET(also_run_disabled_tests, also_run_disabled_tests_);171GTEST_FLAG_SET(break_on_failure, break_on_failure_);172GTEST_FLAG_SET(catch_exceptions, catch_exceptions_);173GTEST_FLAG_SET(color, color_);174GTEST_FLAG_SET(death_test_style, death_test_style_);175GTEST_FLAG_SET(death_test_use_fork, death_test_use_fork_);176GTEST_FLAG_SET(filter, filter_);177GTEST_FLAG_SET(fail_fast, fail_fast_);178GTEST_FLAG_SET(internal_run_death_test, internal_run_death_test_);179GTEST_FLAG_SET(list_tests, list_tests_);180GTEST_FLAG_SET(output, output_);181GTEST_FLAG_SET(brief, brief_);182GTEST_FLAG_SET(print_time, print_time_);183GTEST_FLAG_SET(print_utf8, print_utf8_);184GTEST_FLAG_SET(random_seed, random_seed_);185GTEST_FLAG_SET(repeat, repeat_);186GTEST_FLAG_SET(recreate_environments_when_repeating,187recreate_environments_when_repeating_);188GTEST_FLAG_SET(shuffle, shuffle_);189GTEST_FLAG_SET(stack_trace_depth, stack_trace_depth_);190GTEST_FLAG_SET(stream_result_to, stream_result_to_);191GTEST_FLAG_SET(throw_on_failure, throw_on_failure_);192}193194private:195// Fields for saving the original values of flags.196bool also_run_disabled_tests_;197bool break_on_failure_;198bool catch_exceptions_;199std::string color_;200std::string death_test_style_;201bool death_test_use_fork_;202bool fail_fast_;203std::string filter_;204std::string internal_run_death_test_;205bool list_tests_;206std::string output_;207bool brief_;208bool print_time_;209bool print_utf8_;210int32_t random_seed_;211int32_t repeat_;212bool recreate_environments_when_repeating_;213bool shuffle_;214int32_t stack_trace_depth_;215std::string stream_result_to_;216bool throw_on_failure_;217};218219// Converts a Unicode code point to a narrow string in UTF-8 encoding.220// code_point parameter is of type UInt32 because wchar_t may not be221// wide enough to contain a code point.222// If the code_point is not a valid Unicode code point223// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted224// to "(Invalid Unicode 0xXXXXXXXX)".225GTEST_API_ std::string CodePointToUtf8(uint32_t code_point);226227// Converts a wide string to a narrow string in UTF-8 encoding.228// The wide string is assumed to have the following encoding:229// UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin)230// UTF-32 if sizeof(wchar_t) == 4 (on Linux)231// Parameter str points to a null-terminated wide string.232// Parameter num_chars may additionally limit the number233// of wchar_t characters processed. -1 is used when the entire string234// should be processed.235// If the string contains code points that are not valid Unicode code points236// (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output237// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding238// and contains invalid UTF-16 surrogate pairs, values in those pairs239// will be encoded as individual Unicode characters from Basic Normal Plane.240GTEST_API_ std::string WideStringToUtf8(const wchar_t* str, int num_chars);241242// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file243// if the variable is present. If a file already exists at this location, this244// function will write over it. If the variable is present, but the file cannot245// be created, prints an error and exits.246void WriteToShardStatusFileIfNeeded();247248// Checks whether sharding is enabled by examining the relevant249// environment variable values. If the variables are present,250// but inconsistent (e.g., shard_index >= total_shards), prints251// an error and exits. If in_subprocess_for_death_test, sharding is252// disabled because it must only be applied to the original test253// process. Otherwise, we could filter out death tests we intended to execute.254GTEST_API_ bool ShouldShard(const char* total_shards_str,255const char* shard_index_str,256bool in_subprocess_for_death_test);257258// Parses the environment variable var as a 32-bit integer. If it is unset,259// returns default_val. If it is not a 32-bit integer, prints an error and260// and aborts.261GTEST_API_ int32_t Int32FromEnvOrDie(const char* env_var, int32_t default_val);262263// Given the total number of shards, the shard index, and the test id,264// returns true if and only if the test should be run on this shard. The test id265// is some arbitrary but unique non-negative integer assigned to each test266// method. Assumes that 0 <= shard_index < total_shards.267GTEST_API_ bool ShouldRunTestOnShard(int total_shards, int shard_index,268int test_id);269270// STL container utilities.271272// Returns the number of elements in the given container that satisfy273// the given predicate.274template <class Container, typename Predicate>275inline int CountIf(const Container& c, Predicate predicate) {276// Implemented as an explicit loop since std::count_if() in libCstd on277// Solaris has a non-standard signature.278int count = 0;279for (auto it = c.begin(); it != c.end(); ++it) {280if (predicate(*it)) ++count;281}282return count;283}284285// Applies a function/functor to each element in the container.286template <class Container, typename Functor>287void ForEach(const Container& c, Functor functor) {288std::for_each(c.begin(), c.end(), functor);289}290291// Returns the i-th element of the vector, or default_value if i is not292// in range [0, v.size()).293template <typename E>294inline E GetElementOr(const std::vector<E>& v, int i, E default_value) {295return (i < 0 || i >= static_cast<int>(v.size())) ? default_value296: v[static_cast<size_t>(i)];297}298299// Performs an in-place shuffle of a range of the vector's elements.300// 'begin' and 'end' are element indices as an STL-style range;301// i.e. [begin, end) are shuffled, where 'end' == size() means to302// shuffle to the end of the vector.303template <typename E>304void ShuffleRange(internal::Random* random, int begin, int end,305std::vector<E>* v) {306const int size = static_cast<int>(v->size());307GTEST_CHECK_(0 <= begin && begin <= size)308<< "Invalid shuffle range start " << begin << ": must be in range [0, "309<< size << "].";310GTEST_CHECK_(begin <= end && end <= size)311<< "Invalid shuffle range finish " << end << ": must be in range ["312<< begin << ", " << size << "].";313314// Fisher-Yates shuffle, from315// https://en.wikipedia.org/wiki/Fisher-Yates_shuffle316for (int range_width = end - begin; range_width >= 2; range_width--) {317const int last_in_range = begin + range_width - 1;318const int selected =319begin +320static_cast<int>(random->Generate(static_cast<uint32_t>(range_width)));321std::swap((*v)[static_cast<size_t>(selected)],322(*v)[static_cast<size_t>(last_in_range)]);323}324}325326// Performs an in-place shuffle of the vector's elements.327template <typename E>328inline void Shuffle(internal::Random* random, std::vector<E>* v) {329ShuffleRange(random, 0, static_cast<int>(v->size()), v);330}331332// A function for deleting an object. Handy for being used as a333// functor.334template <typename T>335static void Delete(T* x) {336delete x;337}338339// A predicate that checks the key of a TestProperty against a known key.340//341// TestPropertyKeyIs is copyable.342class TestPropertyKeyIs {343public:344// Constructor.345//346// TestPropertyKeyIs has NO default constructor.347explicit TestPropertyKeyIs(const std::string& key) : key_(key) {}348349// Returns true if and only if the test name of test property matches on key_.350bool operator()(const TestProperty& test_property) const {351return test_property.key() == key_;352}353354private:355std::string key_;356};357358// Class UnitTestOptions.359//360// This class contains functions for processing options the user361// specifies when running the tests. It has only static members.362//363// In most cases, the user can specify an option using either an364// environment variable or a command line flag. E.g. you can set the365// test filter using either GTEST_FILTER or --gtest_filter. If both366// the variable and the flag are present, the latter overrides the367// former.368class GTEST_API_ UnitTestOptions {369public:370// Functions for processing the gtest_output flag.371372// Returns the output format, or "" for normal printed output.373static std::string GetOutputFormat();374375// Returns the absolute path of the requested output file, or the376// default (test_detail.xml in the original working directory) if377// none was explicitly specified.378static std::string GetAbsolutePathToOutputFile();379380// Functions for processing the gtest_filter flag.381382// Returns true if and only if the user-specified filter matches the test383// suite name and the test name.384static bool FilterMatchesTest(const std::string& test_suite_name,385const std::string& test_name);386387#ifdef GTEST_OS_WINDOWS388// Function for supporting the gtest_catch_exception flag.389390// Returns EXCEPTION_EXECUTE_HANDLER if given SEH exception was handled, or391// EXCEPTION_CONTINUE_SEARCH otherwise.392// This function is useful as an __except condition.393static int GTestProcessSEH(DWORD seh_code, const char* location);394#endif // GTEST_OS_WINDOWS395396// Returns true if "name" matches the ':' separated list of glob-style397// filters in "filter".398static bool MatchesFilter(const std::string& name, const char* filter);399};400401#if GTEST_HAS_FILE_SYSTEM402// Returns the current application's name, removing directory path if that403// is present. Used by UnitTestOptions::GetOutputFile.404GTEST_API_ FilePath GetCurrentExecutableName();405#endif // GTEST_HAS_FILE_SYSTEM406407// The role interface for getting the OS stack trace as a string.408class OsStackTraceGetterInterface {409public:410OsStackTraceGetterInterface() = default;411virtual ~OsStackTraceGetterInterface() = default;412413// Returns the current OS stack trace as an std::string. Parameters:414//415// max_depth - the maximum number of stack frames to be included416// in the trace.417// skip_count - the number of top frames to be skipped; doesn't count418// against max_depth.419virtual std::string CurrentStackTrace(int max_depth, int skip_count) = 0;420421// UponLeavingGTest() should be called immediately before Google Test calls422// user code. It saves some information about the current stack that423// CurrentStackTrace() will use to find and hide Google Test stack frames.424virtual void UponLeavingGTest() = 0;425426// This string is inserted in place of stack frames that are part of427// Google Test's implementation.428static const char* const kElidedFramesMarker;429430private:431OsStackTraceGetterInterface(const OsStackTraceGetterInterface&) = delete;432OsStackTraceGetterInterface& operator=(const OsStackTraceGetterInterface&) =433delete;434};435436// A working implementation of the OsStackTraceGetterInterface interface.437class OsStackTraceGetter : public OsStackTraceGetterInterface {438public:439OsStackTraceGetter() = default;440441std::string CurrentStackTrace(int max_depth, int skip_count) override;442void UponLeavingGTest() override;443444private:445#ifdef GTEST_HAS_ABSL446Mutex mutex_; // Protects all internal state.447448// We save the stack frame below the frame that calls user code.449// We do this because the address of the frame immediately below450// the user code changes between the call to UponLeavingGTest()451// and any calls to the stack trace code from within the user code.452void* caller_frame_ = nullptr;453#endif // GTEST_HAS_ABSL454455OsStackTraceGetter(const OsStackTraceGetter&) = delete;456OsStackTraceGetter& operator=(const OsStackTraceGetter&) = delete;457};458459// Information about a Google Test trace point.460struct TraceInfo {461const char* file;462int line;463std::string message;464};465466// This is the default global test part result reporter used in UnitTestImpl.467// This class should only be used by UnitTestImpl.468class DefaultGlobalTestPartResultReporter469: public TestPartResultReporterInterface {470public:471explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test);472// Implements the TestPartResultReporterInterface. Reports the test part473// result in the current test.474void ReportTestPartResult(const TestPartResult& result) override;475476private:477UnitTestImpl* const unit_test_;478479DefaultGlobalTestPartResultReporter(480const DefaultGlobalTestPartResultReporter&) = delete;481DefaultGlobalTestPartResultReporter& operator=(482const DefaultGlobalTestPartResultReporter&) = delete;483};484485// This is the default per thread test part result reporter used in486// UnitTestImpl. This class should only be used by UnitTestImpl.487class DefaultPerThreadTestPartResultReporter488: public TestPartResultReporterInterface {489public:490explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test);491// Implements the TestPartResultReporterInterface. The implementation just492// delegates to the current global test part result reporter of *unit_test_.493void ReportTestPartResult(const TestPartResult& result) override;494495private:496UnitTestImpl* const unit_test_;497498DefaultPerThreadTestPartResultReporter(499const DefaultPerThreadTestPartResultReporter&) = delete;500DefaultPerThreadTestPartResultReporter& operator=(501const DefaultPerThreadTestPartResultReporter&) = delete;502};503504// The private implementation of the UnitTest class. We don't protect505// the methods under a mutex, as this class is not accessible by a506// user and the UnitTest class that delegates work to this class does507// proper locking.508class GTEST_API_ UnitTestImpl {509public:510explicit UnitTestImpl(UnitTest* parent);511virtual ~UnitTestImpl();512513// There are two different ways to register your own TestPartResultReporter.514// You can register your own reporter to listen either only for test results515// from the current thread or for results from all threads.516// By default, each per-thread test result reporter just passes a new517// TestPartResult to the global test result reporter, which registers the518// test part result for the currently running test.519520// Returns the global test part result reporter.521TestPartResultReporterInterface* GetGlobalTestPartResultReporter();522523// Sets the global test part result reporter.524void SetGlobalTestPartResultReporter(525TestPartResultReporterInterface* reporter);526527// Returns the test part result reporter for the current thread.528TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread();529530// Sets the test part result reporter for the current thread.531void SetTestPartResultReporterForCurrentThread(532TestPartResultReporterInterface* reporter);533534// Gets the number of successful test suites.535int successful_test_suite_count() const;536537// Gets the number of failed test suites.538int failed_test_suite_count() const;539540// Gets the number of all test suites.541int total_test_suite_count() const;542543// Gets the number of all test suites that contain at least one test544// that should run.545int test_suite_to_run_count() const;546547// Gets the number of successful tests.548int successful_test_count() const;549550// Gets the number of skipped tests.551int skipped_test_count() const;552553// Gets the number of failed tests.554int failed_test_count() const;555556// Gets the number of disabled tests that will be reported in the XML report.557int reportable_disabled_test_count() const;558559// Gets the number of disabled tests.560int disabled_test_count() const;561562// Gets the number of tests to be printed in the XML report.563int reportable_test_count() const;564565// Gets the number of all tests.566int total_test_count() const;567568// Gets the number of tests that should run.569int test_to_run_count() const;570571// Gets the time of the test program start, in ms from the start of the572// UNIX epoch.573TimeInMillis start_timestamp() const { return start_timestamp_; }574575// Gets the elapsed time, in milliseconds.576TimeInMillis elapsed_time() const { return elapsed_time_; }577578// Returns true if and only if the unit test passed (i.e. all test suites579// passed).580bool Passed() const { return !Failed(); }581582// Returns true if and only if the unit test failed (i.e. some test suite583// failed or something outside of all tests failed).584bool Failed() const {585return failed_test_suite_count() > 0 || ad_hoc_test_result()->Failed();586}587588// Gets the i-th test suite among all the test suites. i can range from 0 to589// total_test_suite_count() - 1. If i is not in that range, returns NULL.590const TestSuite* GetTestSuite(int i) const {591const int index = GetElementOr(test_suite_indices_, i, -1);592return index < 0 ? nullptr : test_suites_[static_cast<size_t>(i)];593}594595// Legacy API is deprecated but still available596#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_597const TestCase* GetTestCase(int i) const { return GetTestSuite(i); }598#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_599600// Gets the i-th test suite among all the test suites. i can range from 0 to601// total_test_suite_count() - 1. If i is not in that range, returns NULL.602TestSuite* GetMutableSuiteCase(int i) {603const int index = GetElementOr(test_suite_indices_, i, -1);604return index < 0 ? nullptr : test_suites_[static_cast<size_t>(index)];605}606607// Provides access to the event listener list.608TestEventListeners* listeners() { return &listeners_; }609610// Returns the TestResult for the test that's currently running, or611// the TestResult for the ad hoc test if no test is running.612TestResult* current_test_result();613614// Returns the TestResult for the ad hoc test.615const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; }616617// Sets the OS stack trace getter.618//619// Does nothing if the input and the current OS stack trace getter620// are the same; otherwise, deletes the old getter and makes the621// input the current getter.622void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter);623624// Returns the current OS stack trace getter if it is not NULL;625// otherwise, creates an OsStackTraceGetter, makes it the current626// getter, and returns it.627OsStackTraceGetterInterface* os_stack_trace_getter();628629// Returns the current OS stack trace as an std::string.630//631// The maximum number of stack frames to be included is specified by632// the gtest_stack_trace_depth flag. The skip_count parameter633// specifies the number of top frames to be skipped, which doesn't634// count against the number of frames to be included.635//636// For example, if Foo() calls Bar(), which in turn calls637// CurrentOsStackTraceExceptTop(1), Foo() will be included in the638// trace but Bar() and CurrentOsStackTraceExceptTop() won't.639std::string CurrentOsStackTraceExceptTop(int skip_count)640GTEST_NO_INLINE_ GTEST_NO_TAIL_CALL_;641642// Finds and returns a TestSuite with the given name. If one doesn't643// exist, creates one and returns it.644//645// Arguments:646//647// test_suite_name: name of the test suite648// type_param: the name of the test's type parameter, or NULL if649// this is not a typed or a type-parameterized test.650// set_up_tc: pointer to the function that sets up the test suite651// tear_down_tc: pointer to the function that tears down the test suite652TestSuite* GetTestSuite(const std::string& test_suite_name,653const char* type_param,654internal::SetUpTestSuiteFunc set_up_tc,655internal::TearDownTestSuiteFunc tear_down_tc);656657// Legacy API is deprecated but still available658#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_659TestCase* GetTestCase(const std::string& test_case_name,660const char* type_param,661internal::SetUpTestSuiteFunc set_up_tc,662internal::TearDownTestSuiteFunc tear_down_tc) {663return GetTestSuite(test_case_name, type_param, set_up_tc, tear_down_tc);664}665#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_666667// Adds a TestInfo to the unit test.668//669// Arguments:670//671// set_up_tc: pointer to the function that sets up the test suite672// tear_down_tc: pointer to the function that tears down the test suite673// test_info: the TestInfo object674void AddTestInfo(internal::SetUpTestSuiteFunc set_up_tc,675internal::TearDownTestSuiteFunc tear_down_tc,676TestInfo* test_info) {677#if GTEST_HAS_FILE_SYSTEM678// In order to support thread-safe death tests, we need to679// remember the original working directory when the test program680// was first invoked. We cannot do this in RUN_ALL_TESTS(), as681// the user may have changed the current directory before calling682// RUN_ALL_TESTS(). Therefore we capture the current directory in683// AddTestInfo(), which is called to register a TEST or TEST_F684// before main() is reached.685if (original_working_dir_.IsEmpty()) {686original_working_dir_ = FilePath::GetCurrentDir();687GTEST_CHECK_(!original_working_dir_.IsEmpty())688<< "Failed to get the current working directory.";689}690#endif // GTEST_HAS_FILE_SYSTEM691692GetTestSuite(test_info->test_suite_name_, test_info->type_param(),693set_up_tc, tear_down_tc)694->AddTestInfo(test_info);695}696697// Returns ParameterizedTestSuiteRegistry object used to keep track of698// value-parameterized tests and instantiate and register them.699internal::ParameterizedTestSuiteRegistry& parameterized_test_registry() {700return parameterized_test_registry_;701}702703std::set<std::string>* ignored_parameterized_test_suites() {704return &ignored_parameterized_test_suites_;705}706707// Returns TypeParameterizedTestSuiteRegistry object used to keep track of708// type-parameterized tests and instantiations of them.709internal::TypeParameterizedTestSuiteRegistry&710type_parameterized_test_registry() {711return type_parameterized_test_registry_;712}713714// Registers all parameterized tests defined using TEST_P and715// INSTANTIATE_TEST_SUITE_P, creating regular tests for each test/parameter716// combination. This method can be called more then once; it has guards717// protecting from registering the tests more then once. If718// value-parameterized tests are disabled, RegisterParameterizedTests is719// present but does nothing.720void RegisterParameterizedTests();721722// Runs all tests in this UnitTest object, prints the result, and723// returns true if all tests are successful. If any exception is724// thrown during a test, this test is considered to be failed, but725// the rest of the tests will still be run.726bool RunAllTests();727728// Clears the results of all tests, except the ad hoc tests.729void ClearNonAdHocTestResult() {730ForEach(test_suites_, TestSuite::ClearTestSuiteResult);731}732733// Clears the results of ad-hoc test assertions.734void ClearAdHocTestResult() { ad_hoc_test_result_.Clear(); }735736// Adds a TestProperty to the current TestResult object when invoked in a737// context of a test or a test suite, or to the global property set. If the738// result already contains a property with the same key, the value will be739// updated.740void RecordProperty(const TestProperty& test_property);741742enum ReactionToSharding { HONOR_SHARDING_PROTOCOL, IGNORE_SHARDING_PROTOCOL };743744// Matches the full name of each test against the user-specified745// filter to decide whether the test should run, then records the746// result in each TestSuite and TestInfo object.747// If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests748// based on sharding variables in the environment.749// Returns the number of tests that should run.750int FilterTests(ReactionToSharding shard_tests);751752// Prints the names of the tests matching the user-specified filter flag.753void ListTestsMatchingFilter();754755const TestSuite* current_test_suite() const { return current_test_suite_; }756TestInfo* current_test_info() { return current_test_info_; }757const TestInfo* current_test_info() const { return current_test_info_; }758759// Returns the vector of environments that need to be set-up/torn-down760// before/after the tests are run.761std::vector<Environment*>& environments() { return environments_; }762763// Getters for the per-thread Google Test trace stack.764std::vector<TraceInfo>& gtest_trace_stack() {765return *(gtest_trace_stack_.pointer());766}767const std::vector<TraceInfo>& gtest_trace_stack() const {768return gtest_trace_stack_.get();769}770771#ifdef GTEST_HAS_DEATH_TEST772void InitDeathTestSubprocessControlInfo() {773internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());774}775// Returns a pointer to the parsed --gtest_internal_run_death_test776// flag, or NULL if that flag was not specified.777// This information is useful only in a death test child process.778// Must not be called before a call to InitGoogleTest.779const InternalRunDeathTestFlag* internal_run_death_test_flag() const {780return internal_run_death_test_flag_.get();781}782783// Returns a pointer to the current death test factory.784internal::DeathTestFactory* death_test_factory() {785return death_test_factory_.get();786}787788void SuppressTestEventsIfInSubprocess();789790friend class ReplaceDeathTestFactory;791#endif // GTEST_HAS_DEATH_TEST792793// Initializes the event listener performing XML output as specified by794// UnitTestOptions. Must not be called before InitGoogleTest.795void ConfigureXmlOutput();796797#if GTEST_CAN_STREAM_RESULTS_798// Initializes the event listener for streaming test results to a socket.799// Must not be called before InitGoogleTest.800void ConfigureStreamingOutput();801#endif802803// Performs initialization dependent upon flag values obtained in804// ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to805// ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest806// this function is also called from RunAllTests. Since this function can be807// called more than once, it has to be idempotent.808void PostFlagParsingInit();809810// Gets the random seed used at the start of the current test iteration.811int random_seed() const { return random_seed_; }812813// Gets the random number generator.814internal::Random* random() { return &random_; }815816// Shuffles all test suites, and the tests within each test suite,817// making sure that death tests are still run first.818void ShuffleTests();819820// Restores the test suites and tests to their order before the first shuffle.821void UnshuffleTests();822823// Returns the value of GTEST_FLAG(catch_exceptions) at the moment824// UnitTest::Run() starts.825bool catch_exceptions() const { return catch_exceptions_; }826827private:828// Returns true if a warning should be issued if no tests match the test829// filter flag.830bool ShouldWarnIfNoTestsMatchFilter() const;831832struct CompareTestSuitesByPointer {833bool operator()(const TestSuite* lhs, const TestSuite* rhs) const {834return lhs->name_ < rhs->name_;835}836};837838friend class ::testing::UnitTest;839840// Used by UnitTest::Run() to capture the state of841// GTEST_FLAG(catch_exceptions) at the moment it starts.842void set_catch_exceptions(bool value) { catch_exceptions_ = value; }843844// Sets the TestSuite object for the test that's currently running.845void set_current_test_suite(TestSuite* a_current_test_suite) {846current_test_suite_ = a_current_test_suite;847}848849// Sets the TestInfo object for the test that's currently running. If850// current_test_info is NULL, the assertion results will be stored in851// ad_hoc_test_result_.852void set_current_test_info(TestInfo* a_current_test_info) {853current_test_info_ = a_current_test_info;854}855856// The UnitTest object that owns this implementation object.857UnitTest* const parent_;858859#if GTEST_HAS_FILE_SYSTEM860// The working directory when the first TEST() or TEST_F() was861// executed.862internal::FilePath original_working_dir_;863#endif // GTEST_HAS_FILE_SYSTEM864865// The default test part result reporters.866DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_;867DefaultPerThreadTestPartResultReporter868default_per_thread_test_part_result_reporter_;869870// Points to (but doesn't own) the global test part result reporter.871TestPartResultReporterInterface* global_test_part_result_reporter_;872873// Protects read and write access to global_test_part_result_reporter_.874internal::Mutex global_test_part_result_reporter_mutex_;875876// Points to (but doesn't own) the per-thread test part result reporter.877internal::ThreadLocal<TestPartResultReporterInterface*>878per_thread_test_part_result_reporter_;879880// The vector of environments that need to be set-up/torn-down881// before/after the tests are run.882std::vector<Environment*> environments_;883884// The vector of TestSuites in their original order. It owns the885// elements in the vector.886std::vector<TestSuite*> test_suites_;887888// The set of TestSuites by name.889std::unordered_map<std::string, TestSuite*> test_suites_by_name_;890891// Provides a level of indirection for the test suite list to allow892// easy shuffling and restoring the test suite order. The i-th893// element of this vector is the index of the i-th test suite in the894// shuffled order.895std::vector<int> test_suite_indices_;896897// ParameterizedTestRegistry object used to register value-parameterized898// tests.899internal::ParameterizedTestSuiteRegistry parameterized_test_registry_;900internal::TypeParameterizedTestSuiteRegistry901type_parameterized_test_registry_;902903// The set holding the name of parameterized904// test suites that may go uninstantiated.905std::set<std::string> ignored_parameterized_test_suites_;906907// Indicates whether RegisterParameterizedTests() has been called already.908bool parameterized_tests_registered_;909910// Index of the last death test suite registered. Initially -1.911int last_death_test_suite_;912913// This points to the TestSuite for the currently running test. It914// changes as Google Test goes through one test suite after another.915// When no test is running, this is set to NULL and Google Test916// stores assertion results in ad_hoc_test_result_. Initially NULL.917TestSuite* current_test_suite_;918919// This points to the TestInfo for the currently running test. It920// changes as Google Test goes through one test after another. When921// no test is running, this is set to NULL and Google Test stores922// assertion results in ad_hoc_test_result_. Initially NULL.923TestInfo* current_test_info_;924925// Normally, a user only writes assertions inside a TEST or TEST_F,926// or inside a function called by a TEST or TEST_F. Since Google927// Test keeps track of which test is current running, it can928// associate such an assertion with the test it belongs to.929//930// If an assertion is encountered when no TEST or TEST_F is running,931// Google Test attributes the assertion result to an imaginary "ad hoc"932// test, and records the result in ad_hoc_test_result_.933TestResult ad_hoc_test_result_;934935// The list of event listeners that can be used to track events inside936// Google Test.937TestEventListeners listeners_;938939// The OS stack trace getter. Will be deleted when the UnitTest940// object is destructed. By default, an OsStackTraceGetter is used,941// but the user can set this field to use a custom getter if that is942// desired.943OsStackTraceGetterInterface* os_stack_trace_getter_;944945// True if and only if PostFlagParsingInit() has been called.946bool post_flag_parse_init_performed_;947948// The random number seed used at the beginning of the test run.949int random_seed_;950951// Our random number generator.952internal::Random random_;953954// The time of the test program start, in ms from the start of the955// UNIX epoch.956TimeInMillis start_timestamp_;957958// How long the test took to run, in milliseconds.959TimeInMillis elapsed_time_;960961#ifdef GTEST_HAS_DEATH_TEST962// The decomposed components of the gtest_internal_run_death_test flag,963// parsed when RUN_ALL_TESTS is called.964std::unique_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;965std::unique_ptr<internal::DeathTestFactory> death_test_factory_;966#endif // GTEST_HAS_DEATH_TEST967968// A per-thread stack of traces created by the SCOPED_TRACE() macro.969internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_;970971// The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests()972// starts.973bool catch_exceptions_;974975UnitTestImpl(const UnitTestImpl&) = delete;976UnitTestImpl& operator=(const UnitTestImpl&) = delete;977}; // class UnitTestImpl978979// Convenience function for accessing the global UnitTest980// implementation object.981inline UnitTestImpl* GetUnitTestImpl() {982return UnitTest::GetInstance()->impl();983}984985#ifdef GTEST_USES_SIMPLE_RE986987// Internal helper functions for implementing the simple regular988// expression matcher.989GTEST_API_ bool IsInSet(char ch, const char* str);990GTEST_API_ bool IsAsciiDigit(char ch);991GTEST_API_ bool IsAsciiPunct(char ch);992GTEST_API_ bool IsRepeat(char ch);993GTEST_API_ bool IsAsciiWhiteSpace(char ch);994GTEST_API_ bool IsAsciiWordChar(char ch);995GTEST_API_ bool IsValidEscape(char ch);996GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch);997GTEST_API_ bool ValidateRegex(const char* regex);998GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str);999GTEST_API_ bool MatchRepetitionAndRegexAtHead(bool escaped, char ch,1000char repeat, const char* regex,1001const char* str);1002GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str);10031004#endif // GTEST_USES_SIMPLE_RE10051006// Parses the command line for Google Test flags, without initializing1007// other parts of Google Test.1008GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv);1009GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv);10101011#ifdef GTEST_HAS_DEATH_TEST10121013// Returns the message describing the last system error, regardless of the1014// platform.1015GTEST_API_ std::string GetLastErrnoDescription();10161017// Attempts to parse a string into a positive integer pointed to by the1018// number parameter. Returns true if that is possible.1019// GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use1020// it here.1021template <typename Integer>1022bool ParseNaturalNumber(const ::std::string& str, Integer* number) {1023// Fail fast if the given string does not begin with a digit;1024// this bypasses strtoXXX's "optional leading whitespace and plus1025// or minus sign" semantics, which are undesirable here.1026if (str.empty() || !IsDigit(str[0])) {1027return false;1028}1029errno = 0;10301031char* end;1032// BiggestConvertible is the largest integer type that system-provided1033// string-to-number conversion routines can return.1034using BiggestConvertible = unsigned long long; // NOLINT10351036const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10); // NOLINT1037const bool parse_success = *end == '\0' && errno == 0;10381039GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed));10401041const Integer result = static_cast<Integer>(parsed);1042if (parse_success && static_cast<BiggestConvertible>(result) == parsed) {1043*number = result;1044return true;1045}1046return false;1047}1048#endif // GTEST_HAS_DEATH_TEST10491050// TestResult contains some private methods that should be hidden from1051// Google Test user but are required for testing. This class allow our tests1052// to access them.1053//1054// This class is supplied only for the purpose of testing Google Test's own1055// constructs. Do not use it in user tests, either directly or indirectly.1056class TestResultAccessor {1057public:1058static void RecordProperty(TestResult* test_result,1059const std::string& xml_element,1060const TestProperty& property) {1061test_result->RecordProperty(xml_element, property);1062}10631064static void ClearTestPartResults(TestResult* test_result) {1065test_result->ClearTestPartResults();1066}10671068static const std::vector<testing::TestPartResult>& test_part_results(1069const TestResult& test_result) {1070return test_result.test_part_results();1071}1072};10731074#if GTEST_CAN_STREAM_RESULTS_10751076// Streams test results to the given port on the given host machine.1077class StreamingListener : public EmptyTestEventListener {1078public:1079// Abstract base class for writing strings to a socket.1080class AbstractSocketWriter {1081public:1082virtual ~AbstractSocketWriter() = default;10831084// Sends a string to the socket.1085virtual void Send(const std::string& message) = 0;10861087// Closes the socket.1088virtual void CloseConnection() {}10891090// Sends a string and a newline to the socket.1091void SendLn(const std::string& message) { Send(message + "\n"); }1092};10931094// Concrete class for actually writing strings to a socket.1095class SocketWriter : public AbstractSocketWriter {1096public:1097SocketWriter(const std::string& host, const std::string& port)1098: sockfd_(-1), host_name_(host), port_num_(port) {1099MakeConnection();1100}11011102~SocketWriter() override {1103if (sockfd_ != -1) CloseConnection();1104}11051106// Sends a string to the socket.1107void Send(const std::string& message) override {1108GTEST_CHECK_(sockfd_ != -1)1109<< "Send() can be called only when there is a connection.";11101111const auto len = static_cast<size_t>(message.length());1112if (write(sockfd_, message.c_str(), len) != static_cast<ssize_t>(len)) {1113GTEST_LOG_(WARNING) << "stream_result_to: failed to stream to "1114<< host_name_ << ":" << port_num_;1115}1116}11171118private:1119// Creates a client socket and connects to the server.1120void MakeConnection();11211122// Closes the socket.1123void CloseConnection() override {1124GTEST_CHECK_(sockfd_ != -1)1125<< "CloseConnection() can be called only when there is a connection.";11261127close(sockfd_);1128sockfd_ = -1;1129}11301131int sockfd_; // socket file descriptor1132const std::string host_name_;1133const std::string port_num_;11341135SocketWriter(const SocketWriter&) = delete;1136SocketWriter& operator=(const SocketWriter&) = delete;1137}; // class SocketWriter11381139// Escapes '=', '&', '%', and '\n' characters in str as "%xx".1140static std::string UrlEncode(const char* str);11411142StreamingListener(const std::string& host, const std::string& port)1143: socket_writer_(new SocketWriter(host, port)) {1144Start();1145}11461147explicit StreamingListener(AbstractSocketWriter* socket_writer)1148: socket_writer_(socket_writer) {1149Start();1150}11511152void OnTestProgramStart(const UnitTest& /* unit_test */) override {1153SendLn("event=TestProgramStart");1154}11551156void OnTestProgramEnd(const UnitTest& unit_test) override {1157// Note that Google Test current only report elapsed time for each1158// test iteration, not for the entire test program.1159SendLn("event=TestProgramEnd&passed=" + FormatBool(unit_test.Passed()));11601161// Notify the streaming server to stop.1162socket_writer_->CloseConnection();1163}11641165void OnTestIterationStart(const UnitTest& /* unit_test */,1166int iteration) override {1167SendLn("event=TestIterationStart&iteration=" +1168StreamableToString(iteration));1169}11701171void OnTestIterationEnd(const UnitTest& unit_test,1172int /* iteration */) override {1173SendLn("event=TestIterationEnd&passed=" + FormatBool(unit_test.Passed()) +1174"&elapsed_time=" + StreamableToString(unit_test.elapsed_time()) +1175"ms");1176}11771178// Note that "event=TestCaseStart" is a wire format and has to remain1179// "case" for compatibility1180void OnTestSuiteStart(const TestSuite& test_suite) override {1181SendLn(std::string("event=TestCaseStart&name=") + test_suite.name());1182}11831184// Note that "event=TestCaseEnd" is a wire format and has to remain1185// "case" for compatibility1186void OnTestSuiteEnd(const TestSuite& test_suite) override {1187SendLn("event=TestCaseEnd&passed=" + FormatBool(test_suite.Passed()) +1188"&elapsed_time=" + StreamableToString(test_suite.elapsed_time()) +1189"ms");1190}11911192void OnTestStart(const TestInfo& test_info) override {1193SendLn(std::string("event=TestStart&name=") + test_info.name());1194}11951196void OnTestEnd(const TestInfo& test_info) override {1197SendLn("event=TestEnd&passed=" +1198FormatBool((test_info.result())->Passed()) + "&elapsed_time=" +1199StreamableToString((test_info.result())->elapsed_time()) + "ms");1200}12011202void OnTestPartResult(const TestPartResult& test_part_result) override {1203const char* file_name = test_part_result.file_name();1204if (file_name == nullptr) file_name = "";1205SendLn("event=TestPartResult&file=" + UrlEncode(file_name) +1206"&line=" + StreamableToString(test_part_result.line_number()) +1207"&message=" + UrlEncode(test_part_result.message()));1208}12091210private:1211// Sends the given message and a newline to the socket.1212void SendLn(const std::string& message) { socket_writer_->SendLn(message); }12131214// Called at the start of streaming to notify the receiver what1215// protocol we are using.1216void Start() { SendLn("gtest_streaming_protocol_version=1.0"); }12171218std::string FormatBool(bool value) { return value ? "1" : "0"; }12191220const std::unique_ptr<AbstractSocketWriter> socket_writer_;12211222StreamingListener(const StreamingListener&) = delete;1223StreamingListener& operator=(const StreamingListener&) = delete;1224}; // class StreamingListener12251226#endif // GTEST_CAN_STREAM_RESULTS_12271228} // namespace internal1229} // namespace testing12301231GTEST_DISABLE_MSC_WARNINGS_POP_() // 425112321233#endif // GOOGLETEST_SRC_GTEST_INTERNAL_INL_H_123412351236