// Copyright 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // The Google C++ Testing and Mocking Framework (Google Test) #include "gtest/gtest.h" #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <wchar.h> #include <wctype.h> #include <algorithm> #include <chrono> // NOLINT #include <cmath> #include <csignal> // NOLINT: raise(3) is used on some platforms #include <cstdint> #include <cstdlib> #include <cstring> #include <initializer_list> #include <iomanip> #include <ios> #include <iostream> #include <iterator> #include <limits> #include <list> #include <map> #include <ostream> // NOLINT #include <set> #include <sstream> #include <unordered_set> #include <utility> #include <vector> #include "gtest/gtest-assertion-result.h" #include "gtest/gtest-spi.h" #include "gtest/internal/custom/gtest.h" #include "gtest/internal/gtest-port.h" #ifdef GTEST_OS_LINUX #include <fcntl.h> // NOLINT #include <limits.h> // NOLINT #include <sched.h> // NOLINT // Declares vsnprintf(). This header is not available on Windows. #include <strings.h> // NOLINT #include <sys/mman.h> // NOLINT #include <sys/time.h> // NOLINT #include <unistd.h> // NOLINT #include <string> #elif defined(GTEST_OS_ZOS) #include <sys/time.h> // NOLINT // On z/OS we additionally need strings.h for strcasecmp. #include <strings.h> // NOLINT #elif defined(GTEST_OS_WINDOWS_MOBILE) // We are on Windows CE. #include <windows.h> // NOLINT #undef min #elif defined(GTEST_OS_WINDOWS) // We are on Windows proper. #include <windows.h> // NOLINT #undef min #ifdef _MSC_VER #include <crtdbg.h> // NOLINT #endif #include <io.h> // NOLINT #include <sys/stat.h> // NOLINT #include <sys/timeb.h> // NOLINT #include <sys/types.h> // NOLINT #ifdef GTEST_OS_WINDOWS_MINGW #include <sys/time.h> // NOLINT #endif // GTEST_OS_WINDOWS_MINGW #else // cpplint thinks that the header is already included, so we want to // silence it. #include <sys/time.h> // NOLINT #include <unistd.h> // NOLINT #endif // GTEST_OS_LINUX #if GTEST_HAS_EXCEPTIONS #include <stdexcept> #endif #if GTEST_CAN_STREAM_RESULTS_ #include <arpa/inet.h> // NOLINT #include <netdb.h> // NOLINT #include <sys/socket.h> // NOLINT #include <sys/types.h> // NOLINT #endif #include "src/gtest-internal-inl.h" #ifdef GTEST_OS_WINDOWS #define vsnprintf … #endif // GTEST_OS_WINDOWS #ifdef GTEST_OS_MAC #ifndef GTEST_OS_IOS #include <crt_externs.h> #endif #endif #ifdef GTEST_HAS_ABSL #include "absl/container/flat_hash_set.h" #include "absl/debugging/failure_signal_handler.h" #include "absl/debugging/stacktrace.h" #include "absl/debugging/symbolize.h" #include "absl/flags/parse.h" #include "absl/flags/usage.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_replace.h" #include "absl/strings/string_view.h" #include "absl/strings/strip.h" #endif // GTEST_HAS_ABSL // Checks builtin compiler feature |x| while avoiding an extra layer of #ifdefs // at the callsite. #if defined(__has_builtin) #define GTEST_HAS_BUILTIN(x) … #else #define GTEST_HAS_BUILTIN … #endif // defined(__has_builtin) #if defined(GTEST_HAS_ABSL) && !defined(GTEST_NO_ABSL_FLAGS) #define GTEST_HAS_ABSL_FLAGS #endif namespace testing { CountIf; ForEach; GetElementOr; Shuffle; // Constants. // A test whose test suite name or test name matches this filter is // disabled and not run. static const char kDisableTestFilter[] = …; // A test suite whose name matches this filter is considered a death // test suite and will be run before test suites whose name doesn't // match this filter. static const char kDeathTestSuiteFilter[] = …; // A test filter that matches everything. static const char kUniversalFilter[] = …; // The default output format. static const char kDefaultOutputFormat[] = …; // The default output file. static const char kDefaultOutputFile[] = …; // The environment variable name for the test shard index. static const char kTestShardIndex[] = …; // The environment variable name for the total number of test shards. static const char kTestTotalShards[] = …; // The environment variable name for the test shard status file. static const char kTestShardStatusFile[] = …; namespace internal { // The text used in failure messages to indicate the start of the // stack trace. const char kStackTraceMarker[] = …; // g_help_flag is true if and only if the --help flag or an equivalent form // is specified on the command line. bool g_help_flag = …; #if GTEST_HAS_FILE_SYSTEM // Utility function to Open File for Writing static FILE* OpenFileForWriting(const std::string& output_file) { … } #endif // GTEST_HAS_FILE_SYSTEM } // namespace internal // Bazel passes in the argument to '--test_filter' via the TESTBRIDGE_TEST_ONLY // environment variable. static const char* GetDefaultFilter() { … } // Bazel passes in the argument to '--test_runner_fail_fast' via the // TESTBRIDGE_TEST_RUNNER_FAIL_FAST environment variable. static bool GetDefaultFailFast() { … } } // namespace testing GTEST_DEFINE_bool_( fail_fast, testing::internal::BoolFromGTestEnv("fail_fast", testing::GetDefaultFailFast()), "True if and only if a test failure should stop further test execution."); GTEST_DEFINE_bool_( also_run_disabled_tests, testing::internal::BoolFromGTestEnv("also_run_disabled_tests", false), "Run disabled tests too, in addition to the tests normally being run."); GTEST_DEFINE_bool_( break_on_failure, testing::internal::BoolFromGTestEnv("break_on_failure", false), "True if and only if a failed assertion should be a debugger " "break-point."); GTEST_DEFINE_bool_(catch_exceptions, testing::internal::BoolFromGTestEnv("catch_exceptions", true), "True if and only if " GTEST_NAME_ " should catch exceptions and treat them as test failures."); GTEST_DEFINE_string_( color, testing::internal::StringFromGTestEnv("color", "auto"), "Whether to use colors in the output. Valid values: yes, no, " "and auto. 'auto' means to use colors if the output is " "being sent to a terminal and the TERM environment variable " "is set to a terminal type that supports colors."); GTEST_DEFINE_string_( filter, testing::internal::StringFromGTestEnv("filter", testing::GetDefaultFilter()), "A colon-separated list of glob (not regex) patterns " "for filtering the tests to run, optionally followed by a " "'-' and a : separated list of negative patterns (tests to " "exclude). A test is run if it matches one of the positive " "patterns and does not match any of the negative patterns."); GTEST_DEFINE_bool_( install_failure_signal_handler, testing::internal::BoolFromGTestEnv("install_failure_signal_handler", false), "If true and supported on the current platform, " GTEST_NAME_ " should " "install a signal handler that dumps debugging information when fatal " "signals are raised."); GTEST_DEFINE_bool_(list_tests, false, "List all tests without running them."); // The net priority order after flag processing is thus: // --gtest_output command line flag // GTEST_OUTPUT environment variable // XML_OUTPUT_FILE environment variable // '' GTEST_DEFINE_string_( output, testing::internal::StringFromGTestEnv( "output", testing::internal::OutputFlagAlsoCheckEnvVar().c_str()), "A format (defaults to \"xml\" but can be specified to be \"json\"), " "optionally followed by a colon and an output file name or directory. " "A directory is indicated by a trailing pathname separator. " "Examples: \"xml:filename.xml\", \"xml::directoryname/\". " "If a directory is specified, output files will be created " "within that directory, with file-names based on the test " "executable's name and, if necessary, made unique by adding " "digits."); GTEST_DEFINE_bool_( brief, testing::internal::BoolFromGTestEnv("brief", false), "True if only test failures should be displayed in text output."); GTEST_DEFINE_bool_(print_time, testing::internal::BoolFromGTestEnv("print_time", true), "True if and only if " GTEST_NAME_ " should display elapsed time in text output."); GTEST_DEFINE_bool_(print_utf8, testing::internal::BoolFromGTestEnv("print_utf8", true), "True if and only if " GTEST_NAME_ " prints UTF8 characters as text."); GTEST_DEFINE_int32_( random_seed, testing::internal::Int32FromGTestEnv("random_seed", 0), "Random number seed to use when shuffling test orders. Must be in range " "[1, 99999], or 0 to use a seed based on the current time."); GTEST_DEFINE_int32_( repeat, testing::internal::Int32FromGTestEnv("repeat", 1), "How many times to repeat each test. Specify a negative number " "for repeating forever. Useful for shaking out flaky tests."); GTEST_DEFINE_bool_( recreate_environments_when_repeating, testing::internal::BoolFromGTestEnv("recreate_environments_when_repeating", false), "Controls whether global test environments are recreated for each repeat " "of the tests. If set to false the global test environments are only set " "up once, for the first iteration, and only torn down once, for the last. " "Useful for shaking out flaky tests with stable, expensive test " "environments. If --gtest_repeat is set to a negative number, meaning " "there is no last run, the environments will always be recreated to avoid " "leaks."); GTEST_DEFINE_bool_(show_internal_stack_frames, false, "True if and only if " GTEST_NAME_ " should include internal stack frames when " "printing test failure stack traces."); GTEST_DEFINE_bool_(shuffle, testing::internal::BoolFromGTestEnv("shuffle", false), "True if and only if " GTEST_NAME_ " should randomize tests' order on every run."); GTEST_DEFINE_int32_( stack_trace_depth, testing::internal::Int32FromGTestEnv("stack_trace_depth", testing::kMaxStackTraceDepth), "The maximum number of stack frames to print when an " "assertion fails. The valid range is 0 through 100, inclusive."); GTEST_DEFINE_string_( stream_result_to, testing::internal::StringFromGTestEnv("stream_result_to", ""), "This flag specifies the host name and the port number on which to stream " "test results. Example: \"localhost:555\". The flag is effective only on " "Linux and macOS."); GTEST_DEFINE_bool_( throw_on_failure, testing::internal::BoolFromGTestEnv("throw_on_failure", false), "When this flag is specified, a failed assertion will throw an exception " "if exceptions are enabled or exit the program with a non-zero code " "otherwise. For use with an external test framework."); #if GTEST_USE_OWN_FLAGFILE_FLAG_ GTEST_DEFINE_string_( flagfile, testing::internal::StringFromGTestEnv("flagfile", ""), "This flag specifies the flagfile to read command-line flags from."); #endif // GTEST_USE_OWN_FLAGFILE_FLAG_ namespace testing { namespace internal { const uint32_t Random::kMaxRange; // Generates a random number from [0, range), using a Linear // Congruential Generator (LCG). Crashes if 'range' is 0 or greater // than kMaxRange. uint32_t Random::Generate(uint32_t range) { … } // GTestIsInitialized() returns true if and only if the user has initialized // Google Test. Useful for catching the user mistake of not initializing // Google Test before calling RUN_ALL_TESTS(). static bool GTestIsInitialized() { … } // Iterates over a vector of TestSuites, keeping a running sum of the // results of calling a given int-returning method on each. // Returns the sum. static int SumOverTestSuiteList(const std::vector<TestSuite*>& case_list, int (TestSuite::*method)() const) { … } // Returns true if and only if the test suite passed. static bool TestSuitePassed(const TestSuite* test_suite) { … } // Returns true if and only if the test suite failed. static bool TestSuiteFailed(const TestSuite* test_suite) { … } // Returns true if and only if test_suite contains at least one test that // should run. static bool ShouldRunTestSuite(const TestSuite* test_suite) { … } namespace { // Returns true if test part results of type `type` should include a stack // trace. bool ShouldEmitStackTraceForResultType(TestPartResult::Type type) { … } } // namespace // AssertHelper constructor. AssertHelper::AssertHelper(TestPartResult::Type type, const char* file, int line, const char* message) : … { … } AssertHelper::~AssertHelper() { … } // Message assignment, for assertion streaming support. void AssertHelper::operator=(const Message& message) const { … } namespace { // When TEST_P is found without a matching INSTANTIATE_TEST_SUITE_P // to creates test cases for it, a synthetic test case is // inserted to report ether an error or a log message. // // This configuration bit will likely be removed at some point. constexpr bool kErrorOnUninstantiatedParameterizedTest = …; constexpr bool kErrorOnUninstantiatedTypeParameterizedTest = …; // A test that fails at a given file/line location with a given message. class FailureTest : public Test { … }; } // namespace std::set<std::string>* GetIgnoredParameterizedTestSuites() { … } // Add a given test_suit to the list of them allow to go un-instantiated. MarkAsIgnored::MarkAsIgnored(const char* test_suite) { … } // If this parameterized test suite has no instantiations (and that // has not been marked as okay), emit a test case reporting that. void InsertSyntheticTestCase(const std::string& name, CodeLocation location, bool has_test_p) { … } void RegisterTypeParameterizedTestSuite(const char* test_suite_name, CodeLocation code_location) { … } void RegisterTypeParameterizedTestSuiteInstantiation(const char* case_name) { … } void TypeParameterizedTestSuiteRegistry::RegisterTestSuite( const char* test_suite_name, CodeLocation code_location) { … } void TypeParameterizedTestSuiteRegistry::RegisterInstantiation( const char* test_suite_name) { … } void TypeParameterizedTestSuiteRegistry::CheckForInstantiations() { … } // A copy of all command line arguments. Set by InitGoogleTest(). static ::std::vector<std::string> g_argvs; ::std::vector<std::string> GetArgvs() { … } #if GTEST_HAS_FILE_SYSTEM // Returns the current application's name, removing directory path if that // is present. FilePath GetCurrentExecutableName() { … } #endif // GTEST_HAS_FILE_SYSTEM // Functions for processing the gtest_output flag. // Returns the output format, or "" for normal printed output. std::string UnitTestOptions::GetOutputFormat() { … } #if GTEST_HAS_FILE_SYSTEM // Returns the name of the requested output file, or the default if none // was explicitly specified. std::string UnitTestOptions::GetAbsolutePathToOutputFile() { … } #endif // GTEST_HAS_FILE_SYSTEM // Returns true if and only if the wildcard pattern matches the string. Each // pattern consists of regular characters, single-character wildcards (?), and // multi-character wildcards (*). // // This function implements a linear-time string globbing algorithm based on // https://research.swtch.com/glob. static bool PatternMatchesString(const std::string& name_str, const char* pattern, const char* pattern_end) { … } namespace { bool IsGlobPattern(const std::string& pattern) { … } class UnitTestFilter { … }; class PositiveAndNegativeUnitTestFilter { … }; } // namespace bool UnitTestOptions::MatchesFilter(const std::string& name_str, const char* filter) { … } // Returns true if and only if the user-specified filter matches the test // suite name and the test name. bool UnitTestOptions::FilterMatchesTest(const std::string& test_suite_name, const std::string& test_name) { … } #if GTEST_HAS_SEH static std::string FormatSehExceptionMessage(DWORD exception_code, const char* location) { Message message; message << "SEH exception with code 0x" << std::setbase(16) << exception_code << std::setbase(10) << " thrown in " << location << "."; return message.GetString(); } int UnitTestOptions::GTestProcessSEH(DWORD seh_code, const char* location) { // Google Test should handle a SEH exception if: // 1. the user wants it to, AND // 2. this is not a breakpoint exception or stack overflow, AND // 3. this is not a C++ exception (VC++ implements them via SEH, // apparently). // // SEH exception code for C++ exceptions. // (see https://support.microsoft.com/kb/185294 for more information). const DWORD kCxxExceptionCode = 0xe06d7363; if (!GTEST_FLAG_GET(catch_exceptions) || seh_code == kCxxExceptionCode || seh_code == EXCEPTION_BREAKPOINT || seh_code == EXCEPTION_STACK_OVERFLOW) { return EXCEPTION_CONTINUE_SEARCH; // Don't handle these exceptions } internal::ReportFailureInUnknownLocation( TestPartResult::kFatalFailure, FormatSehExceptionMessage(seh_code, location) + "\n" "Stack trace:\n" + ::testing::internal::GetCurrentOsStackTraceExceptTop(1)); return EXCEPTION_EXECUTE_HANDLER; } #endif // GTEST_HAS_SEH } // namespace internal // The c'tor sets this object as the test part result reporter used by // Google Test. The 'result' parameter specifies where to report the // results. Intercepts only failures from the current thread. ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter( TestPartResultArray* result) : … { … } // The c'tor sets this object as the test part result reporter used by // Google Test. The 'result' parameter specifies where to report the // results. ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter( InterceptMode intercept_mode, TestPartResultArray* result) : … { … } void ScopedFakeTestPartResultReporter::Init() { … } // The d'tor restores the test part result reporter used by Google Test // before. ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() { … } // Increments the test part result count and remembers the result. // This method is from the TestPartResultReporterInterface interface. void ScopedFakeTestPartResultReporter::ReportTestPartResult( const TestPartResult& result) { … } namespace internal { // Returns the type ID of ::testing::Test. We should always call this // instead of GetTypeId< ::testing::Test>() to get the type ID of // testing::Test. This is to work around a suspected linker bug when // using Google Test as a framework on Mac OS X. The bug causes // GetTypeId< ::testing::Test>() to return different values depending // on whether the call is from the Google Test framework itself or // from user test code. GetTestTypeId() is guaranteed to always // return the same value, as it always calls GetTypeId<>() from the // gtest.cc, which is within the Google Test framework. TypeId GetTestTypeId() { … } // The value of GetTestTypeId() as seen from within the Google Test // library. This is solely for testing GetTestTypeId(). extern const TypeId kTestTypeIdInGoogleTest = …; // This predicate-formatter checks that 'results' contains a test part // failure of the given type and that the failure message contains the // given substring. static AssertionResult HasOneFailure(const char* /* results_expr */, const char* /* type_expr */, const char* /* substr_expr */, const TestPartResultArray& results, TestPartResult::Type type, const std::string& substr) { … } // The constructor of SingleFailureChecker remembers where to look up // test part results, what type of failure we expect, and what // substring the failure message should contain. SingleFailureChecker::SingleFailureChecker(const TestPartResultArray* results, TestPartResult::Type type, const std::string& substr) : … { … } // The destructor of SingleFailureChecker verifies that the given // TestPartResultArray contains exactly one failure that has the given // type and contains the given substring. If that's not the case, a // non-fatal failure will be generated. SingleFailureChecker::~SingleFailureChecker() { … } DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter( UnitTestImpl* unit_test) : … { … } void DefaultGlobalTestPartResultReporter::ReportTestPartResult( const TestPartResult& result) { … } DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter( UnitTestImpl* unit_test) : … { … } void DefaultPerThreadTestPartResultReporter::ReportTestPartResult( const TestPartResult& result) { … } // Returns the global test part result reporter. TestPartResultReporterInterface* UnitTestImpl::GetGlobalTestPartResultReporter() { … } // Sets the global test part result reporter. void UnitTestImpl::SetGlobalTestPartResultReporter( TestPartResultReporterInterface* reporter) { … } // Returns the test part result reporter for the current thread. TestPartResultReporterInterface* UnitTestImpl::GetTestPartResultReporterForCurrentThread() { … } // Sets the test part result reporter for the current thread. void UnitTestImpl::SetTestPartResultReporterForCurrentThread( TestPartResultReporterInterface* reporter) { … } // Gets the number of successful test suites. int UnitTestImpl::successful_test_suite_count() const { … } // Gets the number of failed test suites. int UnitTestImpl::failed_test_suite_count() const { … } // Gets the number of all test suites. int UnitTestImpl::total_test_suite_count() const { … } // Gets the number of all test suites that contain at least one test // that should run. int UnitTestImpl::test_suite_to_run_count() const { … } // Gets the number of successful tests. int UnitTestImpl::successful_test_count() const { … } // Gets the number of skipped tests. int UnitTestImpl::skipped_test_count() const { … } // Gets the number of failed tests. int UnitTestImpl::failed_test_count() const { … } // Gets the number of disabled tests that will be reported in the XML report. int UnitTestImpl::reportable_disabled_test_count() const { … } // Gets the number of disabled tests. int UnitTestImpl::disabled_test_count() const { … } // Gets the number of tests to be printed in the XML report. int UnitTestImpl::reportable_test_count() const { … } // Gets the number of all tests. int UnitTestImpl::total_test_count() const { … } // Gets the number of tests that should run. int UnitTestImpl::test_to_run_count() const { … } // Returns the current OS stack trace as an std::string. // // The maximum number of stack frames to be included is specified by // the gtest_stack_trace_depth flag. The skip_count parameter // specifies the number of top frames to be skipped, which doesn't // count against the number of frames to be included. // // For example, if Foo() calls Bar(), which in turn calls // CurrentOsStackTraceExceptTop(1), Foo() will be included in the // trace but Bar() and CurrentOsStackTraceExceptTop() won't. std::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) { … } // A helper class for measuring elapsed times. class Timer { … }; // Returns a timestamp as milliseconds since the epoch. Note this time may jump // around subject to adjustments by the system, to measure elapsed time use // Timer instead. TimeInMillis GetTimeInMillis() { … } // Utilities // class String. #ifdef GTEST_OS_WINDOWS_MOBILE // Creates a UTF-16 wide string from the given ANSI string, allocating // memory using new. The caller is responsible for deleting the return // value using delete[]. Returns the wide string, or NULL if the // input is NULL. LPCWSTR String::AnsiToUtf16(const char* ansi) { if (!ansi) return nullptr; const int length = strlen(ansi); const int unicode_length = MultiByteToWideChar(CP_ACP, 0, ansi, length, nullptr, 0); WCHAR* unicode = new WCHAR[unicode_length + 1]; MultiByteToWideChar(CP_ACP, 0, ansi, length, unicode, unicode_length); unicode[unicode_length] = 0; return unicode; } // Creates an ANSI string from the given wide string, allocating // memory using new. The caller is responsible for deleting the return // value using delete[]. Returns the ANSI string, or NULL if the // input is NULL. const char* String::Utf16ToAnsi(LPCWSTR utf16_str) { if (!utf16_str) return nullptr; const int ansi_length = WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, nullptr, 0, nullptr, nullptr); char* ansi = new char[ansi_length + 1]; WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, ansi, ansi_length, nullptr, nullptr); ansi[ansi_length] = 0; return ansi; } #endif // GTEST_OS_WINDOWS_MOBILE // Compares two C strings. Returns true if and only if they have the same // content. // // Unlike strcmp(), this function can handle NULL argument(s). A NULL // C string is considered different to any non-NULL C string, // including the empty string. bool String::CStringEquals(const char* lhs, const char* rhs) { … } #if GTEST_HAS_STD_WSTRING // Converts an array of wide chars to a narrow string using the UTF-8 // encoding, and streams the result to the given Message object. static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length, Message* msg) { … } #endif // GTEST_HAS_STD_WSTRING void SplitString(const ::std::string& str, char delimiter, ::std::vector< ::std::string>* dest) { … } } // namespace internal // Constructs an empty Message. // We allocate the stringstream separately because otherwise each use of // ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's // stack frame leading to huge stack frames in some cases; gcc does not reuse // the stack space. Message::Message() : … { … } // These two overloads allow streaming a wide C string to a Message // using the UTF-8 encoding. Message& Message::operator<<(const wchar_t* wide_c_str) { … } Message& Message::operator<<(wchar_t* wide_c_str) { … } #if GTEST_HAS_STD_WSTRING // Converts the given wide string to a narrow string using the UTF-8 // encoding, and streams the result to this Message object. Message& Message::operator<<(const ::std::wstring& wstr) { … } #endif // GTEST_HAS_STD_WSTRING // Gets the text streamed to this object so far as an std::string. // Each '\0' character in the buffer is replaced with "\\0". std::string Message::GetString() const { … } namespace internal { namespace edit_distance { std::vector<EditType> CalculateOptimalEdits(const std::vector<size_t>& left, const std::vector<size_t>& right) { … } namespace { // Helper class to convert string into ids with deduplication. class InternalStrings { … }; } // namespace std::vector<EditType> CalculateOptimalEdits( const std::vector<std::string>& left, const std::vector<std::string>& right) { … } namespace { // Helper class that holds the state for one hunk and prints it out to the // stream. // It reorders adds/removes when possible to group all removes before all // adds. It also adds the hunk header before printint into the stream. class Hunk { … }; } // namespace // Create a list of diff hunks in Unified diff format. // Each hunk has a header generated by PrintHeader above plus a body with // lines prefixed with ' ' for no change, '-' for deletion and '+' for // addition. // 'context' represents the desired unchanged prefix/suffix around the diff. // If two hunks are close enough that their contexts overlap, then they are // joined into one hunk. std::string CreateUnifiedDiff(const std::vector<std::string>& left, const std::vector<std::string>& right, size_t context) { … } } // namespace edit_distance namespace { // The string representation of the values received in EqFailure() are already // escaped. Split them on escaped '\n' boundaries. Leave all other escaped // characters the same. std::vector<std::string> SplitEscapedString(const std::string& str) { … } } // namespace // Constructs and returns the message for an equality assertion // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure. // // The first four parameters are the expressions used in the assertion // and their values, as strings. For example, for ASSERT_EQ(foo, bar) // where foo is 5 and bar is 6, we have: // // lhs_expression: "foo" // rhs_expression: "bar" // lhs_value: "5" // rhs_value: "6" // // The ignoring_case parameter is true if and only if the assertion is a // *_STRCASEEQ*. When it's true, the string "Ignoring case" will // be inserted into the message. AssertionResult EqFailure(const char* lhs_expression, const char* rhs_expression, const std::string& lhs_value, const std::string& rhs_value, bool ignoring_case) { … } // Constructs a failure message for Boolean assertions such as EXPECT_TRUE. std::string GetBoolAssertionFailureMessage( const AssertionResult& assertion_result, const char* expression_text, const char* actual_predicate_value, const char* expected_predicate_value) { … } // Helper function for implementing ASSERT_NEAR. AssertionResult DoubleNearPredFormat(const char* expr1, const char* expr2, const char* abs_error_expr, double val1, double val2, double abs_error) { … } // Helper template for implementing FloatLE() and DoubleLE(). template <typename RawType> AssertionResult FloatingPointLE(const char* expr1, const char* expr2, RawType val1, RawType val2) { … } } // namespace internal // Asserts that val1 is less than, or almost equal to, val2. Fails // otherwise. In particular, it fails if either val1 or val2 is NaN. AssertionResult FloatLE(const char* expr1, const char* expr2, float val1, float val2) { … } // Asserts that val1 is less than, or almost equal to, val2. Fails // otherwise. In particular, it fails if either val1 or val2 is NaN. AssertionResult DoubleLE(const char* expr1, const char* expr2, double val1, double val2) { … } namespace internal { // The helper function for {ASSERT|EXPECT}_STREQ. AssertionResult CmpHelperSTREQ(const char* lhs_expression, const char* rhs_expression, const char* lhs, const char* rhs) { … } // The helper function for {ASSERT|EXPECT}_STRCASEEQ. AssertionResult CmpHelperSTRCASEEQ(const char* lhs_expression, const char* rhs_expression, const char* lhs, const char* rhs) { … } // The helper function for {ASSERT|EXPECT}_STRNE. AssertionResult CmpHelperSTRNE(const char* s1_expression, const char* s2_expression, const char* s1, const char* s2) { … } // The helper function for {ASSERT|EXPECT}_STRCASENE. AssertionResult CmpHelperSTRCASENE(const char* s1_expression, const char* s2_expression, const char* s1, const char* s2) { … } } // namespace internal namespace { // Helper functions for implementing IsSubString() and IsNotSubstring(). // This group of overloaded functions return true if and only if needle // is a substring of haystack. NULL is considered a substring of // itself only. bool IsSubstringPred(const char* needle, const char* haystack) { … } bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) { … } // StringType here can be either ::std::string or ::std::wstring. template <typename StringType> bool IsSubstringPred(const StringType& needle, const StringType& haystack) { … } // This function implements either IsSubstring() or IsNotSubstring(), // depending on the value of the expected_to_be_substring parameter. // StringType here can be const char*, const wchar_t*, ::std::string, // or ::std::wstring. template <typename StringType> AssertionResult IsSubstringImpl(bool expected_to_be_substring, const char* needle_expr, const char* haystack_expr, const StringType& needle, const StringType& haystack) { … } } // namespace // IsSubstring() and IsNotSubstring() check whether needle is a // substring of haystack (NULL is considered a substring of itself // only), and return an appropriate error message when they fail. AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr, const char* needle, const char* haystack) { … } AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr, const wchar_t* needle, const wchar_t* haystack) { … } AssertionResult IsNotSubstring(const char* needle_expr, const char* haystack_expr, const char* needle, const char* haystack) { … } AssertionResult IsNotSubstring(const char* needle_expr, const char* haystack_expr, const wchar_t* needle, const wchar_t* haystack) { … } AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr, const ::std::string& needle, const ::std::string& haystack) { … } AssertionResult IsNotSubstring(const char* needle_expr, const char* haystack_expr, const ::std::string& needle, const ::std::string& haystack) { … } #if GTEST_HAS_STD_WSTRING AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr, const ::std::wstring& needle, const ::std::wstring& haystack) { … } AssertionResult IsNotSubstring(const char* needle_expr, const char* haystack_expr, const ::std::wstring& needle, const ::std::wstring& haystack) { … } #endif // GTEST_HAS_STD_WSTRING namespace internal { #ifdef GTEST_OS_WINDOWS namespace { // Helper function for IsHRESULT{SuccessFailure} predicates AssertionResult HRESULTFailureHelper(const char* expr, const char* expected, long hr) { // NOLINT #if defined(GTEST_OS_WINDOWS_MOBILE) || defined(GTEST_OS_WINDOWS_TV_TITLE) // Windows CE doesn't support FormatMessage. const char error_text[] = ""; #else // Looks up the human-readable system message for the HRESULT code // and since we're not passing any params to FormatMessage, we don't // want inserts expanded. const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS; const DWORD kBufSize = 4096; // Gets the system's human readable message string for this HRESULT. char error_text[kBufSize] = {'\0'}; DWORD message_length = ::FormatMessageA(kFlags, 0, // no source, we're asking system static_cast<DWORD>(hr), // the error 0, // no line width restrictions error_text, // output buffer kBufSize, // buf size nullptr); // no arguments for inserts // Trims tailing white space (FormatMessage leaves a trailing CR-LF) for (; message_length && IsSpace(error_text[message_length - 1]); --message_length) { error_text[message_length - 1] = '\0'; } #endif // GTEST_OS_WINDOWS_MOBILE const std::string error_hex("0x" + String::FormatHexInt(hr)); return ::testing::AssertionFailure() << "Expected: " << expr << " " << expected << ".\n" << " Actual: " << error_hex << " " << error_text << "\n"; } } // namespace AssertionResult IsHRESULTSuccess(const char* expr, long hr) { // NOLINT if (SUCCEEDED(hr)) { return AssertionSuccess(); } return HRESULTFailureHelper(expr, "succeeds", hr); } AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT if (FAILED(hr)) { return AssertionSuccess(); } return HRESULTFailureHelper(expr, "fails", hr); } #endif // GTEST_OS_WINDOWS // Utility functions for encoding Unicode text (wide strings) in // UTF-8. // A Unicode code-point can have up to 21 bits, and is encoded in UTF-8 // like this: // // Code-point length Encoding // 0 - 7 bits 0xxxxxxx // 8 - 11 bits 110xxxxx 10xxxxxx // 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx // 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx // The maximum code-point a one-byte UTF-8 sequence can represent. constexpr uint32_t kMaxCodePoint1 = …; // The maximum code-point a two-byte UTF-8 sequence can represent. constexpr uint32_t kMaxCodePoint2 = …; // The maximum code-point a three-byte UTF-8 sequence can represent. constexpr uint32_t kMaxCodePoint3 = …; // The maximum code-point a four-byte UTF-8 sequence can represent. constexpr uint32_t kMaxCodePoint4 = …; // Chops off the n lowest bits from a bit pattern. Returns the n // lowest bits. As a side effect, the original bit pattern will be // shifted to the right by n bits. inline uint32_t ChopLowBits(uint32_t* bits, int n) { … } // Converts a Unicode code point to a narrow string in UTF-8 encoding. // code_point parameter is of type uint32_t because wchar_t may not be // wide enough to contain a code point. // If the code_point is not a valid Unicode code point // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted // to "(Invalid Unicode 0xXXXXXXXX)". std::string CodePointToUtf8(uint32_t code_point) { … } // The following two functions only make sense if the system // uses UTF-16 for wide string encoding. All supported systems // with 16 bit wchar_t (Windows, Cygwin) do use UTF-16. // Determines if the arguments constitute UTF-16 surrogate pair // and thus should be combined into a single Unicode code point // using CreateCodePointFromUtf16SurrogatePair. inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) { … } // Creates a Unicode code point from UTF16 surrogate pair. inline uint32_t CreateCodePointFromUtf16SurrogatePair(wchar_t first, wchar_t second) { … } // Converts a wide string to a narrow string in UTF-8 encoding. // The wide string is assumed to have the following encoding: // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin) // UTF-32 if sizeof(wchar_t) == 4 (on Linux) // Parameter str points to a null-terminated wide string. // Parameter num_chars may additionally limit the number // of wchar_t characters processed. -1 is used when the entire string // should be processed. // If the string contains code points that are not valid Unicode code points // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding // and contains invalid UTF-16 surrogate pairs, values in those pairs // will be encoded as individual Unicode characters from Basic Normal Plane. std::string WideStringToUtf8(const wchar_t* str, int num_chars) { … } // Converts a wide C string to an std::string using the UTF-8 encoding. // NULL will be converted to "(null)". std::string String::ShowWideCString(const wchar_t* wide_c_str) { … } // Compares two wide C strings. Returns true if and only if they have the // same content. // // Unlike wcscmp(), this function can handle NULL argument(s). A NULL // C string is considered different to any non-NULL C string, // including the empty string. bool String::WideCStringEquals(const wchar_t* lhs, const wchar_t* rhs) { … } // Helper function for *_STREQ on wide strings. AssertionResult CmpHelperSTREQ(const char* lhs_expression, const char* rhs_expression, const wchar_t* lhs, const wchar_t* rhs) { … } // Helper function for *_STRNE on wide strings. AssertionResult CmpHelperSTRNE(const char* s1_expression, const char* s2_expression, const wchar_t* s1, const wchar_t* s2) { … } // Compares two C strings, ignoring case. Returns true if and only if they have // the same content. // // Unlike strcasecmp(), this function can handle NULL argument(s). A // NULL C string is considered different to any non-NULL C string, // including the empty string. bool String::CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) { … } // Compares two wide C strings, ignoring case. Returns true if and only if they // have the same content. // // Unlike wcscasecmp(), this function can handle NULL argument(s). // A NULL C string is considered different to any non-NULL wide C string, // including the empty string. // NB: The implementations on different platforms slightly differ. // On windows, this method uses _wcsicmp which compares according to LC_CTYPE // environment variable. On GNU platform this method uses wcscasecmp // which compares according to LC_CTYPE category of the current locale. // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the // current locale. bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs, const wchar_t* rhs) { … } // Returns true if and only if str ends with the given suffix, ignoring case. // Any string is considered to end with an empty suffix. bool String::EndsWithCaseInsensitive(const std::string& str, const std::string& suffix) { … } // Formats an int value as "%02d". std::string String::FormatIntWidth2(int value) { … } // Formats an int value to given width with leading zeros. std::string String::FormatIntWidthN(int value, int width) { … } // Formats an int value as "%X". std::string String::FormatHexUInt32(uint32_t value) { … } // Formats an int value as "%X". std::string String::FormatHexInt(int value) { … } // Formats a byte as "%02X". std::string String::FormatByte(unsigned char value) { … } // Converts the buffer in a stringstream to an std::string, converting NUL // bytes to "\\0" along the way. std::string StringStreamToString(::std::stringstream* ss) { … } // Appends the user-supplied message to the Google-Test-generated message. std::string AppendUserMessage(const std::string& gtest_msg, const Message& user_msg) { … } } // namespace internal // class TestResult // Creates an empty TestResult. TestResult::TestResult() : … { … } // D'tor. TestResult::~TestResult() = default; // Returns the i-th test part result among all the results. i can // range from 0 to total_part_count() - 1. If i is not in that range, // aborts the program. const TestPartResult& TestResult::GetTestPartResult(int i) const { … } // Returns the i-th test property. i can range from 0 to // test_property_count() - 1. If i is not in that range, aborts the // program. const TestProperty& TestResult::GetTestProperty(int i) const { … } // Clears the test part results. void TestResult::ClearTestPartResults() { … } // Adds a test part result to the list. void TestResult::AddTestPartResult(const TestPartResult& test_part_result) { … } // Adds a test property to the list. If a property with the same key as the // supplied property is already represented, the value of this test_property // replaces the old value for that key. void TestResult::RecordProperty(const std::string& xml_element, const TestProperty& test_property) { … } // The list of reserved attributes used in the <testsuites> element of XML // output. static const char* const kReservedTestSuitesAttributes[] = …; // The list of reserved attributes used in the <testsuite> element of XML // output. static const char* const kReservedTestSuiteAttributes[] = …; // The list of reserved attributes used in the <testcase> element of XML output. static const char* const kReservedTestCaseAttributes[] = …; // Use a slightly different set for allowed output to ensure existing tests can // still RecordProperty("result") or RecordProperty("timestamp") static const char* const kReservedOutputTestCaseAttributes[] = …; template <size_t kSize> std::vector<std::string> ArrayAsVector(const char* const (&array)[kSize]) { … } static std::vector<std::string> GetReservedAttributesForElement( const std::string& xml_element) { … } #if GTEST_HAS_FILE_SYSTEM // TODO(jdesprez): Merge the two getReserved attributes once skip is improved // This function is only used when file systems are enabled. static std::vector<std::string> GetReservedOutputAttributesForElement( const std::string& xml_element) { … } #endif static std::string FormatWordList(const std::vector<std::string>& words) { … } static bool ValidateTestPropertyName( const std::string& property_name, const std::vector<std::string>& reserved_names) { … } // Adds a failure if the key is a reserved attribute of the element named // xml_element. Returns true if the property is valid. bool TestResult::ValidateTestProperty(const std::string& xml_element, const TestProperty& test_property) { … } // Clears the object. void TestResult::Clear() { … } // Returns true off the test part was skipped. static bool TestPartSkipped(const TestPartResult& result) { … } // Returns true if and only if the test was skipped. bool TestResult::Skipped() const { … } // Returns true if and only if the test failed. bool TestResult::Failed() const { … } // Returns true if and only if the test part fatally failed. static bool TestPartFatallyFailed(const TestPartResult& result) { … } // Returns true if and only if the test fatally failed. bool TestResult::HasFatalFailure() const { … } // Returns true if and only if the test part non-fatally failed. static bool TestPartNonfatallyFailed(const TestPartResult& result) { … } // Returns true if and only if the test has a non-fatal failure. bool TestResult::HasNonfatalFailure() const { … } // Gets the number of all test parts. This is the sum of the number // of successful test parts and the number of failed test parts. int TestResult::total_part_count() const { … } // Returns the number of the test properties. int TestResult::test_property_count() const { … } // class Test // Creates a Test object. // The c'tor saves the states of all flags. Test::Test() : … { … } // The d'tor restores the states of all flags. The actual work is // done by the d'tor of the gtest_flag_saver_ field, and thus not // visible here. Test::~Test() = default; // Sets up the test fixture. // // A sub-class may override this. void Test::SetUp() { … } // Tears down the test fixture. // // A sub-class may override this. void Test::TearDown() { … } // Allows user supplied key value pairs to be recorded for later output. void Test::RecordProperty(const std::string& key, const std::string& value) { … } namespace internal { void ReportFailureInUnknownLocation(TestPartResult::Type result_type, const std::string& message) { … } } // namespace internal // Google Test requires all tests in the same test suite to use the same test // fixture class. This function checks if the current test has the // same fixture class as the first test in the current test suite. If // yes, it returns true; otherwise it generates a Google Test failure and // returns false. bool Test::HasSameFixtureClass() { … } namespace internal { #if GTEST_HAS_EXCEPTIONS // Adds an "exception thrown" fatal failure to the current test. static std::string FormatCxxExceptionMessage(const char* description, const char* location) { Message message; if (description != nullptr) { message << "C++ exception with description \"" << description << "\""; } else { message << "Unknown C++ exception"; } message << " thrown in " << location << "."; return message.GetString(); } static std::string PrintTestPartResultToString( const TestPartResult& test_part_result); GoogleTestFailureException::GoogleTestFailureException( const TestPartResult& failure) : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {} #endif // GTEST_HAS_EXCEPTIONS // We put these helper functions in the internal namespace as IBM's xlC // compiler rejects the code if they were declared static. // Runs the given method and handles SEH exceptions it throws, when // SEH is supported; returns the 0-value for type Result in case of an // SEH exception. (Microsoft compilers cannot handle SEH and C++ // exceptions in the same function. Therefore, we provide a separate // wrapper function for handling SEH exceptions.) template <class T, typename Result> Result HandleSehExceptionsInMethodIfSupported(T* object, Result (T::*method)(), const char* location) { … } // Runs the given method and catches and reports C++ and/or SEH-style // exceptions, if they are supported; returns the 0-value for type // Result in case of an SEH exception. template <class T, typename Result> Result HandleExceptionsInMethodIfSupported(T* object, Result (T::*method)(), const char* location) { … } } // namespace internal // Runs the test and updates the test result. void Test::Run() { … } // Returns true if and only if the current test has a fatal failure. bool Test::HasFatalFailure() { … } // Returns true if and only if the current test has a non-fatal failure. bool Test::HasNonfatalFailure() { … } // Returns true if and only if the current test was skipped. bool Test::IsSkipped() { … } // class TestInfo // Constructs a TestInfo object. It assumes ownership of the test factory // object. TestInfo::TestInfo(std::string a_test_suite_name, std::string a_name, const char* a_type_param, const char* a_value_param, internal::CodeLocation a_code_location, internal::TypeId fixture_class_id, internal::TestFactoryBase* factory) : … { … } // Destructs a TestInfo object. TestInfo::~TestInfo() { … } namespace internal { // Creates a new TestInfo object and registers it with Google Test; // returns the created object. // // Arguments: // // test_suite_name: name of the test suite // name: name of the test // type_param: the name of the test's type parameter, or NULL if // this is not a typed or a type-parameterized test. // value_param: text representation of the test's value parameter, // or NULL if this is not a value-parameterized test. // code_location: code location where the test is defined // fixture_class_id: ID of the test fixture class // set_up_tc: pointer to the function that sets up the test suite // tear_down_tc: pointer to the function that tears down the test suite // factory: pointer to the factory that creates a test object. // The newly created TestInfo instance will assume // ownership of the factory object. TestInfo* MakeAndRegisterTestInfo( std::string test_suite_name, const char* name, const char* type_param, const char* value_param, CodeLocation code_location, TypeId fixture_class_id, SetUpTestSuiteFunc set_up_tc, TearDownTestSuiteFunc tear_down_tc, TestFactoryBase* factory) { … } void ReportInvalidTestSuiteType(const char* test_suite_name, const CodeLocation& code_location) { … } // This method expands all parameterized tests registered with macros TEST_P // and INSTANTIATE_TEST_SUITE_P into regular tests and registers those. // This will be done just once during the program runtime. void UnitTestImpl::RegisterParameterizedTests() { … } } // namespace internal // Creates the test object, runs it, records its result, and then // deletes it. void TestInfo::Run() { … } // Skip and records a skipped test result for this object. void TestInfo::Skip() { … } // class TestSuite // Gets the number of successful tests in this test suite. int TestSuite::successful_test_count() const { … } // Gets the number of successful tests in this test suite. int TestSuite::skipped_test_count() const { … } // Gets the number of failed tests in this test suite. int TestSuite::failed_test_count() const { … } // Gets the number of disabled tests that will be reported in the XML report. int TestSuite::reportable_disabled_test_count() const { … } // Gets the number of disabled tests in this test suite. int TestSuite::disabled_test_count() const { … } // Gets the number of tests to be printed in the XML report. int TestSuite::reportable_test_count() const { … } // Get the number of tests in this test suite that should run. int TestSuite::test_to_run_count() const { … } // Gets the number of all tests. int TestSuite::total_test_count() const { … } // Creates a TestSuite with the given name. // // Arguments: // // a_name: name of the test suite // a_type_param: the name of the test suite's type parameter, or NULL if // this is not a typed or a type-parameterized test suite. // set_up_tc: pointer to the function that sets up the test suite // tear_down_tc: pointer to the function that tears down the test suite TestSuite::TestSuite(const std::string& a_name, const char* a_type_param, internal::SetUpTestSuiteFunc set_up_tc, internal::TearDownTestSuiteFunc tear_down_tc) : … { … } // Destructor of TestSuite. TestSuite::~TestSuite() { … } // Returns the i-th test among all the tests. i can range from 0 to // total_test_count() - 1. If i is not in that range, returns NULL. const TestInfo* TestSuite::GetTestInfo(int i) const { … } // Returns the i-th test among all the tests. i can range from 0 to // total_test_count() - 1. If i is not in that range, returns NULL. TestInfo* TestSuite::GetMutableTestInfo(int i) { … } // Adds a test to this test suite. Will delete the test upon // destruction of the TestSuite object. void TestSuite::AddTestInfo(TestInfo* test_info) { … } // Runs every test in this TestSuite. void TestSuite::Run() { … } // Skips all tests under this TestSuite. void TestSuite::Skip() { … } // Clears the results of all tests in this test suite. void TestSuite::ClearResult() { … } // Shuffles the tests in this test suite. void TestSuite::ShuffleTests(internal::Random* random) { … } // Restores the test order to before the first shuffle. void TestSuite::UnshuffleTests() { … } // Formats a countable noun. Depending on its quantity, either the // singular form or the plural form is used. e.g. // // FormatCountableNoun(1, "formula", "formuli") returns "1 formula". // FormatCountableNoun(5, "book", "books") returns "5 books". static std::string FormatCountableNoun(int count, const char* singular_form, const char* plural_form) { … } // Formats the count of tests. static std::string FormatTestCount(int test_count) { … } // Formats the count of test suites. static std::string FormatTestSuiteCount(int test_suite_count) { … } // Converts a TestPartResult::Type enum to human-friendly string // representation. Both kNonFatalFailure and kFatalFailure are translated // to "Failure", as the user usually doesn't care about the difference // between the two when viewing the test result. static const char* TestPartResultTypeToString(TestPartResult::Type type) { … } namespace internal { namespace { enum class GTestColor { … }; } // namespace // Prints a TestPartResult to an std::string. static std::string PrintTestPartResultToString( const TestPartResult& test_part_result) { … } // Prints a TestPartResult. static void PrintTestPartResult(const TestPartResult& test_part_result) { … } // class PrettyUnitTestResultPrinter #if defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_MOBILE) && \ !defined(GTEST_OS_WINDOWS_GAMES) && !defined(GTEST_OS_WINDOWS_PHONE) && \ !defined(GTEST_OS_WINDOWS_RT) && !defined(GTEST_OS_WINDOWS_MINGW) // Returns the character attribute for the given color. static WORD GetColorAttribute(GTestColor color) { switch (color) { case GTestColor::kRed: return FOREGROUND_RED; case GTestColor::kGreen: return FOREGROUND_GREEN; case GTestColor::kYellow: return FOREGROUND_RED | FOREGROUND_GREEN; default: return 0; } } static int GetBitOffset(WORD color_mask) { if (color_mask == 0) return 0; int bitOffset = 0; while ((color_mask & 1) == 0) { color_mask >>= 1; ++bitOffset; } return bitOffset; } static WORD GetNewColor(GTestColor color, WORD old_color_attrs) { // Let's reuse the BG static const WORD background_mask = BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_INTENSITY; static const WORD foreground_mask = FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY; const WORD existing_bg = old_color_attrs & background_mask; WORD new_color = GetColorAttribute(color) | existing_bg | FOREGROUND_INTENSITY; static const int bg_bitOffset = GetBitOffset(background_mask); static const int fg_bitOffset = GetBitOffset(foreground_mask); if (((new_color & background_mask) >> bg_bitOffset) == ((new_color & foreground_mask) >> fg_bitOffset)) { new_color ^= FOREGROUND_INTENSITY; // invert intensity } return new_color; } #else // Returns the ANSI color code for the given color. GTestColor::kDefault is // an invalid input. static const char* GetAnsiColorCode(GTestColor color) { … } #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE // Returns true if and only if Google Test should use colors in the output. bool ShouldUseColor(bool stdout_is_tty) { … } // Helpers for printing colored strings to stdout. Note that on Windows, we // cannot simply emit special characters and have the terminal change colors. // This routine must actually emit the characters rather than return a string // that would be colored when printed, as can be done on Linux. GTEST_ATTRIBUTE_PRINTF_(2, 3) static void ColoredPrintf(GTestColor color, const char* fmt, ...) { … } // Text printed in Google Test's text output and --gtest_list_tests // output to label the type parameter and value parameter for a test. static const char kTypeParamLabel[] = …; static const char kValueParamLabel[] = …; static void PrintFullTestCommentIfPresent(const TestInfo& test_info) { … } // This class implements the TestEventListener interface. // // Class PrettyUnitTestResultPrinter is copyable. class PrettyUnitTestResultPrinter : public TestEventListener { … }; // Fired before each iteration of tests starts. void PrettyUnitTestResultPrinter::OnTestIterationStart( const UnitTest& unit_test, int iteration) { … } void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart( const UnitTest& /*unit_test*/) { … } #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) { … } #else void PrettyUnitTestResultPrinter::OnTestSuiteStart( const TestSuite& test_suite) { const std::string counts = FormatCountableNoun(test_suite.test_to_run_count(), "test", "tests"); ColoredPrintf(GTestColor::kGreen, "[----------] "); printf("%s from %s", counts.c_str(), test_suite.name()); if (test_suite.type_param() == nullptr) { printf("\n"); } else { printf(", where %s = %s\n", kTypeParamLabel, test_suite.type_param()); } fflush(stdout); } #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) { … } void PrettyUnitTestResultPrinter::OnTestDisabled(const TestInfo& test_info) { … } // Called after an assertion failure. void PrettyUnitTestResultPrinter::OnTestPartResult( const TestPartResult& result) { … } void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) { … } #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) { … } #else void PrettyUnitTestResultPrinter::OnTestSuiteEnd(const TestSuite& test_suite) { if (!GTEST_FLAG_GET(print_time)) return; const std::string counts = FormatCountableNoun(test_suite.test_to_run_count(), "test", "tests"); ColoredPrintf(GTestColor::kGreen, "[----------] "); printf("%s from %s (%s ms total)\n\n", counts.c_str(), test_suite.name(), internal::StreamableToString(test_suite.elapsed_time()).c_str()); fflush(stdout); } #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart( const UnitTest& /*unit_test*/) { … } // Internal helper for printing the list of failed tests. void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) { … } // Internal helper for printing the list of test suite failures not covered by // PrintFailedTests. void PrettyUnitTestResultPrinter::PrintFailedTestSuites( const UnitTest& unit_test) { … } // Internal helper for printing the list of skipped tests. void PrettyUnitTestResultPrinter::PrintSkippedTests(const UnitTest& unit_test) { … } void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, int /*iteration*/) { … } // End PrettyUnitTestResultPrinter // This class implements the TestEventListener interface. // // Class BriefUnitTestResultPrinter is copyable. class BriefUnitTestResultPrinter : public TestEventListener { … }; // Called after an assertion failure. void BriefUnitTestResultPrinter::OnTestPartResult( const TestPartResult& result) { … } void BriefUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) { … } void BriefUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, int /*iteration*/) { … } // End BriefUnitTestResultPrinter // class TestEventRepeater // // This class forwards events to other event listeners. class TestEventRepeater : public TestEventListener { … }; TestEventRepeater::~TestEventRepeater() { … } void TestEventRepeater::Append(TestEventListener* listener) { … } TestEventListener* TestEventRepeater::Release(TestEventListener* listener) { … } // Since most methods are very similar, use macros to reduce boilerplate. // This defines a member that forwards the call to all listeners. #define GTEST_REPEATER_METHOD_ … // This defines a member that forwards the call to all listeners in reverse // order. #define GTEST_REVERSE_REPEATER_METHOD_ … GTEST_REPEATER_METHOD_ GTEST_REPEATER_METHOD_ // Legacy API is deprecated but still available #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ GTEST_REPEATER_METHOD_ #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ GTEST_REPEATER_METHOD_ GTEST_REPEATER_METHOD_ GTEST_REPEATER_METHOD_ GTEST_REPEATER_METHOD_ GTEST_REPEATER_METHOD_ GTEST_REVERSE_REPEATER_METHOD_ GTEST_REVERSE_REPEATER_METHOD_ GTEST_REVERSE_REPEATER_METHOD_ // Legacy API is deprecated but still available #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ GTEST_REVERSE_REPEATER_METHOD_ #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ GTEST_REVERSE_REPEATER_METHOD_ GTEST_REVERSE_REPEATER_METHOD_ #undef GTEST_REPEATER_METHOD_ #undef GTEST_REVERSE_REPEATER_METHOD_ void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test, int iteration) { … } void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test, int iteration) { … } // End TestEventRepeater #if GTEST_HAS_FILE_SYSTEM // This class generates an XML output file. class XmlUnitTestResultPrinter : public EmptyTestEventListener { … }; // Creates a new XmlUnitTestResultPrinter. XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file) : … { … } // Called after the unit test ends. void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, int /*iteration*/) { … } void XmlUnitTestResultPrinter::ListTestsMatchingFilter( const std::vector<TestSuite*>& test_suites) { … } // Returns an XML-escaped copy of the input string str. If is_attribute // is true, the text is meant to appear as an attribute value, and // normalizable whitespace is preserved by replacing it with character // references. // // Invalid XML characters in str, if any, are stripped from the output. // It is expected that most, if not all, of the text processed by this // module will consist of ordinary English text. // If this module is ever modified to produce version 1.1 XML output, // most invalid characters can be retained using character references. std::string XmlUnitTestResultPrinter::EscapeXml(const std::string& str, bool is_attribute) { … } // Returns the given string with all characters invalid in XML removed. // Currently invalid characters are dropped from the string. An // alternative is to replace them with certain characters such as . or ?. std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters( const std::string& str) { … } // The following routines generate an XML representation of a UnitTest // object. // // This is how Google Test concepts map to the DTD: // // <testsuites name="AllTests"> <-- corresponds to a UnitTest object // <testsuite name="testcase-name"> <-- corresponds to a TestSuite object // <testcase name="test-name"> <-- corresponds to a TestInfo object // <failure message="...">...</failure> // <failure message="...">...</failure> // <failure message="...">...</failure> // <-- individual assertion failures // </testcase> // </testsuite> // </testsuites> // Formats the given time in milliseconds as seconds. std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) { … } static bool PortableLocaltime(time_t seconds, struct tm* out) { … } // Converts the given epoch time in milliseconds to a date string in the ISO // 8601 format, without the timezone information. std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) { … } // Streams an XML CDATA section, escaping invalid CDATA sequences as needed. void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream, const char* data) { … } void XmlUnitTestResultPrinter::OutputXmlAttribute( std::ostream* stream, const std::string& element_name, const std::string& name, const std::string& value) { … } // Streams a test suite XML stanza containing the given test result. void XmlUnitTestResultPrinter::OutputXmlTestSuiteForTestResult( ::std::ostream* stream, const TestResult& result) { … } // Prints an XML representation of a TestInfo object. void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream, const char* test_suite_name, const TestInfo& test_info) { … } void XmlUnitTestResultPrinter::OutputXmlTestResult(::std::ostream* stream, const TestResult& result) { … } // Prints an XML representation of a TestSuite object void XmlUnitTestResultPrinter::PrintXmlTestSuite(std::ostream* stream, const TestSuite& test_suite) { … } // Prints an XML summary of unit_test to output stream out. void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream, const UnitTest& unit_test) { … } void XmlUnitTestResultPrinter::PrintXmlTestsList( std::ostream* stream, const std::vector<TestSuite*>& test_suites) { … } // Produces a string representing the test properties in a result as space // delimited XML attributes based on the property key="value" pairs. std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes( const TestResult& result) { … } void XmlUnitTestResultPrinter::OutputXmlTestProperties( std::ostream* stream, const TestResult& result) { … } // End XmlUnitTestResultPrinter #endif // GTEST_HAS_FILE_SYSTEM #if GTEST_HAS_FILE_SYSTEM // This class generates an JSON output file. class JsonUnitTestResultPrinter : public EmptyTestEventListener { … }; // Creates a new JsonUnitTestResultPrinter. JsonUnitTestResultPrinter::JsonUnitTestResultPrinter(const char* output_file) : … { … } void JsonUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, int /*iteration*/) { … } // Returns an JSON-escaped copy of the input string str. std::string JsonUnitTestResultPrinter::EscapeJson(const std::string& str) { … } // The following routines generate an JSON representation of a UnitTest // object. // Formats the given time in milliseconds as seconds. static std::string FormatTimeInMillisAsDuration(TimeInMillis ms) { … } // Converts the given epoch time in milliseconds to a date string in the // RFC3339 format, without the timezone information. static std::string FormatEpochTimeInMillisAsRFC3339(TimeInMillis ms) { … } static inline std::string Indent(size_t width) { … } void JsonUnitTestResultPrinter::OutputJsonKey(std::ostream* stream, const std::string& element_name, const std::string& name, const std::string& value, const std::string& indent, bool comma) { … } void JsonUnitTestResultPrinter::OutputJsonKey( std::ostream* stream, const std::string& element_name, const std::string& name, int value, const std::string& indent, bool comma) { … } // Streams a test suite JSON stanza containing the given test result. void JsonUnitTestResultPrinter::OutputJsonTestSuiteForTestResult( ::std::ostream* stream, const TestResult& result) { … } // Prints a JSON representation of a TestInfo object. void JsonUnitTestResultPrinter::OutputJsonTestInfo(::std::ostream* stream, const char* test_suite_name, const TestInfo& test_info) { … } void JsonUnitTestResultPrinter::OutputJsonTestResult(::std::ostream* stream, const TestResult& result) { … } // Prints an JSON representation of a TestSuite object void JsonUnitTestResultPrinter::PrintJsonTestSuite( std::ostream* stream, const TestSuite& test_suite) { … } // Prints a JSON summary of unit_test to output stream out. void JsonUnitTestResultPrinter::PrintJsonUnitTest(std::ostream* stream, const UnitTest& unit_test) { … } void JsonUnitTestResultPrinter::PrintJsonTestList( std::ostream* stream, const std::vector<TestSuite*>& test_suites) { … } // Produces a string representing the test properties in a result as // a JSON dictionary. std::string JsonUnitTestResultPrinter::TestPropertiesAsJson( const TestResult& result, const std::string& indent) { … } // End JsonUnitTestResultPrinter #endif // GTEST_HAS_FILE_SYSTEM #if GTEST_CAN_STREAM_RESULTS_ // Checks if str contains '=', '&', '%' or '\n' characters. If yes, // replaces them by "%xx" where xx is their hexadecimal value. For // example, replaces "=" with "%3D". This algorithm is O(strlen(str)) // in both time and space -- important as the input str may contain an // arbitrarily long test failure message and stack trace. std::string StreamingListener::UrlEncode(const char* str) { … } void StreamingListener::SocketWriter::MakeConnection() { … } // End of class Streaming Listener #endif // GTEST_CAN_STREAM_RESULTS__ // class OsStackTraceGetter const char* const OsStackTraceGetterInterface::kElidedFramesMarker = …; std::string OsStackTraceGetter::CurrentStackTrace(int max_depth, int skip_count) GTEST_LOCK_EXCLUDED_(mutex_) { … } void OsStackTraceGetter::UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_) { … } #ifdef GTEST_HAS_DEATH_TEST // A helper class that creates the premature-exit file in its // constructor and deletes the file in its destructor. class ScopedPrematureExitFile { … }; #endif // GTEST_HAS_DEATH_TEST } // namespace internal // class TestEventListeners TestEventListeners::TestEventListeners() : … { … } TestEventListeners::~TestEventListeners() { … } // Returns the standard listener responsible for the default console // output. Can be removed from the listeners list to shut down default // console output. Note that removing this object from the listener list // with Release transfers its ownership to the user. void TestEventListeners::Append(TestEventListener* listener) { … } // Removes the given event listener from the list and returns it. It then // becomes the caller's responsibility to delete the listener. Returns // NULL if the listener is not found in the list. TestEventListener* TestEventListeners::Release(TestEventListener* listener) { … } // Returns repeater that broadcasts the TestEventListener events to all // subscribers. TestEventListener* TestEventListeners::repeater() { … } // Sets the default_result_printer attribute to the provided listener. // The listener is also added to the listener list and previous // default_result_printer is removed from it and deleted. The listener can // also be NULL in which case it will not be added to the list. Does // nothing if the previous and the current listener objects are the same. void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) { … } // Sets the default_xml_generator attribute to the provided listener. The // listener is also added to the listener list and previous // default_xml_generator is removed from it and deleted. The listener can // also be NULL in which case it will not be added to the list. Does // nothing if the previous and the current listener objects are the same. void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) { … } // Controls whether events will be forwarded by the repeater to the // listeners in the list. bool TestEventListeners::EventForwardingEnabled() const { … } void TestEventListeners::SuppressEventForwarding(bool suppress) { … } // class UnitTest // Gets the singleton UnitTest object. The first time this method is // called, a UnitTest object is constructed and returned. Consecutive // calls will return the same object. // // We don't protect this under mutex_ as a user is not supposed to // call this before main() starts, from which point on the return // value will never change. UnitTest* UnitTest::GetInstance() { … } // Gets the number of successful test suites. int UnitTest::successful_test_suite_count() const { … } // Gets the number of failed test suites. int UnitTest::failed_test_suite_count() const { … } // Gets the number of all test suites. int UnitTest::total_test_suite_count() const { … } // Gets the number of all test suites that contain at least one test // that should run. int UnitTest::test_suite_to_run_count() const { … } // Legacy API is deprecated but still available #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ int UnitTest::successful_test_case_count() const { … } int UnitTest::failed_test_case_count() const { … } int UnitTest::total_test_case_count() const { … } int UnitTest::test_case_to_run_count() const { … } #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ // Gets the number of successful tests. int UnitTest::successful_test_count() const { … } // Gets the number of skipped tests. int UnitTest::skipped_test_count() const { … } // Gets the number of failed tests. int UnitTest::failed_test_count() const { … } // Gets the number of disabled tests that will be reported in the XML report. int UnitTest::reportable_disabled_test_count() const { … } // Gets the number of disabled tests. int UnitTest::disabled_test_count() const { … } // Gets the number of tests to be printed in the XML report. int UnitTest::reportable_test_count() const { … } // Gets the number of all tests. int UnitTest::total_test_count() const { … } // Gets the number of tests that should run. int UnitTest::test_to_run_count() const { … } // Gets the time of the test program start, in ms from the start of the // UNIX epoch. internal::TimeInMillis UnitTest::start_timestamp() const { … } // Gets the elapsed time, in milliseconds. internal::TimeInMillis UnitTest::elapsed_time() const { … } // Returns true if and only if the unit test passed (i.e. all test suites // passed). bool UnitTest::Passed() const { … } // Returns true if and only if the unit test failed (i.e. some test suite // failed or something outside of all tests failed). bool UnitTest::Failed() const { … } // Gets the i-th test suite among all the test suites. i can range from 0 to // total_test_suite_count() - 1. If i is not in that range, returns NULL. const TestSuite* UnitTest::GetTestSuite(int i) const { … } // Legacy API is deprecated but still available #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ const TestCase* UnitTest::GetTestCase(int i) const { … } #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ // Returns the TestResult containing information on test failures and // properties logged outside of individual test suites. const TestResult& UnitTest::ad_hoc_test_result() const { … } // Gets the i-th test suite among all the test suites. i can range from 0 to // total_test_suite_count() - 1. If i is not in that range, returns NULL. TestSuite* UnitTest::GetMutableTestSuite(int i) { … } void UnitTest::UponLeavingGTest() { … } // Sets the TestSuite object for the test that's currently running. void UnitTest::set_current_test_suite(TestSuite* a_current_test_suite) { … } // Sets the TestInfo object for the test that's currently running. void UnitTest::set_current_test_info(TestInfo* a_current_test_info) { … } // Returns the list of event listeners that can be used to track events // inside Google Test. TestEventListeners& UnitTest::listeners() { … } // Registers and returns a global test environment. When a test // program is run, all global test environments will be set-up in the // order they were registered. After all tests in the program have // finished, all global test environments will be torn-down in the // *reverse* order they were registered. // // The UnitTest object takes ownership of the given environment. // // We don't protect this under mutex_, as we only support calling it // from the main thread. Environment* UnitTest::AddEnvironment(Environment* env) { … } // Adds a TestPartResult to the current TestResult object. All Google Test // assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call // this to report their results. The user code should use the // assertion macros instead of calling this directly. void UnitTest::AddTestPartResult(TestPartResult::Type result_type, const char* file_name, int line_number, const std::string& message, const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_) { … } // Adds a TestProperty to the current TestResult object when invoked from // inside a test, to current TestSuite's ad_hoc_test_result_ when invoked // from SetUpTestSuite or TearDownTestSuite, or to the global property set // when invoked elsewhere. If the result already contains a property with // the same key, the value will be updated. void UnitTest::RecordProperty(const std::string& key, const std::string& value) { … } // Runs all tests in this UnitTest object and prints the result. // Returns 0 if successful, or 1 otherwise. // // We don't protect this under mutex_, as we only support calling it // from the main thread. int UnitTest::Run() { … } #if GTEST_HAS_FILE_SYSTEM // Returns the working directory when the first TEST() or TEST_F() was // executed. const char* UnitTest::original_working_dir() const { … } #endif // GTEST_HAS_FILE_SYSTEM // Returns the TestSuite object for the test that's currently running, // or NULL if no test is running. const TestSuite* UnitTest::current_test_suite() const GTEST_LOCK_EXCLUDED_(mutex_) { … } // Legacy API is still available but deprecated #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ const TestCase* UnitTest::current_test_case() const GTEST_LOCK_EXCLUDED_(mutex_) { … } #endif // Returns the TestInfo object for the test that's currently running, // or NULL if no test is running. const TestInfo* UnitTest::current_test_info() const GTEST_LOCK_EXCLUDED_(mutex_) { … } // Returns the random seed used at the start of the current test run. int UnitTest::random_seed() const { … } // Returns ParameterizedTestSuiteRegistry object used to keep track of // value-parameterized tests and instantiate and register them. internal::ParameterizedTestSuiteRegistry& UnitTest::parameterized_test_registry() GTEST_LOCK_EXCLUDED_(mutex_) { … } // Creates an empty UnitTest. UnitTest::UnitTest() { … } // Destructor of UnitTest. UnitTest::~UnitTest() { … } // Pushes a trace defined by SCOPED_TRACE() on to the per-thread // Google Test trace stack. void UnitTest::PushGTestTrace(const internal::TraceInfo& trace) GTEST_LOCK_EXCLUDED_(mutex_) { … } // Pops a trace from the per-thread Google Test trace stack. void UnitTest::PopGTestTrace() GTEST_LOCK_EXCLUDED_(mutex_) { … } namespace internal { UnitTestImpl::UnitTestImpl(UnitTest* parent) : … { … } UnitTestImpl::~UnitTestImpl() { … } // Adds a TestProperty to the current TestResult object when invoked in a // context of a test, to current test suite's ad_hoc_test_result when invoke // from SetUpTestSuite/TearDownTestSuite, or to the global property set // otherwise. If the result already contains a property with the same key, // the value will be updated. void UnitTestImpl::RecordProperty(const TestProperty& test_property) { … } #ifdef GTEST_HAS_DEATH_TEST // Disables event forwarding if the control is currently in a death test // subprocess. Must not be called before InitGoogleTest. void UnitTestImpl::SuppressTestEventsIfInSubprocess() { … } #endif // GTEST_HAS_DEATH_TEST // Initializes event listeners performing XML output as specified by // UnitTestOptions. Must not be called before InitGoogleTest. void UnitTestImpl::ConfigureXmlOutput() { … } #if GTEST_CAN_STREAM_RESULTS_ // Initializes event listeners for streaming test results in string form. // Must not be called before InitGoogleTest. void UnitTestImpl::ConfigureStreamingOutput() { … } #endif // GTEST_CAN_STREAM_RESULTS_ // Performs initialization dependent upon flag values obtained in // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest // this function is also called from RunAllTests. Since this function can be // called more than once, it has to be idempotent. void UnitTestImpl::PostFlagParsingInit() { … } // Finds and returns a TestSuite with the given name. If one doesn't // exist, creates one and returns it. It's the CALLER'S // RESPONSIBILITY to ensure that this function is only called WHEN THE // TESTS ARE NOT SHUFFLED. // // Arguments: // // test_suite_name: name of the test suite // type_param: the name of the test suite's type parameter, or NULL if // this is not a typed or a type-parameterized test suite. // set_up_tc: pointer to the function that sets up the test suite // tear_down_tc: pointer to the function that tears down the test suite TestSuite* UnitTestImpl::GetTestSuite( const std::string& test_suite_name, const char* type_param, internal::SetUpTestSuiteFunc set_up_tc, internal::TearDownTestSuiteFunc tear_down_tc) { … } // Helpers for setting up / tearing down the given environment. They // are for use in the ForEach() function. static void SetUpEnvironment(Environment* env) { … } static void TearDownEnvironment(Environment* env) { … } // Runs all tests in this UnitTest object, prints the result, and // returns true if all tests are successful. If any exception is // thrown during a test, the test is considered to be failed, but the // rest of the tests will still be run. // // When parameterized tests are enabled, it expands and registers // parameterized tests first in RegisterParameterizedTests(). // All other functions called from RunAllTests() may safely assume that // parameterized tests are ready to be counted and run. bool UnitTestImpl::RunAllTests() { … } #if GTEST_HAS_FILE_SYSTEM // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file // if the variable is present. If a file already exists at this location, this // function will write over it. If the variable is present, but the file cannot // be created, prints an error and exits. void WriteToShardStatusFileIfNeeded() { … } #endif // GTEST_HAS_FILE_SYSTEM // Checks whether sharding is enabled by examining the relevant // environment variable values. If the variables are present, // but inconsistent (i.e., shard_index >= total_shards), prints // an error and exits. If in_subprocess_for_death_test, sharding is // disabled because it must only be applied to the original test // process. Otherwise, we could filter out death tests we intended to execute. bool ShouldShard(const char* total_shards_env, const char* shard_index_env, bool in_subprocess_for_death_test) { … } // Parses the environment variable var as an Int32. If it is unset, // returns default_val. If it is not an Int32, prints an error // and aborts. int32_t Int32FromEnvOrDie(const char* var, int32_t default_val) { … } // Given the total number of shards, the shard index, and the test id, // returns true if and only if the test should be run on this shard. The test id // is some arbitrary but unique non-negative integer assigned to each test // method. Assumes that 0 <= shard_index < total_shards. bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) { … } // Compares the name of each test with the user-specified filter to // decide whether the test should be run, then records the result in // each TestSuite and TestInfo object. // If shard_tests == true, further filters tests based on sharding // variables in the environment - see // https://github.com/google/googletest/blob/main/docs/advanced.md // . Returns the number of tests that should run. int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) { … } // Prints the given C-string on a single line by replacing all '\n' // characters with string "\\n". If the output takes more than // max_length characters, only prints the first max_length characters // and "...". static void PrintOnOneLine(const char* str, int max_length) { … } // Prints the names of the tests matching the user-specified filter flag. void UnitTestImpl::ListTestsMatchingFilter() { … } // Sets the OS stack trace getter. // // Does nothing if the input and the current OS stack trace getter are // the same; otherwise, deletes the old getter and makes the input the // current getter. void UnitTestImpl::set_os_stack_trace_getter( OsStackTraceGetterInterface* getter) { … } // Returns the current OS stack trace getter if it is not NULL; // otherwise, creates an OsStackTraceGetter, makes it the current // getter, and returns it. OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() { … } // Returns the most specific TestResult currently running. TestResult* UnitTestImpl::current_test_result() { … } // Shuffles all test suites, and the tests within each test suite, // making sure that death tests are still run first. void UnitTestImpl::ShuffleTests() { … } // Restores the test suites and tests to their order before the first shuffle. void UnitTestImpl::UnshuffleTests() { … } // Returns the current OS stack trace as an std::string. // // The maximum number of stack frames to be included is specified by // the gtest_stack_trace_depth flag. The skip_count parameter // specifies the number of top frames to be skipped, which doesn't // count against the number of frames to be included. // // For example, if Foo() calls Bar(), which in turn calls // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't. GTEST_NO_INLINE_ GTEST_NO_TAIL_CALL_ std::string GetCurrentOsStackTraceExceptTop(int skip_count) { … } // Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to // suppress unreachable code warnings. namespace { class ClassUniqueToAlwaysTrue { … }; } // namespace bool IsTrue(bool condition) { … } bool AlwaysTrue() { … } // If *pstr starts with the given prefix, modifies *pstr to be right // past the prefix and returns true; otherwise leaves *pstr unchanged // and returns false. None of pstr, *pstr, and prefix can be NULL. bool SkipPrefix(const char* prefix, const char** pstr) { … } // Parses a string as a command line flag. The string should have // the format "--flag=value". When def_optional is true, the "=value" // part can be omitted. // // Returns the value of the flag, or NULL if the parsing failed. static const char* ParseFlagValue(const char* str, const char* flag_name, bool def_optional) { … } // Parses a string for a bool flag, in the form of either // "--flag=value" or "--flag". // // In the former case, the value is taken as true as long as it does // not start with '0', 'f', or 'F'. // // In the latter case, the value is taken as true. // // On success, stores the value of the flag in *value, and returns // true. On failure, returns false without changing *value. static bool ParseFlag(const char* str, const char* flag_name, bool* value) { … } // Parses a string for an int32_t flag, in the form of "--flag=value". // // On success, stores the value of the flag in *value, and returns // true. On failure, returns false without changing *value. bool ParseFlag(const char* str, const char* flag_name, int32_t* value) { … } // Parses a string for a string flag, in the form of "--flag=value". // // On success, stores the value of the flag in *value, and returns // true. On failure, returns false without changing *value. template <typename String> static bool ParseFlag(const char* str, const char* flag_name, String* value) { … } // Determines whether a string has a prefix that Google Test uses for its // flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_. // If Google Test detects that a command line flag has its prefix but is not // recognized, it will print its help message. Flags starting with // GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test // internal flags and do not trigger the help message. static bool HasGoogleTestFlagPrefix(const char* str) { … } // Prints a string containing code-encoded text. The following escape // sequences can be used in the string to control the text color: // // @@ prints a single '@' character. // @R changes the color to red. // @G changes the color to green. // @Y changes the color to yellow. // @D changes to the default terminal text color. // static void PrintColorEncoded(const char* str) { … } static const char kColorEncodedHelpMessage[] = …; static bool ParseGoogleTestFlag(const char* const arg) { … } #if GTEST_USE_OWN_FLAGFILE_FLAG_ && GTEST_HAS_FILE_SYSTEM static void LoadFlagsFromFile(const std::string& path) { … } #endif // GTEST_USE_OWN_FLAGFILE_FLAG_ && GTEST_HAS_FILE_SYSTEM // Parses the command line for Google Test flags, without initializing // other parts of Google Test. The type parameter CharType can be // instantiated to either char or wchar_t. template <typename CharType> void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) { … } // Parses the command line for Google Test flags, without initializing // other parts of Google Test. This function updates argc and argv by removing // flags that are known to GoogleTest (including other user flags defined using // ABSL_FLAG if GoogleTest is built with GTEST_USE_ABSL). Other arguments // remain in place. Unrecognized flags are not reported and do not cause the // program to exit. void ParseGoogleTestFlagsOnly(int* argc, char** argv) { … } void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) { … } // The internal implementation of InitGoogleTest(). // // The type parameter CharType can be instantiated to either char or // wchar_t. template <typename CharType> void InitGoogleTestImpl(int* argc, CharType** argv) { … } } // namespace internal // Initializes Google Test. This must be called before calling // RUN_ALL_TESTS(). In particular, it parses a command line for the // flags that Google Test recognizes. Whenever a Google Test flag is // seen, it is removed from argv, and *argc is decremented. // // No value is returned. Instead, the Google Test flag variables are // updated. // // Calling the function for the second time has no user-visible effect. void InitGoogleTest(int* argc, char** argv) { … } // This overloaded version can be used in Windows programs compiled in // UNICODE mode. void InitGoogleTest(int* argc, wchar_t** argv) { … } // This overloaded version can be used on Arduino/embedded platforms where // there is no argc/argv. void InitGoogleTest() { … } #if !defined(GTEST_CUSTOM_TEMPDIR_FUNCTION_) || \ !defined(GTEST_CUSTOM_SRCDIR_FUNCTION_) // Returns the value of the first environment variable that is set and contains // a non-empty string. If there are none, returns the "fallback" string. Adds // the director-separator character as a suffix if not provided in the // environment variable value. static std::string GetDirFromEnv( std::initializer_list<const char*> environment_variables, const char* fallback, char separator) { … } #endif std::string TempDir() { … } #if GTEST_HAS_FILE_SYSTEM && !defined(GTEST_CUSTOM_SRCDIR_FUNCTION_) // Returns the directory path (including terminating separator) of the current // executable as derived from argv[0]. static std::string GetCurrentExecutableDirectory() { … } #endif #if GTEST_HAS_FILE_SYSTEM std::string SrcDir() { … } #endif // Class ScopedTrace // Pushes the given source file location and message onto a per-thread // trace stack maintained by Google Test. void ScopedTrace::PushTrace(const char* file, int line, std::string message) { … } // Pops the info pushed by the c'tor. ScopedTrace::~ScopedTrace() GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) { … } } // namespace testing