diff options
Diffstat (limited to 'googletest/src')
-rw-r--r-- | googletest/src/gtest-assertion-result.cc | 4 | ||||
-rw-r--r-- | googletest/src/gtest-death-test.cc | 156 | ||||
-rw-r--r-- | googletest/src/gtest-filepath.cc | 41 | ||||
-rw-r--r-- | googletest/src/gtest-internal-inl.h | 26 | ||||
-rw-r--r-- | googletest/src/gtest-port.cc | 106 | ||||
-rw-r--r-- | googletest/src/gtest-printers.cc | 4 | ||||
-rw-r--r-- | googletest/src/gtest-test-part.cc | 5 | ||||
-rw-r--r-- | googletest/src/gtest-typed-test.cc | 6 | ||||
-rw-r--r-- | googletest/src/gtest.cc | 240 | ||||
-rw-r--r-- | googletest/src/gtest_main.cc | 8 |
10 files changed, 320 insertions, 276 deletions
diff --git a/googletest/src/gtest-assertion-result.cc b/googletest/src/gtest-assertion-result.cc index f1c0b10d..39989216 100644 --- a/googletest/src/gtest-assertion-result.cc +++ b/googletest/src/gtest-assertion-result.cc @@ -44,7 +44,7 @@ namespace testing { // Used in EXPECT_TRUE/FALSE(assertion_result). AssertionResult::AssertionResult(const AssertionResult& other) : success_(other.success_), - message_(other.message_.get() != nullptr + message_(other.message_ != nullptr ? new ::std::string(*other.message_) : static_cast< ::std::string*>(nullptr)) {} @@ -58,7 +58,7 @@ void AssertionResult::swap(AssertionResult& other) { // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE. AssertionResult AssertionResult::operator!() const { AssertionResult negation(!success_); - if (message_.get() != nullptr) negation << *message_; + if (message_ != nullptr) negation << *message_; return negation; } diff --git a/googletest/src/gtest-death-test.cc b/googletest/src/gtest-death-test.cc index b6968a9c..c3b7820e 100644 --- a/googletest/src/gtest-death-test.cc +++ b/googletest/src/gtest-death-test.cc @@ -33,14 +33,18 @@ #include "gtest/gtest-death-test.h" #include <functional> +#include <memory> +#include <sstream> +#include <string> #include <utility> +#include <vector> #include "gtest/internal/custom/gtest.h" #include "gtest/internal/gtest-port.h" -#if GTEST_HAS_DEATH_TEST +#ifdef GTEST_HAS_DEATH_TEST -#if GTEST_OS_MAC +#ifdef GTEST_OS_MAC #include <crt_externs.h> #endif // GTEST_OS_MAC @@ -48,24 +52,24 @@ #include <fcntl.h> #include <limits.h> -#if GTEST_OS_LINUX +#ifdef GTEST_OS_LINUX #include <signal.h> #endif // GTEST_OS_LINUX #include <stdarg.h> -#if GTEST_OS_WINDOWS +#ifdef GTEST_OS_WINDOWS #include <windows.h> #else #include <sys/mman.h> #include <sys/wait.h> #endif // GTEST_OS_WINDOWS -#if GTEST_OS_QNX +#ifdef GTEST_OS_QNX #include <spawn.h> #endif // GTEST_OS_QNX -#if GTEST_OS_FUCHSIA +#ifdef GTEST_OS_FUCHSIA #include <lib/fdio/fd.h> #include <lib/fdio/io.h> #include <lib/fdio/spawn.h> @@ -131,13 +135,13 @@ GTEST_DEFINE_string_( namespace testing { -#if GTEST_HAS_DEATH_TEST +#ifdef GTEST_HAS_DEATH_TEST namespace internal { // Valid only for fast death tests. Indicates the code is running in the // child process of a fast style death test. -#if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA +#if !defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_FUCHSIA) static bool g_in_fast_death_test_child = false; #endif @@ -147,7 +151,7 @@ static bool g_in_fast_death_test_child = false; // tests. IMPORTANT: This is an internal utility. Using it may break the // implementation of death tests. User code MUST NOT use it. bool InDeathTestChild() { -#if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA +#if defined(GTEST_OS_WINDOWS) || defined(GTEST_OS_FUCHSIA) // On Windows and Fuchsia, death tests are thread-safe regardless of the value // of the death_test_style flag. @@ -169,7 +173,7 @@ ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {} // ExitedWithCode function-call operator. bool ExitedWithCode::operator()(int exit_status) const { -#if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA +#if defined(GTEST_OS_WINDOWS) || defined(GTEST_OS_FUCHSIA) return exit_status == exit_code_; @@ -180,7 +184,7 @@ bool ExitedWithCode::operator()(int exit_status) const { #endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA } -#if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA +#if !defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_FUCHSIA) // KilledBySignal constructor. KilledBySignal::KilledBySignal(int signum) : signum_(signum) {} @@ -207,7 +211,7 @@ namespace internal { static std::string ExitSummary(int exit_code) { Message m; -#if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA +#if defined(GTEST_OS_WINDOWS) || defined(GTEST_OS_FUCHSIA) m << "Exited with exit status " << exit_code; @@ -234,7 +238,7 @@ bool ExitedUnsuccessfully(int exit_status) { return !ExitedWithCode(0)(exit_status); } -#if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA +#if !defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_FUCHSIA) // Generates a textual failure message when a death test finds more than // one thread running, or cannot determine the number of threads, prior // to executing the given statement. It is the responsibility of the @@ -263,7 +267,7 @@ static const char kDeathTestReturned = 'R'; static const char kDeathTestThrew = 'T'; static const char kDeathTestInternalError = 'I'; -#if GTEST_OS_FUCHSIA +#ifdef GTEST_OS_FUCHSIA // File descriptor used for the pipe in the child process. static const int kFuchsiaReadPipeFd = 3; @@ -621,7 +625,18 @@ bool DeathTestImpl::Passed(bool status_ok) { return success; } -#if GTEST_OS_WINDOWS +// Note: The return value points into args, so the return value's lifetime is +// bound to that of args. +std::unique_ptr<char*[]> CreateArgvFromArgs(std::vector<std::string>& args) { + auto result = std::make_unique<char*[]>(args.size() + 1); + for (size_t i = 0; i < args.size(); ++i) { + result[i] = &args[i][0]; + } + result[args.size()] = nullptr; // extra null terminator + return result; +} + +#ifdef GTEST_OS_WINDOWS // WindowsDeathTest implements death tests on Windows. Due to the // specifics of starting new processes on Windows, death tests there are // always threadsafe, and Google Test considers the @@ -808,7 +823,7 @@ DeathTest::TestRole WindowsDeathTest::AssumeRole() { return OVERSEE_TEST; } -#elif GTEST_OS_FUCHSIA +#elif defined(GTEST_OS_FUCHSIA) class FuchsiaDeathTest : public DeathTestImpl { public: @@ -836,36 +851,6 @@ class FuchsiaDeathTest : public DeathTestImpl { zx::socket stderr_socket_; }; -// Utility class for accumulating command-line arguments. -class Arguments { - public: - Arguments() { args_.push_back(nullptr); } - - ~Arguments() { - for (std::vector<char*>::iterator i = args_.begin(); i != args_.end(); - ++i) { - free(*i); - } - } - void AddArgument(const char* argument) { - args_.insert(args_.end() - 1, posix::StrDup(argument)); - } - - template <typename Str> - void AddArguments(const ::std::vector<Str>& arguments) { - for (typename ::std::vector<Str>::const_iterator i = arguments.begin(); - i != arguments.end(); ++i) { - args_.insert(args_.end() - 1, posix::StrDup(i->c_str())); - } - } - char* const* Argv() { return &args_[0]; } - - int size() { return static_cast<int>(args_.size()) - 1; } - - private: - std::vector<char*> args_; -}; - // Waits for the child in a death test to exit, returning its exit // status, or 0 if no child process exists. As a side effect, sets the // outcome data member. @@ -986,10 +971,10 @@ DeathTest::TestRole FuchsiaDeathTest::AssumeRole() { kInternalRunDeathTestFlag + "=" + file_ + "|" + StreamableToString(line_) + "|" + StreamableToString(death_test_index); - Arguments args; - args.AddArguments(GetInjectableArgvs()); - args.AddArgument(filter_flag.c_str()); - args.AddArgument(internal_flag.c_str()); + + std::vector<std::string> args = GetInjectableArgvs(); + args.push_back(filter_flag); + args.push_back(internal_flag); // Build the pipe for communication with the child. zx_status_t status; @@ -1041,8 +1026,14 @@ DeathTest::TestRole FuchsiaDeathTest::AssumeRole() { GTEST_DEATH_TEST_CHECK_(status == ZX_OK); // Spawn the child process. - status = fdio_spawn_etc(child_job, FDIO_SPAWN_CLONE_ALL, args.Argv()[0], - args.Argv(), nullptr, 2, spawn_actions, + // Note: The test component must have `fuchsia.process.Launcher` declared + // in its manifest. (Fuchsia integration tests require creating a + // "Fuchsia Test Component" which contains a "Fuchsia Component Manifest") + // Launching processes is a privileged operation in Fuchsia, and the + // declaration indicates that the ability is required for the component. + std::unique_ptr<char*[]> argv = CreateArgvFromArgs(args); + status = fdio_spawn_etc(child_job, FDIO_SPAWN_CLONE_ALL, argv[0], argv.get(), + nullptr, 2, spawn_actions, child_process_.reset_and_get_address(), nullptr); GTEST_DEATH_TEST_CHECK_(status == ZX_OK); @@ -1173,34 +1164,6 @@ class ExecDeathTest : public ForkingDeathTest { const int line_; }; -// Utility class for accumulating command-line arguments. -class Arguments { - public: - Arguments() { args_.push_back(nullptr); } - - ~Arguments() { - for (std::vector<char*>::iterator i = args_.begin(); i != args_.end(); - ++i) { - free(*i); - } - } - void AddArgument(const char* argument) { - args_.insert(args_.end() - 1, posix::StrDup(argument)); - } - - template <typename Str> - void AddArguments(const ::std::vector<Str>& arguments) { - for (typename ::std::vector<Str>::const_iterator i = arguments.begin(); - i != arguments.end(); ++i) { - args_.insert(args_.end() - 1, posix::StrDup(i->c_str())); - } - } - char* const* Argv() { return &args_[0]; } - - private: - std::vector<char*> args_; -}; - // A struct that encompasses the arguments to the child process of a // threadsafe-style death test process. struct ExecDeathTestArgs { @@ -1208,7 +1171,7 @@ struct ExecDeathTestArgs { int close_fd; // File descriptor to close; the read end of a pipe }; -#if GTEST_OS_QNX +#ifdef GTEST_OS_QNX extern "C" char** environ; #else // GTEST_OS_QNX // The main function for a threadsafe-style death test child process. @@ -1289,7 +1252,7 @@ static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) { ExecDeathTestArgs args = {argv, close_fd}; pid_t child_pid = -1; -#if GTEST_OS_QNX +#ifdef GTEST_OS_QNX // Obtains the current directory and sets it to be closed in the child // process. const int cwd_fd = open(".", O_RDONLY); @@ -1320,7 +1283,7 @@ static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) { GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd)); #else // GTEST_OS_QNX -#if GTEST_OS_LINUX +#ifdef GTEST_OS_LINUX // When a SIGPROF signal is received while fork() or clone() are executing, // the process may hang. To avoid this, we ignore SIGPROF here and re-enable // it after the call to fork()/clone() is complete. @@ -1367,11 +1330,10 @@ static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) { #endif // GTEST_HAS_CLONE if (use_fork && (child_pid = fork()) == 0) { - ExecDeathTestChildMain(&args); - _exit(0); + _exit(ExecDeathTestChildMain(&args)); } #endif // GTEST_OS_QNX -#if GTEST_OS_LINUX +#ifdef GTEST_OS_LINUX GTEST_DEATH_TEST_CHECK_SYSCALL_( sigaction(SIGPROF, &saved_sigprof_action, nullptr)); #endif // GTEST_OS_LINUX @@ -1410,10 +1372,9 @@ DeathTest::TestRole ExecDeathTest::AssumeRole() { StreamableToString(line_) + "|" + StreamableToString(death_test_index) + "|" + StreamableToString(pipe_fd[1]); - Arguments args; - args.AddArguments(GetArgvsForDeathTestChildProcess()); - args.AddArgument(filter_flag.c_str()); - args.AddArgument(internal_flag.c_str()); + std::vector<std::string> args = GetArgvsForDeathTestChildProcess(); + args.push_back(filter_flag); + args.push_back(internal_flag); DeathTest::set_last_death_test_message(""); @@ -1422,7 +1383,8 @@ DeathTest::TestRole ExecDeathTest::AssumeRole() { // is necessary. FlushInfoLog(); - const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]); + std::unique_ptr<char*[]> argv = CreateArgvFromArgs(args); + const pid_t child_pid = ExecDeathTestSpawnChild(argv.get(), pipe_fd[0]); GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1])); set_child_pid(child_pid); set_read_fd(pipe_fd[0]); @@ -1463,14 +1425,14 @@ bool DefaultDeathTestFactory::Create(const char* statement, } } -#if GTEST_OS_WINDOWS +#ifdef GTEST_OS_WINDOWS if (GTEST_FLAG_GET(death_test_style) == "threadsafe" || GTEST_FLAG_GET(death_test_style) == "fast") { *test = new WindowsDeathTest(statement, std::move(matcher), file, line); } -#elif GTEST_OS_FUCHSIA +#elif defined(GTEST_OS_FUCHSIA) if (GTEST_FLAG_GET(death_test_style) == "threadsafe" || GTEST_FLAG_GET(death_test_style) == "fast") { @@ -1497,7 +1459,7 @@ bool DefaultDeathTestFactory::Create(const char* statement, return true; } -#if GTEST_OS_WINDOWS +#ifdef GTEST_OS_WINDOWS // Recreates the pipe and event handles from the provided parameters, // signals the event, and returns a file descriptor wrapped around the pipe // handle. This function is called in the child process only. @@ -1564,7 +1526,7 @@ static int GetStatusFileDescriptor(unsigned int parent_process_id, // initialized from the GTEST_FLAG(internal_run_death_test) flag if // the flag is specified; otherwise returns NULL. InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() { - if (GTEST_FLAG_GET(internal_run_death_test) == "") return nullptr; + if (GTEST_FLAG_GET(internal_run_death_test).empty()) return nullptr; // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we // can use it here. @@ -1574,7 +1536,7 @@ InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() { SplitString(GTEST_FLAG_GET(internal_run_death_test), '|', &fields); int write_fd = -1; -#if GTEST_OS_WINDOWS +#ifdef GTEST_OS_WINDOWS unsigned int parent_process_id = 0; size_t write_handle_as_size_t = 0; @@ -1591,7 +1553,7 @@ InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() { write_fd = GetStatusFileDescriptor(parent_process_id, write_handle_as_size_t, event_handle_as_size_t); -#elif GTEST_OS_FUCHSIA +#elif defined(GTEST_OS_FUCHSIA) if (fields.size() != 3 || !ParseNaturalNumber(fields[1], &line) || !ParseNaturalNumber(fields[2], &index)) { diff --git a/googletest/src/gtest-filepath.cc b/googletest/src/gtest-filepath.cc index 940585db..75f52bcf 100644 --- a/googletest/src/gtest-filepath.cc +++ b/googletest/src/gtest-filepath.cc @@ -31,12 +31,15 @@ #include <stdlib.h> +#include <iterator> +#include <string> + #include "gtest/gtest-message.h" #include "gtest/internal/gtest-port.h" -#if GTEST_OS_WINDOWS_MOBILE +#ifdef GTEST_OS_WINDOWS_MOBILE #include <windows.h> -#elif GTEST_OS_WINDOWS +#elif defined(GTEST_OS_WINDOWS) #include <direct.h> #include <io.h> #else @@ -47,7 +50,7 @@ #include "gtest/internal/gtest-string.h" -#if GTEST_OS_WINDOWS +#ifdef GTEST_OS_WINDOWS #define GTEST_PATH_MAX_ _MAX_PATH #elif defined(PATH_MAX) #define GTEST_PATH_MAX_ PATH_MAX @@ -62,7 +65,7 @@ namespace testing { namespace internal { -#if GTEST_OS_WINDOWS +#ifdef GTEST_OS_WINDOWS // On Windows, '\\' is the standard path separator, but many tools and the // Windows API also accept '/' as an alternate path separator. Unless otherwise // noted, a file path can contain either kind of path separators, or a mixture @@ -70,7 +73,7 @@ namespace internal { const char kPathSeparator = '\\'; const char kAlternatePathSeparator = '/'; const char kAlternatePathSeparatorString[] = "/"; -#if GTEST_OS_WINDOWS_MOBILE +#ifdef GTEST_OS_WINDOWS_MOBILE // Windows CE doesn't have a current directory. You should not use // the current directory in tests on Windows CE, but this at least // provides a reasonable fallback. @@ -96,19 +99,20 @@ static bool IsPathSeparator(char c) { // Returns the current working directory, or "" if unsuccessful. FilePath FilePath::GetCurrentDir() { -#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || \ - GTEST_OS_WINDOWS_RT || GTEST_OS_ESP8266 || GTEST_OS_ESP32 || \ - GTEST_OS_XTENSA || GTEST_OS_QURT +#if defined(GTEST_OS_WINDOWS_MOBILE) || defined(GTEST_OS_WINDOWS_PHONE) || \ + defined(GTEST_OS_WINDOWS_RT) || defined(GTEST_OS_ESP8266) || \ + defined(GTEST_OS_ESP32) || defined(GTEST_OS_XTENSA) || \ + defined(GTEST_OS_QURT) // These platforms do not have a current directory, so we just return // something reasonable. return FilePath(kCurrentDirectoryString); -#elif GTEST_OS_WINDOWS +#elif defined(GTEST_OS_WINDOWS) char cwd[GTEST_PATH_MAX_ + 1] = {'\0'}; return FilePath(_getcwd(cwd, sizeof(cwd)) == nullptr ? "" : cwd); #else char cwd[GTEST_PATH_MAX_ + 1] = {'\0'}; char* result = getcwd(cwd, sizeof(cwd)); -#if GTEST_OS_NACL +#ifdef GTEST_OS_NACL // getcwd will likely fail in NaCl due to the sandbox, so return something // reasonable. The user may have provided a shim implementation for getcwd, // however, so fallback only when failure is detected. @@ -151,7 +155,7 @@ size_t FilePath::CalculateRootLength() const { const auto& path = pathname_; auto s = path.begin(); auto end = path.end(); -#if GTEST_OS_WINDOWS +#ifdef GTEST_OS_WINDOWS if (end - s >= 2 && s[1] == ':' && (end - s == 2 || IsPathSeparator(s[2])) && (('A' <= s[0] && s[0] <= 'Z') || ('a' <= s[0] && s[0] <= 'z'))) { // A typical absolute path like "C:\Windows" or "D:" @@ -244,7 +248,7 @@ FilePath FilePath::ConcatPaths(const FilePath& directory, // Returns true if pathname describes something findable in the file-system, // either a file, directory, or whatever. bool FilePath::FileOrDirectoryExists() const { -#if GTEST_OS_WINDOWS_MOBILE +#ifdef GTEST_OS_WINDOWS_MOBILE LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str()); const DWORD attributes = GetFileAttributes(unicode); delete[] unicode; @@ -259,7 +263,7 @@ bool FilePath::FileOrDirectoryExists() const { // that exists. bool FilePath::DirectoryExists() const { bool result = false; -#if GTEST_OS_WINDOWS +#ifdef GTEST_OS_WINDOWS // Don't strip off trailing separator if path is a root directory on // Windows (like "C:\\"). const FilePath& path(IsRootDirectory() ? *this @@ -268,7 +272,7 @@ bool FilePath::DirectoryExists() const { const FilePath& path(*this); #endif -#if GTEST_OS_WINDOWS_MOBILE +#ifdef GTEST_OS_WINDOWS_MOBILE LPCWSTR unicode = String::AnsiToUtf16(path.c_str()); const DWORD attributes = GetFileAttributes(unicode); delete[] unicode; @@ -344,14 +348,15 @@ bool FilePath::CreateDirectoriesRecursively() const { // directory for any reason, including if the parent directory does not // exist. Not named "CreateDirectory" because that's a macro on Windows. bool FilePath::CreateFolder() const { -#if GTEST_OS_WINDOWS_MOBILE +#ifdef GTEST_OS_WINDOWS_MOBILE FilePath removed_sep(this->RemoveTrailingPathSeparator()); LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str()); int result = CreateDirectory(unicode, nullptr) ? 0 : -1; delete[] unicode; -#elif GTEST_OS_WINDOWS +#elif defined(GTEST_OS_WINDOWS) int result = _mkdir(pathname_.c_str()); -#elif GTEST_OS_ESP8266 || GTEST_OS_XTENSA || GTEST_OS_QURT +#elif defined(GTEST_OS_ESP8266) || defined(GTEST_OS_XTENSA) || \ + defined(GTEST_OS_QURT) // do nothing int result = 0; #else @@ -380,7 +385,7 @@ void FilePath::Normalize() { auto out = pathname_.begin(); auto i = pathname_.cbegin(); -#if GTEST_OS_WINDOWS +#ifdef GTEST_OS_WINDOWS // UNC paths are treated specially if (pathname_.end() - i >= 3 && IsPathSeparator(*i) && IsPathSeparator(*(i + 1)) && !IsPathSeparator(*(i + 2))) { diff --git a/googletest/src/gtest-internal-inl.h b/googletest/src/gtest-internal-inl.h index 9fbcfd34..5ba557fe 100644 --- a/googletest/src/gtest-internal-inl.h +++ b/googletest/src/gtest-internal-inl.h @@ -55,7 +55,7 @@ #include <netdb.h> // NOLINT #endif -#if GTEST_OS_WINDOWS +#ifdef GTEST_OS_WINDOWS #include <windows.h> // NOLINT #endif // GTEST_OS_WINDOWS @@ -93,7 +93,7 @@ GTEST_API_ TimeInMillis GetTimeInMillis(); GTEST_API_ bool ShouldUseColor(bool stdout_is_tty); // Formats the given time in milliseconds as seconds. If the input is an exact N -// seconds, the output has a trailing decimal point (e.g., "N." intead of "N"). +// seconds, the output has a trailing decimal point (e.g., "N." instead of "N"). GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms); // Converts the given time in milliseconds to a date string in the ISO 8601 @@ -384,7 +384,7 @@ class GTEST_API_ UnitTestOptions { static bool FilterMatchesTest(const std::string& test_suite_name, const std::string& test_name); -#if GTEST_OS_WINDOWS +#ifdef GTEST_OS_WINDOWS // Function for supporting the gtest_catch_exception flag. // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the @@ -407,8 +407,8 @@ GTEST_API_ FilePath GetCurrentExecutableName(); // The role interface for getting the OS stack trace as a string. class OsStackTraceGetterInterface { public: - OsStackTraceGetterInterface() {} - virtual ~OsStackTraceGetterInterface() {} + OsStackTraceGetterInterface() = default; + virtual ~OsStackTraceGetterInterface() = default; // Returns the current OS stack trace as an std::string. Parameters: // @@ -436,13 +436,13 @@ class OsStackTraceGetterInterface { // A working implementation of the OsStackTraceGetterInterface interface. class OsStackTraceGetter : public OsStackTraceGetterInterface { public: - OsStackTraceGetter() {} + OsStackTraceGetter() = default; std::string CurrentStackTrace(int max_depth, int skip_count) override; void UponLeavingGTest() override; private: -#if GTEST_HAS_ABSL +#ifdef GTEST_HAS_ABSL Mutex mutex_; // Protects all internal state. // We save the stack frame below the frame that calls user code. @@ -672,7 +672,7 @@ class GTEST_API_ UnitTestImpl { void AddTestInfo(internal::SetUpTestSuiteFunc set_up_tc, internal::TearDownTestSuiteFunc tear_down_tc, TestInfo* test_info) { -#if GTEST_HAS_DEATH_TEST +#ifdef GTEST_HAS_DEATH_TEST // In order to support thread-safe death tests, we need to // remember the original working directory when the test program // was first invoked. We cannot do this in RUN_ALL_TESTS(), as @@ -778,7 +778,7 @@ class GTEST_API_ UnitTestImpl { return gtest_trace_stack_.get(); } -#if GTEST_HAS_DEATH_TEST +#ifdef GTEST_HAS_DEATH_TEST void InitDeathTestSubprocessControlInfo() { internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag()); } @@ -943,7 +943,7 @@ class GTEST_API_ UnitTestImpl { // How long the test took to run, in milliseconds. TimeInMillis elapsed_time_; -#if GTEST_HAS_DEATH_TEST +#ifdef GTEST_HAS_DEATH_TEST // The decomposed components of the gtest_internal_run_death_test flag, // parsed when RUN_ALL_TESTS is called. std::unique_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_; @@ -967,7 +967,7 @@ inline UnitTestImpl* GetUnitTestImpl() { return UnitTest::GetInstance()->impl(); } -#if GTEST_USES_SIMPLE_RE +#ifdef GTEST_USES_SIMPLE_RE // Internal helper functions for implementing the simple regular // expression matcher. @@ -993,7 +993,7 @@ GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str); GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv); GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv); -#if GTEST_HAS_DEATH_TEST +#ifdef GTEST_HAS_DEATH_TEST // Returns the message describing the last system error, regardless of the // platform. @@ -1064,7 +1064,7 @@ class StreamingListener : public EmptyTestEventListener { // Abstract base class for writing strings to a socket. class AbstractSocketWriter { public: - virtual ~AbstractSocketWriter() {} + virtual ~AbstractSocketWriter() = default; // Sends a string to the socket. virtual void Send(const std::string& message) = 0; diff --git a/googletest/src/gtest-port.cc b/googletest/src/gtest-port.cc index d797fe4d..77b618c4 100644 --- a/googletest/src/gtest-port.cc +++ b/googletest/src/gtest-port.cc @@ -37,8 +37,12 @@ #include <cstdint> #include <fstream> #include <memory> +#include <ostream> +#include <string> +#include <utility> +#include <vector> -#if GTEST_OS_WINDOWS +#ifdef GTEST_OS_WINDOWS #include <io.h> #include <sys/stat.h> #include <windows.h> @@ -51,32 +55,34 @@ #include <unistd.h> #endif // GTEST_OS_WINDOWS -#if GTEST_OS_MAC +#ifdef GTEST_OS_MAC #include <mach/mach_init.h> #include <mach/task.h> #include <mach/vm_map.h> #endif // GTEST_OS_MAC -#if GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \ - GTEST_OS_NETBSD || GTEST_OS_OPENBSD +#if defined(GTEST_OS_DRAGONFLY) || defined(GTEST_OS_FREEBSD) || \ + defined(GTEST_OS_GNU_KFREEBSD) || defined(GTEST_OS_NETBSD) || \ + defined(GTEST_OS_OPENBSD) #include <sys/sysctl.h> -#if GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD +#if defined(GTEST_OS_DRAGONFLY) || defined(GTEST_OS_FREEBSD) || \ + defined(GTEST_OS_GNU_KFREEBSD) #include <sys/user.h> #endif #endif -#if GTEST_OS_QNX +#ifdef GTEST_OS_QNX #include <devctl.h> #include <fcntl.h> #include <sys/procfs.h> #endif // GTEST_OS_QNX -#if GTEST_OS_AIX +#ifdef GTEST_OS_AIX #include <procinfo.h> #include <sys/types.h> #endif // GTEST_OS_AIX -#if GTEST_OS_FUCHSIA +#ifdef GTEST_OS_FUCHSIA #include <zircon/process.h> #include <zircon/syscalls.h> #endif // GTEST_OS_FUCHSIA @@ -90,7 +96,7 @@ namespace testing { namespace internal { -#if GTEST_OS_LINUX || GTEST_OS_GNU_HURD +#if defined(GTEST_OS_LINUX) || defined(GTEST_OS_GNU_HURD) namespace { template <typename T> @@ -113,7 +119,7 @@ size_t GetThreadCount() { return ReadProcFileField<size_t>(filename, 19); } -#elif GTEST_OS_MAC +#elif defined(GTEST_OS_MAC) size_t GetThreadCount() { const task_t task = mach_task_self(); @@ -131,20 +137,20 @@ size_t GetThreadCount() { } } -#elif GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \ - GTEST_OS_NETBSD +#elif defined(GTEST_OS_DRAGONFLY) || defined(GTEST_OS_FREEBSD) || \ + defined(GTEST_OS_GNU_KFREEBSD) || defined(GTEST_OS_NETBSD) -#if GTEST_OS_NETBSD +#ifdef GTEST_OS_NETBSD #undef KERN_PROC #define KERN_PROC KERN_PROC2 #define kinfo_proc kinfo_proc2 #endif -#if GTEST_OS_DRAGONFLY +#ifdef GTEST_OS_DRAGONFLY #define KP_NLWP(kp) (kp.kp_nthreads) -#elif GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD +#elif defined(GTEST_OS_FREEBSD) || defined(GTEST_OS_GNU_KFREEBSD) #define KP_NLWP(kp) (kp.ki_numthreads) -#elif GTEST_OS_NETBSD +#elif defined(GTEST_OS_NETBSD) #define KP_NLWP(kp) (kp.p_nlwps) #endif @@ -156,7 +162,7 @@ size_t GetThreadCount() { KERN_PROC, KERN_PROC_PID, getpid(), -#if GTEST_OS_NETBSD +#ifdef GTEST_OS_NETBSD sizeof(struct kinfo_proc), 1, #endif @@ -169,7 +175,7 @@ size_t GetThreadCount() { } return static_cast<size_t>(KP_NLWP(info)); } -#elif GTEST_OS_OPENBSD +#elif defined(GTEST_OS_OPENBSD) // Returns the number of threads running in the process, or 0 to indicate that // we cannot detect it. @@ -206,7 +212,7 @@ size_t GetThreadCount() { return nthreads; } -#elif GTEST_OS_QNX +#elif defined(GTEST_OS_QNX) // Returns the number of threads running in the process, or 0 to indicate that // we cannot detect it. @@ -226,7 +232,7 @@ size_t GetThreadCount() { } } -#elif GTEST_OS_AIX +#elif defined(GTEST_OS_AIX) size_t GetThreadCount() { struct procentry64 entry; @@ -239,7 +245,7 @@ size_t GetThreadCount() { } } -#elif GTEST_OS_FUCHSIA +#elif defined(GTEST_OS_FUCHSIA) size_t GetThreadCount() { int dummy_buffer; @@ -264,7 +270,7 @@ size_t GetThreadCount() { #endif // GTEST_OS_LINUX -#if GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS +#if defined(GTEST_IS_THREADSAFE) && defined(GTEST_OS_WINDOWS) AutoHandle::AutoHandle() : handle_(INVALID_HANDLE_VALUE) {} @@ -655,7 +661,7 @@ void ThreadLocalRegistry::OnThreadLocalDestroyed( #endif // GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS -#if GTEST_USES_POSIX_RE +#ifdef GTEST_USES_POSIX_RE // Implements RE. Currently only needed for death tests. @@ -668,7 +674,6 @@ RE::~RE() { regfree(&partial_regex_); regfree(&full_regex_); } - free(const_cast<char*>(pattern_)); } // Returns true if and only if regular expression re matches the entire str. @@ -690,7 +695,7 @@ bool RE::PartialMatch(const char* str, const RE& re) { // Initializes an RE from its string representation. void RE::Init(const char* regex) { - pattern_ = posix::StrDup(regex); + pattern_ = regex; // Reserves enough bytes to hold the regular expression used for a // full match. @@ -718,7 +723,7 @@ void RE::Init(const char* regex) { delete[] full_pattern; } -#elif GTEST_USES_SIMPLE_RE +#elif defined(GTEST_USES_SIMPLE_RE) // Returns true if and only if ch appears anywhere in str (excluding the // terminating '\0' character). @@ -920,27 +925,26 @@ bool MatchRegexAnywhere(const char* regex, const char* str) { // Implements the RE class. -RE::~RE() { - free(const_cast<char*>(pattern_)); - free(const_cast<char*>(full_pattern_)); -} +RE::~RE() = default; // Returns true if and only if regular expression re matches the entire str. bool RE::FullMatch(const char* str, const RE& re) { - return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str); + return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_.c_str(), str); } // Returns true if and only if regular expression re matches a substring of // str (including str itself). bool RE::PartialMatch(const char* str, const RE& re) { - return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str); + return re.is_valid_ && MatchRegexAnywhere(re.pattern_.c_str(), str); } // Initializes an RE from its string representation. void RE::Init(const char* regex) { - pattern_ = full_pattern_ = nullptr; + full_pattern_.clear(); + pattern_.clear(); + if (regex != nullptr) { - pattern_ = posix::StrDup(regex); + pattern_ = regex; } is_valid_ = ValidateRegex(regex); @@ -949,25 +953,19 @@ void RE::Init(const char* regex) { return; } - const size_t len = strlen(regex); // Reserves enough bytes to hold the regular expression used for a - // full match: we need space to prepend a '^', append a '$', and - // terminate the string with '\0'. - char* buffer = static_cast<char*>(malloc(len + 3)); - full_pattern_ = buffer; + // full match: we need space to prepend a '^' and append a '$'. + full_pattern_.reserve(pattern_.size() + 2); - if (*regex != '^') - *buffer++ = '^'; // Makes sure full_pattern_ starts with '^'. - - // We don't use snprintf or strncpy, as they trigger a warning when - // compiled with VC++ 8.0. - memcpy(buffer, regex, len); - buffer += len; + if (pattern_.empty() || pattern_.front() != '^') { + full_pattern_.push_back('^'); // Makes sure full_pattern_ starts with '^'. + } - if (len == 0 || regex[len - 1] != '$') - *buffer++ = '$'; // Makes sure full_pattern_ ends with '$'. + full_pattern_.append(pattern_); - *buffer = '\0'; + if (pattern_.empty() || pattern_.back() != '$') { + full_pattern_.push_back('$'); // Makes sure full_pattern_ ends with '$'. + } } #endif // GTEST_USES_POSIX_RE @@ -1035,7 +1033,7 @@ class CapturedStream { public: // The ctor redirects the stream to a temporary file. explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) { -#if GTEST_OS_WINDOWS +#ifdef GTEST_OS_WINDOWS char temp_dir_path[MAX_PATH + 1] = {'\0'}; // NOLINT char temp_file_path[MAX_PATH + 1] = {'\0'}; // NOLINT @@ -1054,7 +1052,7 @@ class CapturedStream { // directory, so we create the temporary file in a temporary directory. std::string name_template; -#if GTEST_OS_LINUX_ANDROID +#ifdef GTEST_OS_LINUX_ANDROID // Note: Android applications are expected to call the framework's // Context.getExternalStorageDirectory() method through JNI to get // the location of the world-writable SD Card directory. However, @@ -1067,7 +1065,7 @@ class CapturedStream { // '/sdcard' and other variants cannot be relied on, as they are not // guaranteed to be mounted, or may have a delay in mounting. name_template = "/data/local/tmp/"; -#elif GTEST_OS_IOS +#elif defined(GTEST_OS_IOS) char user_temp_dir[PATH_MAX + 1]; // Documented alternative to NSTemporaryDirectory() (for obtaining creating @@ -1227,7 +1225,7 @@ std::string ReadEntireFile(FILE* file) { return content; } -#if GTEST_HAS_DEATH_TEST +#ifdef GTEST_HAS_DEATH_TEST static const std::vector<std::string>* g_injected_test_argvs = nullptr; // Owned. @@ -1254,7 +1252,7 @@ void ClearInjectableArgvs() { } #endif // GTEST_HAS_DEATH_TEST -#if GTEST_OS_WINDOWS_MOBILE +#ifdef GTEST_OS_WINDOWS_MOBILE namespace posix { void Abort() { DebugBreak(); diff --git a/googletest/src/gtest-printers.cc b/googletest/src/gtest-printers.cc index d475ad36..2b470678 100644 --- a/googletest/src/gtest-printers.cc +++ b/googletest/src/gtest-printers.cc @@ -47,6 +47,8 @@ #include <cctype> #include <cstdint> #include <cwchar> +#include <iomanip> +#include <ios> #include <ostream> // NOLINT #include <string> #include <type_traits> @@ -528,7 +530,7 @@ void PrintStringTo(const ::std::string& s, ostream* os) { } } -#ifdef __cpp_char8_t +#ifdef __cpp_lib_char8_t void PrintU8StringTo(const ::std::u8string& s, ostream* os) { PrintCharsAsStringTo(s.data(), s.size(), os); } diff --git a/googletest/src/gtest-test-part.cc b/googletest/src/gtest-test-part.cc index eb7c8d1c..6f8ddd7c 100644 --- a/googletest/src/gtest-test-part.cc +++ b/googletest/src/gtest-test-part.cc @@ -32,13 +32,14 @@ #include "gtest/gtest-test-part.h" +#include <ostream> +#include <string> + #include "gtest/internal/gtest-port.h" #include "src/gtest-internal-inl.h" namespace testing { -using internal::GetUnitTestImpl; - // Gets the summary of the failure message by omitting the stack trace // in it. std::string TestPartResult::ExtractSummary(const char* message) { diff --git a/googletest/src/gtest-typed-test.cc b/googletest/src/gtest-typed-test.cc index a2828b83..b251c09d 100644 --- a/googletest/src/gtest-typed-test.cc +++ b/googletest/src/gtest-typed-test.cc @@ -29,6 +29,10 @@ #include "gtest/gtest-typed-test.h" +#include <set> +#include <string> +#include <vector> + #include "gtest/gtest.h" namespace testing { @@ -90,7 +94,7 @@ const char* TypedTestSuitePState::VerifyRegisteredTestNames( } const std::string& errors_str = errors.GetString(); - if (errors_str != "") { + if (!errors_str.empty()) { fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(), errors_str.c_str()); fflush(stderr); diff --git a/googletest/src/gtest.cc b/googletest/src/gtest.cc index f79f915f..fb7512c1 100644 --- a/googletest/src/gtest.cc +++ b/googletest/src/gtest.cc @@ -44,16 +44,21 @@ #include <chrono> // NOLINT #include <cmath> #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" @@ -61,7 +66,7 @@ #include "gtest/internal/custom/gtest.h" #include "gtest/internal/gtest-port.h" -#if GTEST_OS_LINUX +#ifdef GTEST_OS_LINUX #include <fcntl.h> // NOLINT #include <limits.h> // NOLINT @@ -74,18 +79,18 @@ #include <string> -#elif GTEST_OS_ZOS +#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 GTEST_OS_WINDOWS_MOBILE // We are on Windows CE. +#elif defined(GTEST_OS_WINDOWS_MOBILE) // We are on Windows CE. #include <windows.h> // NOLINT #undef min -#elif GTEST_OS_WINDOWS // We are on Windows proper. +#elif defined(GTEST_OS_WINDOWS) // We are on Windows proper. #include <windows.h> // NOLINT #undef min @@ -99,7 +104,7 @@ #include <sys/timeb.h> // NOLINT #include <sys/types.h> // NOLINT -#if GTEST_OS_WINDOWS_MINGW +#ifdef GTEST_OS_WINDOWS_MINGW #include <sys/time.h> // NOLINT #endif // GTEST_OS_WINDOWS_MINGW @@ -125,17 +130,18 @@ #include "src/gtest-internal-inl.h" -#if GTEST_OS_WINDOWS +#ifdef GTEST_OS_WINDOWS #define vsnprintf _vsnprintf #endif // GTEST_OS_WINDOWS -#if GTEST_OS_MAC +#ifdef GTEST_OS_MAC #ifndef GTEST_OS_IOS #include <crt_externs.h> #endif #endif -#if GTEST_HAS_ABSL +#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" @@ -143,6 +149,8 @@ #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 @@ -408,7 +416,7 @@ 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() { return GetArgvs().size() > 0; } +static bool GTestIsInitialized() { return !GetArgvs().empty(); } // Iterates over a vector of TestSuites, keeping a running sum of the // results of calling a given int-returning method on each. @@ -630,7 +638,7 @@ static ::std::vector<std::string> g_argvs; FilePath GetCurrentExecutableName() { FilePath result; -#if GTEST_OS_WINDOWS || GTEST_OS_OS2 +#if defined(GTEST_OS_WINDOWS) || defined(GTEST_OS_OS2) result.Set(FilePath(GetArgvs()[0]).RemoveExtension("exe")); #else result.Set(FilePath(GetArgvs()[0])); @@ -1165,7 +1173,7 @@ TimeInMillis GetTimeInMillis() { // class String. -#if GTEST_OS_WINDOWS_MOBILE +#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 @@ -1867,14 +1875,14 @@ AssertionResult IsNotSubstring(const char* needle_expr, namespace internal { -#if GTEST_OS_WINDOWS +#ifdef GTEST_OS_WINDOWS namespace { // Helper function for IsHRESULT{SuccessFailure} predicates AssertionResult HRESULTFailureHelper(const char* expr, const char* expected, long hr) { // NOLINT -#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_TV_TITLE +#if defined(GTEST_OS_WINDOWS_MOBILE) || defined(GTEST_OS_WINDOWS_TV_TITLE) // Windows CE doesn't support FormatMessage. const char error_text[] = ""; @@ -2135,9 +2143,9 @@ bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs, if (rhs == nullptr) return false; -#if GTEST_OS_WINDOWS +#ifdef GTEST_OS_WINDOWS return _wcsicmp(lhs, rhs) == 0; -#elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID +#elif defined(GTEST_OS_LINUX) && !defined(GTEST_OS_LINUX_ANDROID) return wcscasecmp(lhs, rhs) == 0; #else // Android, Mac OS X and Cygwin don't define wcscasecmp. @@ -2237,7 +2245,7 @@ TestResult::TestResult() : death_test_count_(0), start_timestamp_(0), elapsed_time_(0) {} // D'tor. -TestResult::~TestResult() {} +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, @@ -2325,7 +2333,9 @@ static std::vector<std::string> GetReservedAttributesForElement( return std::vector<std::string>(); } +#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) { if (xml_element == "testsuites") { @@ -2340,6 +2350,7 @@ static std::vector<std::string> GetReservedOutputAttributesForElement( // This code is unreachable but some compilers may not realizes that. return std::vector<std::string>(); } +#endif static std::string FormatWordList(const std::vector<std::string>& words) { Message word_list; @@ -2443,7 +2454,7 @@ Test::Test() : gtest_flag_saver_(new GTEST_FLAG_SAVER_) {} // 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() {} +Test::~Test() = default; // Sets up the test fixture. // @@ -2978,6 +2989,25 @@ void TestSuite::Run() { TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater(); + // Ensure our tests are in a deterministic order. + // + // We do this by sorting lexicographically on (file, line number), providing + // an order matching what the user can see in the source code. + // + // In the common case the line number comparison shouldn't be necessary, + // because the registrations made by the TEST macro are executed in order + // within a translation unit. But this is not true of the manual registration + // API, and in more exotic scenarios a single file may be part of multiple + // translation units. + std::stable_sort(test_info_list_.begin(), test_info_list_.end(), + [](const TestInfo* const a, const TestInfo* const b) { + if (const int result = std::strcmp(a->file(), b->file())) { + return result < 0; + } + + return a->line() < b->line(); + }); + // Call both legacy and the new API repeater->OnTestSuiteStart(*this); // Legacy API is deprecated but still available @@ -3141,7 +3171,7 @@ static void PrintTestPartResult(const TestPartResult& test_part_result) { // following statements add the test part result message to the Output // window such that the user can double-click on it to jump to the // corresponding source code location; otherwise they do nothing. -#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE +#if defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_MOBILE) // We don't call OutputDebugString*() on Windows Mobile, as printing // to stdout is done by OutputDebugString() there already - we don't // want the same message printed twice. @@ -3151,8 +3181,9 @@ static void PrintTestPartResult(const TestPartResult& test_part_result) { } // class PrettyUnitTestResultPrinter -#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && \ - !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW +#if defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_MOBILE) && \ + !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) { @@ -3224,7 +3255,7 @@ bool ShouldUseColor(bool stdout_is_tty) { const char* const gtest_color = c.c_str(); if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) { -#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW +#if defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_MINGW) // On Windows the TERM variable is usually not set, but the // console there does support colors. return stdout_is_tty; @@ -3279,8 +3310,9 @@ static void ColoredPrintf(GTestColor color, const char* fmt, ...) { return; } -#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && \ - !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW +#if defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_MOBILE) && \ + !defined(GTEST_OS_WINDOWS_PHONE) && !defined(GTEST_OS_WINDOWS_RT) && \ + !defined(GTEST_OS_WINDOWS_MINGW) const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE); // Gets the current text color. @@ -3334,7 +3366,7 @@ static void PrintFullTestCommentIfPresent(const TestInfo& test_info) { // Class PrettyUnitTestResultPrinter is copyable. class PrettyUnitTestResultPrinter : public TestEventListener { public: - PrettyUnitTestResultPrinter() {} + PrettyUnitTestResultPrinter() = default; static void PrintTestName(const char* test_suite, const char* test) { printf("%s.%s", test_suite, test); } @@ -3642,7 +3674,7 @@ void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, // Class BriefUnitTestResultPrinter is copyable. class BriefUnitTestResultPrinter : public TestEventListener { public: - BriefUnitTestResultPrinter() {} + BriefUnitTestResultPrinter() = default; static void PrintTestName(const char* test_suite, const char* test) { printf("%s.%s", test_suite, test); } @@ -3757,28 +3789,28 @@ class TestEventRepeater : public TestEventListener { bool forwarding_enabled() const { return forwarding_enabled_; } void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; } - void OnTestProgramStart(const UnitTest& unit_test) override; + void OnTestProgramStart(const UnitTest& parameter) override; void OnTestIterationStart(const UnitTest& unit_test, int iteration) override; - void OnEnvironmentsSetUpStart(const UnitTest& unit_test) override; - void OnEnvironmentsSetUpEnd(const UnitTest& unit_test) override; + void OnEnvironmentsSetUpStart(const UnitTest& parameter) override; + void OnEnvironmentsSetUpEnd(const UnitTest& parameter) override; // Legacy API is deprecated but still available #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ void OnTestCaseStart(const TestSuite& parameter) override; #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ void OnTestSuiteStart(const TestSuite& parameter) override; - void OnTestStart(const TestInfo& test_info) override; - void OnTestDisabled(const TestInfo& test_info) override; - void OnTestPartResult(const TestPartResult& result) override; - void OnTestEnd(const TestInfo& test_info) override; + void OnTestStart(const TestInfo& parameter) override; + void OnTestDisabled(const TestInfo& parameter) override; + void OnTestPartResult(const TestPartResult& parameter) override; + void OnTestEnd(const TestInfo& parameter) override; // Legacy API is deprecated but still available #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ void OnTestCaseEnd(const TestCase& parameter) override; #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ void OnTestSuiteEnd(const TestSuite& parameter) override; - void OnEnvironmentsTearDownStart(const UnitTest& unit_test) override; - void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) override; + void OnEnvironmentsTearDownStart(const UnitTest& parameter) override; + void OnEnvironmentsTearDownEnd(const UnitTest& parameter) override; void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override; - void OnTestProgramEnd(const UnitTest& unit_test) override; + void OnTestProgramEnd(const UnitTest& parameter) override; private: // Controls whether events will be forwarded to listeners_. Set to false @@ -4953,7 +4985,7 @@ const char* const OsStackTraceGetterInterface::kElidedFramesMarker = std::string OsStackTraceGetter::CurrentStackTrace(int max_depth, int skip_count) GTEST_LOCK_EXCLUDED_(mutex_) { -#if GTEST_HAS_ABSL +#ifdef GTEST_HAS_ABSL std::string result; if (max_depth <= 0) { @@ -5002,7 +5034,7 @@ std::string OsStackTraceGetter::CurrentStackTrace(int max_depth, int skip_count) } void OsStackTraceGetter::UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_) { -#if GTEST_HAS_ABSL +#ifdef GTEST_HAS_ABSL void* caller_frame = nullptr; if (absl::GetStackTrace(&caller_frame, 1, 3) <= 0) { caller_frame = nullptr; @@ -5013,7 +5045,7 @@ void OsStackTraceGetter::UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_) { #endif // GTEST_HAS_ABSL } -#if GTEST_HAS_DEATH_TEST +#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 { @@ -5033,7 +5065,7 @@ class ScopedPrematureExitFile { } ~ScopedPrematureExitFile() { -#if !GTEST_OS_ESP8266 +#ifndef GTEST_OS_ESP8266 if (!premature_exit_filepath_.empty()) { int retval = remove(premature_exit_filepath_.c_str()); if (retval) { @@ -5301,7 +5333,7 @@ void UnitTest::AddTestPartResult(TestPartResult::Type result_type, msg << message; internal::MutexLock lock(&mutex_); - if (impl_->gtest_trace_stack().size() > 0) { + if (!impl_->gtest_trace_stack().empty()) { msg << "\n" << GTEST_NAME_ << " trace:"; for (size_t i = impl_->gtest_trace_stack().size(); i > 0; --i) { @@ -5314,6 +5346,8 @@ void UnitTest::AddTestPartResult(TestPartResult::Type result_type, if (os_stack_trace.c_str() != nullptr && !os_stack_trace.empty()) { msg << internal::kStackTraceMarker << os_stack_trace; + } else { + msg << "\n"; } const TestPartResult result = TestPartResult( @@ -5329,7 +5363,8 @@ void UnitTest::AddTestPartResult(TestPartResult::Type result_type, // with another testing framework) and specify the former on the // command line for debugging. if (GTEST_FLAG_GET(break_on_failure)) { -#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT +#if defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_PHONE) && \ + !defined(GTEST_OS_WINDOWS_RT) // Using DebugBreak on Windows allows gtest to still break into a debugger // when a failure happens and both the --gtest_break_on_failure and // the --gtest_catch_exceptions flags are specified. @@ -5377,7 +5412,7 @@ void UnitTest::RecordProperty(const std::string& key, // We don't protect this under mutex_, as we only support calling it // from the main thread. int UnitTest::Run() { -#if GTEST_HAS_DEATH_TEST +#ifdef GTEST_HAS_DEATH_TEST const bool in_death_test_child_process = GTEST_FLAG_GET(internal_run_death_test).length() > 0; @@ -5406,32 +5441,36 @@ int UnitTest::Run() { in_death_test_child_process ? nullptr : internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE")); +#else + const bool in_death_test_child_process = false; #endif // GTEST_HAS_DEATH_TEST // Captures the value of GTEST_FLAG(catch_exceptions). This value will be // used for the duration of the program. impl()->set_catch_exceptions(GTEST_FLAG_GET(catch_exceptions)); -#if GTEST_OS_WINDOWS +#ifdef GTEST_OS_WINDOWS // Either the user wants Google Test to catch exceptions thrown by the // tests or this is executing in the context of death test child // process. In either case the user does not want to see pop-up dialogs // about crashes - they are expected. if (impl()->catch_exceptions() || in_death_test_child_process) { -#if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT +#if !defined(GTEST_OS_WINDOWS_MOBILE) && !defined(GTEST_OS_WINDOWS_PHONE) && \ + !defined(GTEST_OS_WINDOWS_RT) // SetErrorMode doesn't exist on CE. SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX); #endif // !GTEST_OS_WINDOWS_MOBILE -#if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE +#if (defined(_MSC_VER) || defined(GTEST_OS_WINDOWS_MINGW)) && \ + !defined(GTEST_OS_WINDOWS_MOBILE) // Death test children can be terminated with _abort(). On Windows, // _abort() can show a dialog with a warning message. This forces the // abort message to go to stderr instead. _set_error_mode(_OUT_TO_STDERR); #endif -#if defined(_MSC_VER) && !GTEST_OS_WINDOWS_MOBILE +#if defined(_MSC_VER) && !defined(GTEST_OS_WINDOWS_MOBILE) // In the debug version, Visual Studio pops up a separate dialog // offering a choice to debug the aborted program. We need to suppress // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement @@ -5453,6 +5492,8 @@ int UnitTest::Run() { } #endif } +#else + (void)in_death_test_child_process; // Needed inside the #if block above #endif // GTEST_OS_WINDOWS return internal::HandleExceptionsInMethodIfSupported( @@ -5548,7 +5589,7 @@ UnitTestImpl::UnitTestImpl(UnitTest* parent) random_(0), // Will be reseeded before first use. start_timestamp_(0), elapsed_time_(0), -#if GTEST_HAS_DEATH_TEST +#ifdef GTEST_HAS_DEATH_TEST death_test_factory_(new DefaultDeathTestFactory), #endif // Will be overridden by the flag before first use. @@ -5588,11 +5629,11 @@ void UnitTestImpl::RecordProperty(const TestProperty& test_property) { test_result->RecordProperty(xml_element, test_property); } -#if GTEST_HAS_DEATH_TEST +#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() { - if (internal_run_death_test_flag_.get() != nullptr) + if (internal_run_death_test_flag_ != nullptr) listeners()->SuppressEventForwarding(); } #endif // GTEST_HAS_DEATH_TEST @@ -5608,7 +5649,7 @@ void UnitTestImpl::ConfigureXmlOutput() { } else if (output_format == "json") { listeners()->SetDefaultXmlGenerator(new JsonUnitTestResultPrinter( UnitTestOptions::GetAbsolutePathToOutputFile().c_str())); - } else if (output_format != "") { + } else if (!output_format.empty()) { GTEST_LOG_(WARNING) << "WARNING: unrecognized output format \"" << output_format << "\" ignored."; } @@ -5651,7 +5692,7 @@ void UnitTestImpl::PostFlagParsingInit() { listeners()->Append(new GTEST_CUSTOM_TEST_EVENT_LISTENER_()); #endif // defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_) -#if GTEST_HAS_DEATH_TEST +#ifdef GTEST_HAS_DEATH_TEST InitDeathTestSubprocessControlInfo(); SuppressTestEventsIfInSubprocess(); #endif // GTEST_HAS_DEATH_TEST @@ -5674,7 +5715,7 @@ void UnitTestImpl::PostFlagParsingInit() { ConfigureStreamingOutput(); #endif // GTEST_CAN_STREAM_RESULTS_ -#if GTEST_HAS_ABSL +#ifdef GTEST_HAS_ABSL if (GTEST_FLAG_GET(install_failure_signal_handler)) { absl::FailureSignalHandlerOptions options; absl::InstallFailureSignalHandler(options); @@ -5789,9 +5830,8 @@ bool UnitTestImpl::RunAllTests() { // death test. bool in_subprocess_for_death_test = false; -#if GTEST_HAS_DEATH_TEST - in_subprocess_for_death_test = - (internal_run_death_test_flag_.get() != nullptr); +#ifdef GTEST_HAS_DEATH_TEST + in_subprocess_for_death_test = (internal_run_death_test_flag_ != nullptr); #if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_) if (in_subprocess_for_death_test) { GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_(); @@ -5954,10 +5994,6 @@ bool UnitTestImpl::RunAllTests() { "() before calling RUN_ALL_TESTS(). This is INVALID. Soon " GTEST_NAME_ " will start to enforce the valid usage. " "Please fix it ASAP, or IT WILL START TO FAIL.\n"); // NOLINT -#if GTEST_FOR_GOOGLE_ - ColoredPrintf(GTestColor::kRed, - "For more details, see http://wiki/Main/ValidGUnitMain.\n"); -#endif // GTEST_FOR_GOOGLE_ } return !failed; @@ -6513,7 +6549,7 @@ static const char kColorEncodedHelpMessage[] = #endif // GTEST_CAN_STREAM_RESULTS_ "\n" "Assertion Behavior:\n" -#if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS +#if defined(GTEST_HAS_DEATH_TEST) && !defined(GTEST_OS_WINDOWS) " @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n" " Set the default death test style.\n" @@ -6654,26 +6690,60 @@ void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) { } // Parses the command line for Google Test flags, without initializing -// other parts of Google Test. +// 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) { -#if GTEST_HAS_ABSL - if (*argc > 0) { - // absl::ParseCommandLine() requires *argc > 0. - auto positional_args = absl::flags_internal::ParseCommandLineImpl( - *argc, argv, absl::flags_internal::ArgvListAction::kRemoveParsedArgs, - absl::flags_internal::UsageFlagsAction::kHandleUsage, - absl::flags_internal::OnUndefinedFlag::kReportUndefined); - // Any command-line positional arguments not part of any command-line flag - // (or arguments to a flag) are copied back out to argv, with the program - // invocation name at position 0, and argc is resized. This includes - // positional arguments after the flag-terminating delimiter '--'. - // See https://abseil.io/docs/cpp/guides/flags. - std::copy(positional_args.begin(), positional_args.end(), argv); - if (static_cast<int>(positional_args.size()) < *argc) { - argv[positional_args.size()] = nullptr; - *argc = static_cast<int>(positional_args.size()); +#ifdef GTEST_HAS_ABSL + if (*argc <= 0) return; + + std::vector<char*> positional_args; + std::vector<absl::UnrecognizedFlag> unrecognized_flags; + absl::ParseAbseilFlagsOnly(*argc, argv, positional_args, unrecognized_flags); + absl::flat_hash_set<absl::string_view> unrecognized; + for (const auto& flag : unrecognized_flags) { + unrecognized.insert(flag.flag_name); + } + absl::flat_hash_set<char*> positional; + for (const auto& arg : positional_args) { + positional.insert(arg); + } + + int out_pos = 1; + int in_pos = 1; + for (; in_pos < *argc; ++in_pos) { + char* arg = argv[in_pos]; + absl::string_view arg_str(arg); + if (absl::ConsumePrefix(&arg_str, "--")) { + // Flag-like argument. If the flag was unrecognized, keep it. + // If it was a GoogleTest flag, remove it. + if (unrecognized.contains(arg_str)) { + argv[out_pos++] = argv[in_pos]; + continue; + } } + + if (arg_str.empty()) { + ++in_pos; + break; // '--' indicates that the rest of the arguments are positional + } + + // Probably a positional argument. If it is in fact positional, keep it. + // If it was a value for the flag argument, remove it. + if (positional.contains(arg)) { + argv[out_pos++] = arg; + } + } + + // The rest are positional args for sure. + while (in_pos < *argc) { + argv[out_pos++] = argv[in_pos++]; } + + *argc = out_pos; + argv[out_pos] = nullptr; #else ParseGoogleTestFlagsOnlyImpl(argc, argv); #endif @@ -6681,7 +6751,7 @@ void ParseGoogleTestFlagsOnly(int* argc, char** argv) { // Fix the value of *_NSGetArgc() on macOS, but if and only if // *_NSGetArgv() == argv // Only applicable to char** version of argv -#if GTEST_OS_MAC +#ifdef GTEST_OS_MAC #ifndef GTEST_OS_IOS if (*_NSGetArgv() == argv) { *_NSGetArgc() = *argc; @@ -6709,7 +6779,7 @@ void InitGoogleTestImpl(int* argc, CharType** argv) { g_argvs.push_back(StreamableToString(argv[i])); } -#if GTEST_HAS_ABSL +#ifdef GTEST_HAS_ABSL absl::InitializeSymbolizer(g_argvs[0].c_str()); // When using the Abseil Flags library, set the program usage message to the @@ -6793,16 +6863,16 @@ static std::string GetDirFromEnv( std::string TempDir() { #if defined(GTEST_CUSTOM_TEMPDIR_FUNCTION_) return GTEST_CUSTOM_TEMPDIR_FUNCTION_(); -#elif GTEST_OS_WINDOWS || GTEST_OS_WINDOWS_MOBILE +#elif defined(GTEST_OS_WINDOWS) || defined(GTEST_OS_WINDOWS_MOBILE) return GetDirFromEnv({"TEST_TMPDIR", "TEMP"}, "\\temp\\", '\\'); -#elif GTEST_OS_LINUX_ANDROID +#elif defined(GTEST_OS_LINUX_ANDROID) return GetDirFromEnv({"TEST_TMPDIR", "TMPDIR"}, "/data/local/tmp/", '/'); #else return GetDirFromEnv({"TEST_TMPDIR", "TMPDIR"}, "/tmp/", '/'); #endif } -#if !defined(GTEST_CUSTOM_SRCDIR_FUNCTION_) +#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() { @@ -6811,13 +6881,14 @@ static std::string GetCurrentExecutableDirectory() { } #endif +#if GTEST_HAS_FILE_SYSTEM std::string SrcDir() { #if defined(GTEST_CUSTOM_SRCDIR_FUNCTION_) return GTEST_CUSTOM_SRCDIR_FUNCTION_(); -#elif GTEST_OS_WINDOWS || GTEST_OS_WINDOWS_MOBILE +#elif defined(GTEST_OS_WINDOWS) || defined(GTEST_OS_WINDOWS_MOBILE) return GetDirFromEnv({"TEST_SRCDIR"}, GetCurrentExecutableDirectory().c_str(), '\\'); -#elif GTEST_OS_LINUX_ANDROID +#elif defined(GTEST_OS_LINUX_ANDROID) return GetDirFromEnv({"TEST_SRCDIR"}, GetCurrentExecutableDirectory().c_str(), '/'); #else @@ -6825,6 +6896,7 @@ std::string SrcDir() { '/'); #endif } +#endif // Class ScopedTrace diff --git a/googletest/src/gtest_main.cc b/googletest/src/gtest_main.cc index 5abaa29f..c2e3b3cc 100644 --- a/googletest/src/gtest_main.cc +++ b/googletest/src/gtest_main.cc @@ -31,10 +31,10 @@ #include "gtest/gtest.h" -#if GTEST_OS_ESP8266 || GTEST_OS_ESP32 +#if defined(GTEST_OS_ESP8266) || defined(GTEST_OS_ESP32) // Arduino-like platforms: program entry points are setup/loop instead of main. -#if GTEST_OS_ESP8266 +#ifdef GTEST_OS_ESP8266 extern "C" { #endif @@ -42,11 +42,11 @@ void setup() { testing::InitGoogleTest(); } void loop() { RUN_ALL_TESTS(); } -#if GTEST_OS_ESP8266 +#ifdef GTEST_OS_ESP8266 } #endif -#elif GTEST_OS_QURT +#elif defined(GTEST_OS_QURT) // QuRT: program entry point is main, but argc/argv are unusable. GTEST_API_ int main() { |