diff --git a/Modules/ThirdParty/GoogleTest/UpdateFromUpstream.sh b/Modules/ThirdParty/GoogleTest/UpdateFromUpstream.sh index 7985fe95c2c..f926d29d02e 100755 --- a/Modules/ThirdParty/GoogleTest/UpdateFromUpstream.sh +++ b/Modules/ThirdParty/GoogleTest/UpdateFromUpstream.sh @@ -8,7 +8,7 @@ readonly name="GoogleTest" readonly ownership="GoogleTest Upstream " readonly subtree="Modules/ThirdParty/GoogleTest/src/itkgoogletest" readonly repo="https://github.com/google/googletest.git" -readonly tag="v1.13.0" +readonly tag="v1.15.2" readonly shortlog=false readonly paths=" CMakeLists.txt diff --git a/Modules/ThirdParty/GoogleTest/src/itkgoogletest/CMakeLists.txt b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/CMakeLists.txt index 6af414371f7..512e5c3d480 100644 --- a/Modules/ThirdParty/GoogleTest/src/itkgoogletest/CMakeLists.txt +++ b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/CMakeLists.txt @@ -1,22 +1,10 @@ # Note: CMake support is community-based. The maintainers do not use CMake # internally. -cmake_minimum_required(VERSION 3.5) - -if (POLICY CMP0048) - cmake_policy(SET CMP0048 NEW) -endif (POLICY CMP0048) - -if (POLICY CMP0069) - cmake_policy(SET CMP0069 NEW) -endif (POLICY CMP0069) - -if (POLICY CMP0077) - cmake_policy(SET CMP0077 NEW) -endif (POLICY CMP0077) +cmake_minimum_required(VERSION 3.13) project(googletest-distribution) -set(GOOGLETEST_VERSION 1.13.0) +set(GOOGLETEST_VERSION 1.15.2) if(NOT CYGWIN AND NOT MSYS AND NOT ${CMAKE_SYSTEM_NAME} STREQUAL QNX) set(CMAKE_CXX_EXTENSIONS OFF) @@ -27,11 +15,20 @@ enable_testing() include(CMakeDependentOption) include(GNUInstallDirs) -#Note that googlemock target already builds googletest +# Note that googlemock target already builds googletest. option(BUILD_GMOCK "Builds the googlemock subproject" ON) option(INSTALL_GTEST "Enable installation of googletest. (Projects embedding googletest may want to turn this OFF.)" ON) option(GTEST_HAS_ABSL "Use Abseil and RE2. Requires Abseil and RE2 to be separately added to the build." OFF) +if(GTEST_HAS_ABSL) + if(NOT TARGET absl::base) + find_package(absl REQUIRED) + endif() + if(NOT TARGET re2::re2) + find_package(re2 REQUIRED) + endif() +endif() + if(BUILD_GMOCK) add_subdirectory( googlemock ) else() diff --git a/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/CMakeLists.txt b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/CMakeLists.txt index 3e044587cfe..b52ed77fc03 100644 --- a/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/CMakeLists.txt +++ b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/CMakeLists.txt @@ -5,7 +5,7 @@ # CMake build script for Google Test. # # To run the tests for Google Test itself on Linux, use 'make test' or -# ctest. You can select which tests to run using 'ctest -R regex'. +# ctest. You can select which tests to run using 'ctest -R regex'. # For more options, run 'ctest --help'. # When other libraries are using a shared version of runtime libraries, @@ -36,7 +36,7 @@ endif() ######################################################################## # -# Project-wide settings +# Project-wide settings. # Name of the project. # @@ -45,21 +45,16 @@ endif() # ${gtest_BINARY_DIR}. # Language "C" is required for find_package(Threads). -# Project version: +# Project version. -cmake_minimum_required(VERSION 3.5) -cmake_policy(SET CMP0048 NEW) +cmake_minimum_required(VERSION 3.13) project(gtest VERSION ${GOOGLETEST_VERSION} LANGUAGES CXX C) -if (POLICY CMP0063) # Visibility - cmake_policy(SET CMP0063 NEW) -endif (POLICY CMP0063) - if (COMMAND set_up_hermetic_build) set_up_hermetic_build() endif() -# These commands only run if this is the main project +# These commands only run if this is the main project. if(CMAKE_PROJECT_NAME STREQUAL "gtest" OR CMAKE_PROJECT_NAME STREQUAL "googletest-distribution") # BUILD_SHARED_LIBS is a standard CMake variable, but we declare it here to @@ -89,7 +84,7 @@ include(cmake/internal_utils.cmake) config_compiler_and_linker() # Defined in internal_utils.cmake. # Needed to set the namespace for both the export targets and the -# alias libraries +# alias libraries. set(cmake_package_name GTest CACHE INTERNAL "") # Create the CMake package file descriptors. @@ -101,12 +96,14 @@ if (INSTALL_GTEST) set(version_file "${generated_dir}/${cmake_package_name}ConfigVersion.cmake") write_basic_package_version_file(${version_file} VERSION ${GOOGLETEST_VERSION} COMPATIBILITY AnyNewerVersion) install(EXPORT ${targets_export_name} + COMPONENT "${PROJECT_NAME}" NAMESPACE ${cmake_package_name}:: DESTINATION ${cmake_files_install_dir}) set(config_file "${generated_dir}/${cmake_package_name}Config.cmake") configure_package_config_file("${gtest_SOURCE_DIR}/cmake/Config.cmake.in" "${config_file}" INSTALL_DESTINATION ${cmake_files_install_dir}) install(FILES ${version_file} ${config_file} + COMPONENT "${PROJECT_NAME}" DESTINATION ${cmake_files_install_dir}) endif() @@ -118,10 +115,10 @@ include_directories(${gtest_build_include_dirs}) ######################################################################## # -# Defines the gtest & gtest_main libraries. User tests should link +# Defines the gtest & gtest_main libraries. User tests should link # with one of them. -# Google Test libraries. We build them using more strict warnings than what +# Google Test libraries. We build them using more strict warnings than what # are used for other targets, to ensure that gtest can be compiled by a user # aggressive about warnings. cxx_library(gtest "${cxx_strict}" src/gtest-all.cc) @@ -144,34 +141,29 @@ if(GTEST_HAS_ABSL) endif() cxx_library(gtest_main "${cxx_strict}" src/gtest_main.cc) set_target_properties(gtest_main PROPERTIES VERSION ${GOOGLETEST_VERSION}) -# If the CMake version supports it, attach header directory information -# to the targets for when we are part of a parent build (ie being pulled -# in via add_subdirectory() rather than being a standalone build). -if (DEFINED CMAKE_VERSION AND NOT "${CMAKE_VERSION}" VERSION_LESS "2.8.11") - string(REPLACE ";" "$" dirs "${gtest_build_include_dirs}") - target_include_directories(gtest SYSTEM INTERFACE - "$" - "$/${CMAKE_INSTALL_INCLUDEDIR}>") - target_include_directories(gtest_main SYSTEM INTERFACE - "$" - "$/${CMAKE_INSTALL_INCLUDEDIR}>") -endif() -if(CMAKE_SYSTEM_NAME MATCHES "QNX") +string(REPLACE ";" "$" dirs "${gtest_build_include_dirs}") +target_include_directories(gtest SYSTEM INTERFACE + "$" + "$/${CMAKE_INSTALL_INCLUDEDIR}>") +target_include_directories(gtest_main SYSTEM INTERFACE + "$" + "$/${CMAKE_INSTALL_INCLUDEDIR}>") +if(CMAKE_SYSTEM_NAME MATCHES "QNX" AND CMAKE_SYSTEM_VERSION VERSION_GREATER_EQUAL 7.1) target_link_libraries(gtest PUBLIC regex) endif() target_link_libraries(gtest_main PUBLIC gtest) ######################################################################## # -# Install rules +# Install rules. install_project(gtest gtest_main) ######################################################################## # # Samples on how to link user tests with gtest or gtest_main. # -# They are not built by default. To build them, set the -# gtest_build_samples option to ON. You can do it by running ccmake +# They are not built by default. To build them, set the +# gtest_build_samples option to ON. You can do it by running ccmake # or specifying the -Dgtest_build_samples=ON flag when running cmake. if (gtest_build_samples) @@ -194,8 +186,8 @@ endif() # You can skip this section if you aren't interested in testing # Google Test itself. # -# The tests are not built by default. To build them, set the -# gtest_build_tests option to ON. You can do it by running ccmake +# The tests are not built by default. To build them, set the +# gtest_build_tests option to ON. You can do it by running ccmake # or specifying the -Dgtest_build_tests=ON flag when running cmake. if (gtest_build_tests) @@ -277,7 +269,7 @@ if (gtest_build_tests) py_test(gtest_skip_environment_check_output_test) # Visual Studio .NET 2003 does not support STL with exceptions disabled. - if (NOT MSVC OR MSVC_VERSION GREATER 1310) # 1310 is Visual Studio .NET 2003 + if (NOT MSVC OR MSVC_VERSION GREATER 1310) # 1310 is Visual Studio .NET 2003 cxx_executable_with_flags( googletest-catch-exceptions-no-ex-test_ "${cxx_no_exception}" diff --git a/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/cmake/Config.cmake.in b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/cmake/Config.cmake.in index 12be4498b1a..3f706612b24 100644 --- a/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/cmake/Config.cmake.in +++ b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/cmake/Config.cmake.in @@ -4,6 +4,10 @@ if (@GTEST_HAS_PTHREAD@) set(THREADS_PREFER_PTHREAD_FLAG @THREADS_PREFER_PTHREAD_FLAG@) find_dependency(Threads) endif() +if (@GTEST_HAS_ABSL@) + find_dependency(absl) + find_dependency(re2) +endif() include("${CMAKE_CURRENT_LIST_DIR}/@targets_export_name@.cmake") check_required_components("@project_name@") diff --git a/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/cmake/internal_utils.cmake b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/cmake/internal_utils.cmake index 80ea44b3cff..d9c046c5498 100644 --- a/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/cmake/internal_utils.cmake +++ b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/cmake/internal_utils.cmake @@ -12,10 +12,6 @@ # Test and Google Mock's option() definitions, and thus must be # called *after* the options have been defined. -if (POLICY CMP0054) - cmake_policy(SET CMP0054 NEW) -endif (POLICY CMP0054) - # Tweaks CMake's default compiler/linker settings to suit Google Test's needs. # # This must be a macro(), as inside a function string() can only @@ -33,7 +29,7 @@ macro(fix_default_compiler_settings_) CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELWITHDEBINFO) if (NOT BUILD_SHARED_LIBS AND NOT gtest_force_shared_crt) # When Google Test is built as a shared library, it should also use - # shared runtime libraries. Otherwise, it may end up with multiple + # shared runtime libraries. Otherwise, it may end up with multiple # copies of runtime library data in different modules, resulting in # hard-to-find crashes. When it is built as a static library, it is # preferable to use CRT as static libraries, as we don't have to rely @@ -59,11 +55,11 @@ macro(fix_default_compiler_settings_) endmacro() # Defines the compiler/linker flags used to build Google Test and -# Google Mock. You can tweak these definitions to suit your need. A +# Google Mock. You can tweak these definitions to suit your need. A # variable's value is empty before it's explicitly assigned to. macro(config_compiler_and_linker) # Note: pthreads on MinGW is not supported, even if available - # instead, we use windows threading primitives + # instead, we use windows threading primitives. unset(GTEST_HAS_PTHREAD) if (NOT gtest_disable_pthreads AND NOT MINGW) # Defines CMAKE_USE_PTHREADS_INIT and CMAKE_THREAD_LIBS_INIT. @@ -83,28 +79,38 @@ macro(config_compiler_and_linker) set(cxx_exception_flags "-EHsc -D_HAS_EXCEPTIONS=1") set(cxx_no_exception_flags "-EHs-c- -D_HAS_EXCEPTIONS=0") set(cxx_no_rtti_flags "-GR-") - # Suppress "unreachable code" warning - # http://stackoverflow.com/questions/3232669 explains the issue. + # Suppress "unreachable code" warning, + # https://stackoverflow.com/questions/3232669 explains the issue. set(cxx_base_flags "${cxx_base_flags} -wd4702") # Ensure MSVC treats source files as UTF-8 encoded. if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") set(cxx_base_flags "${cxx_base_flags} -utf-8") endif() - elseif (CMAKE_CXX_COMPILER_ID STREQUAL "Clang") - set(cxx_base_flags "-Wall -Wshadow -Wconversion") + if (CMAKE_CXX_COMPILER_ID STREQUAL "IntelLLVM") + set(cxx_base_flags "${cxx_base_flags} /fp:precise -Wno-inconsistent-missing-override -Wno-microsoft-exception-spec -Wno-unused-function -Wno-unused-but-set-variable") + endif() + elseif (CMAKE_CXX_COMPILER_ID STREQUAL "Clang" OR + CMAKE_CXX_COMPILER_ID STREQUAL "IntelLLVM") + set(cxx_base_flags "-Wall -Wshadow -Wconversion -Wundef") set(cxx_exception_flags "-fexceptions") set(cxx_no_exception_flags "-fno-exceptions") - set(cxx_strict_flags "-W -Wpointer-arith -Wreturn-type -Wcast-qual -Wwrite-strings -Wswitch -Wunused-parameter -Wcast-align -Wchar-subscripts -Winline -Wredundant-decls") + set(cxx_strict_flags "-W -Wpointer-arith -Wreturn-type -Wcast-qual -Wwrite-strings -Wswitch -Wunused-parameter -Wcast-align -Winline -Wredundant-decls") set(cxx_no_rtti_flags "-fno-rtti") + if (CMAKE_CXX_COMPILER_ID STREQUAL "Clang") + set(cxx_strict_flags "${cxx_strict_flags} -Wchar-subscripts") + endif() + if (CMAKE_CXX_COMPILER_ID STREQUAL "IntelLLVM") + set(cxx_base_flags "${cxx_base_flags} -Wno-implicit-float-size-conversion -ffp-model=precise") + endif() elseif (CMAKE_COMPILER_IS_GNUCXX) - set(cxx_base_flags "-Wall -Wshadow") + set(cxx_base_flags "-Wall -Wshadow -Wundef") if(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 7.0.0) set(cxx_base_flags "${cxx_base_flags} -Wno-error=dangling-else") endif() set(cxx_exception_flags "-fexceptions") set(cxx_no_exception_flags "-fno-exceptions") # Until version 4.3.2, GCC doesn't define a macro to indicate - # whether RTTI is enabled. Therefore we define GTEST_HAS_RTTI + # whether RTTI is enabled. Therefore we define GTEST_HAS_RTTI # explicitly. set(cxx_no_rtti_flags "-fno-rtti -DGTEST_HAS_RTTI=0") set(cxx_strict_flags @@ -121,7 +127,7 @@ macro(config_compiler_and_linker) set(cxx_exception_flags "-qeh") set(cxx_no_exception_flags "-qnoeh") # Until version 9.0, Visual Age doesn't define a macro to indicate - # whether RTTI is enabled. Therefore we define GTEST_HAS_RTTI + # whether RTTI is enabled. Therefore we define GTEST_HAS_RTTI # explicitly. set(cxx_no_rtti_flags "-qnortti -DGTEST_HAS_RTTI=0") elseif (CMAKE_CXX_COMPILER_ID STREQUAL "HP") @@ -151,7 +157,7 @@ macro(config_compiler_and_linker) set(cxx_strict "${cxx_default} ${cxx_strict_flags}") endmacro() -# Defines the gtest & gtest_main libraries. User tests should link +# Defines the gtest & gtest_main libraries. User tests should link # with one of them. function(cxx_library_with_type name type cxx_flags) # type can be either STATIC or SHARED to denote a static or shared library. @@ -161,7 +167,7 @@ function(cxx_library_with_type name type cxx_flags) set_target_properties(${name} PROPERTIES COMPILE_FLAGS "${cxx_flags}") - # Set the output directory for build artifacts + # Set the output directory for build artifacts. set_target_properties(${name} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/${ITK_INSTALL_RUNTIME_DIR}" @@ -169,7 +175,7 @@ function(cxx_library_with_type name type cxx_flags) ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/${ITK_INSTALL_ARCHIVE_DIR}" PDB_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin" COMPILE_PDB_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib") - # make PDBs match library name + # Make PDBs match library name. get_target_property(pdb_debug_postfix ${name} DEBUG_POSTFIX) set_target_properties(${name} PROPERTIES @@ -182,23 +188,14 @@ function(cxx_library_with_type name type cxx_flags) set_target_properties(${name} PROPERTIES COMPILE_DEFINITIONS "GTEST_CREATE_SHARED_LIBRARY=1") - if (NOT "${CMAKE_VERSION}" VERSION_LESS "2.8.11") - target_compile_definitions(${name} INTERFACE - $) - endif() + target_compile_definitions(${name} INTERFACE + $) endif() if (DEFINED GTEST_HAS_PTHREAD) - if ("${CMAKE_VERSION}" VERSION_LESS "3.1.0") - set(threads_spec ${CMAKE_THREAD_LIBS_INIT}) - else() - set(threads_spec Threads::Threads) - endif() - target_link_libraries(${name} PUBLIC ${threads_spec}) + target_link_libraries(${name} PUBLIC Threads::Threads) endif() - if (NOT "${CMAKE_VERSION}" VERSION_LESS "3.8") - target_compile_features(${name} PUBLIC cxx_std_14) - endif() + target_compile_features(${name} PUBLIC cxx_std_14) endfunction() ######################################################################## @@ -215,7 +212,7 @@ endfunction() # cxx_executable_with_flags(name cxx_flags libs srcs...) # -# creates a named C++ executable that depends on the given libraries and +# Creates a named C++ executable that depends on the given libraries and # is built from the given source files with the given compiler flags. function(cxx_executable_with_flags name cxx_flags libs) add_executable(${name} ${ARGN}) @@ -242,17 +239,18 @@ endfunction() # cxx_executable(name dir lib srcs...) # -# creates a named target that depends on the given libs and is built -# from the given source files. dir/name.cc is implicitly included in +# Creates a named target that depends on the given libs and is built +# from the given source files. dir/name.cc is implicitly included in # the source file list. function(cxx_executable name dir libs) cxx_executable_with_flags( ${name} "${cxx_default}" "${libs}" "${dir}/${name}.cc" ${ARGN}) endfunction() + # cxx_test_with_flags(name cxx_flags libs srcs...) # -# creates a named C++ test that depends on the given libs and is built +# Creates a named C++ test that depends on the given libs and is built # from the given source files with the given compiler flags. function(cxx_test_with_flags name cxx_flags libs) cxx_executable_with_flags(${name} "${cxx_flags}" "${libs}" ${ARGN}) @@ -261,8 +259,8 @@ endfunction() # cxx_test(name libs srcs...) # -# creates a named test target that depends on the given libs and is -# built from the given source files. Unlike cxx_test_with_flags, +# Creates a named test target that depends on the given libs and is +# built from the given source files. Unlike cxx_test_with_flags, # test/name.cc is already implicitly included in the source file list. function(cxx_test name libs) cxx_test_with_flags("${name}" "${cxx_default}" "${libs}" @@ -278,21 +276,24 @@ endfunction() function(install_project) if(INSTALL_GTEST) install(DIRECTORY "${PROJECT_SOURCE_DIR}/include/" + COMPONENT "${PROJECT_NAME}" DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}") # Install the project targets. install(TARGETS ${ARGN} EXPORT ${targets_export_name} + COMPONENT "${PROJECT_NAME}" RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}" ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}" LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}") if(CMAKE_CXX_COMPILER_ID MATCHES "MSVC") - # Install PDBs + # Install PDBs. foreach(t ${ARGN}) get_target_property(t_pdb_name ${t} COMPILE_PDB_NAME) get_target_property(t_pdb_name_debug ${t} COMPILE_PDB_NAME_DEBUG) get_target_property(t_pdb_output_directory ${t} PDB_OUTPUT_DIRECTORY) install(FILES "${t_pdb_output_directory}/\${CMAKE_INSTALL_CONFIG_NAME}/$<$:${t_pdb_name_debug}>$<$>:${t_pdb_name}>.pdb" + COMPONENT "${PROJECT_NAME}" DESTINATION ${CMAKE_INSTALL_LIBDIR} OPTIONAL) endforeach() @@ -303,6 +304,7 @@ function(install_project) configure_file("${PROJECT_SOURCE_DIR}/cmake/${t}.pc.in" "${configured_pc}" @ONLY) install(FILES "${configured_pc}" + COMPONENT "${PROJECT_NAME}" DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig") endforeach() endif() diff --git a/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/gtest-assertion-result.h b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/gtest-assertion-result.h index addbb59c641..74eb2b1f3c7 100644 --- a/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/gtest-assertion-result.h +++ b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/gtest-assertion-result.h @@ -129,7 +129,7 @@ namespace testing { // // Expected: Foo() is even // Actual: it's 5 -// + class GTEST_API_ AssertionResult { public: // Copy constructor. @@ -181,7 +181,7 @@ class GTEST_API_ AssertionResult { // assertion's expectation). When nothing has been streamed into the // object, returns an empty string. const char* message() const { - return message_.get() != nullptr ? message_->c_str() : ""; + return message_ != nullptr ? message_->c_str() : ""; } // Deprecated; please use message() instead. const char* failure_message() const { return message(); } @@ -204,7 +204,7 @@ class GTEST_API_ AssertionResult { private: // Appends the contents of message to message_. void AppendMessage(const Message& a_message) { - if (message_.get() == nullptr) message_.reset(new ::std::string); + if (message_ == nullptr) message_ = ::std::make_unique<::std::string>(); message_->append(a_message.GetString().c_str()); } diff --git a/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/gtest-death-test.h b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/gtest-death-test.h index 84e5a5bbd37..3c61909726f 100644 --- a/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/gtest-death-test.h +++ b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/gtest-death-test.h @@ -51,7 +51,7 @@ GTEST_DECLARE_string_(death_test_style); namespace testing { -#if GTEST_HAS_DEATH_TEST +#ifdef GTEST_HAS_DEATH_TEST namespace internal { @@ -203,7 +203,7 @@ class GTEST_API_ ExitedWithCode { const int exit_code_; }; -#if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA +#if !defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_FUCHSIA) // Tests that an exit code describes an exit due to termination by a // given signal. class GTEST_API_ KilledBySignal { @@ -293,8 +293,8 @@ class GTEST_API_ KilledBySignal { // statement is compiled but not executed, to ensure that // EXPECT_DEATH_IF_SUPPORTED compiles with a certain // parameter if and only if EXPECT_DEATH compiles with it. -// regex - A regex that a macro such as EXPECT_DEATH would use to test -// the output of statement. This parameter has to be +// regex_or_matcher - A regex that a macro such as EXPECT_DEATH would use +// to test the output of statement. This parameter has to be // compiled but not evaluated by this macro, to ensure that // this macro only accepts expressions that a macro such as // EXPECT_DEATH would accept. @@ -311,13 +311,13 @@ class GTEST_API_ KilledBySignal { // statement unconditionally returns or throws. The Message constructor at // the end allows the syntax of streaming additional messages into the // macro, for compilational compatibility with EXPECT_DEATH/ASSERT_DEATH. -#define GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, terminator) \ +#define GTEST_UNSUPPORTED_DEATH_TEST(statement, regex_or_matcher, terminator) \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ if (::testing::internal::AlwaysTrue()) { \ GTEST_LOG_(WARNING) << "Death tests are not supported on this platform.\n" \ << "Statement '" #statement "' cannot be verified."; \ } else if (::testing::internal::AlwaysFalse()) { \ - ::testing::internal::RE::PartialMatch(".*", (regex)); \ + ::testing::internal::MakeDeathTestMatcher(regex_or_matcher); \ GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ terminator; \ } else \ @@ -328,7 +328,7 @@ class GTEST_API_ KilledBySignal { // death tests are supported; otherwise they just issue a warning. This is // useful when you are combining death test assertions with normal test // assertions in one test. -#if GTEST_HAS_DEATH_TEST +#ifdef GTEST_HAS_DEATH_TEST #define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \ EXPECT_DEATH(statement, regex) #define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \ diff --git a/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/gtest-matchers.h b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/gtest-matchers.h index 4a60b0d0b8d..eae210e99dd 100644 --- a/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/gtest-matchers.h +++ b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/gtest-matchers.h @@ -40,6 +40,7 @@ #define GOOGLETEST_INCLUDE_GTEST_GTEST_MATCHERS_H_ #include +#include #include #include #include @@ -106,13 +107,13 @@ class MatchResultListener { MatchResultListener& operator=(const MatchResultListener&) = delete; }; -inline MatchResultListener::~MatchResultListener() {} +inline MatchResultListener::~MatchResultListener() = default; // An instance of a subclass of this knows how to describe itself as a // matcher. class GTEST_API_ MatcherDescriberInterface { public: - virtual ~MatcherDescriberInterface() {} + virtual ~MatcherDescriberInterface() = default; // Describes this matcher to an ostream. The function should print // a verb phrase that describes the property a value matching this @@ -178,43 +179,6 @@ class MatcherInterface : public MatcherDescriberInterface { namespace internal { -struct AnyEq { - template - bool operator()(const A& a, const B& b) const { - return a == b; - } -}; -struct AnyNe { - template - bool operator()(const A& a, const B& b) const { - return a != b; - } -}; -struct AnyLt { - template - bool operator()(const A& a, const B& b) const { - return a < b; - } -}; -struct AnyGt { - template - bool operator()(const A& a, const B& b) const { - return a > b; - } -}; -struct AnyLe { - template - bool operator()(const A& a, const B& b) const { - return a <= b; - } -}; -struct AnyGe { - template - bool operator()(const A& a, const B& b) const { - return a >= b; - } -}; - // A match result listener that ignores the explanation. class DummyMatchResultListener : public MatchResultListener { public: @@ -530,7 +494,7 @@ template <> class GTEST_API_ Matcher : public internal::MatcherBase { public: - Matcher() {} + Matcher() = default; explicit Matcher(const MatcherInterface* impl) : internal::MatcherBase(impl) {} @@ -552,7 +516,7 @@ template <> class GTEST_API_ Matcher : public internal::MatcherBase { public: - Matcher() {} + Matcher() = default; explicit Matcher(const MatcherInterface* impl) : internal::MatcherBase(impl) {} @@ -580,7 +544,7 @@ template <> class GTEST_API_ Matcher : public internal::MatcherBase { public: - Matcher() {} + Matcher() = default; explicit Matcher(const MatcherInterface* impl) : internal::MatcherBase(impl) {} @@ -606,7 +570,7 @@ template <> class GTEST_API_ Matcher : public internal::MatcherBase { public: - Matcher() {} + Matcher() = default; explicit Matcher(const MatcherInterface* impl) : internal::MatcherBase(impl) {} @@ -758,50 +722,53 @@ class ComparisonBase { }; template -class EqMatcher : public ComparisonBase, Rhs, AnyEq> { +class EqMatcher : public ComparisonBase, Rhs, std::equal_to<>> { public: explicit EqMatcher(const Rhs& rhs) - : ComparisonBase, Rhs, AnyEq>(rhs) {} + : ComparisonBase, Rhs, std::equal_to<>>(rhs) {} static const char* Desc() { return "is equal to"; } static const char* NegatedDesc() { return "isn't equal to"; } }; template -class NeMatcher : public ComparisonBase, Rhs, AnyNe> { +class NeMatcher + : public ComparisonBase, Rhs, std::not_equal_to<>> { public: explicit NeMatcher(const Rhs& rhs) - : ComparisonBase, Rhs, AnyNe>(rhs) {} + : ComparisonBase, Rhs, std::not_equal_to<>>(rhs) {} static const char* Desc() { return "isn't equal to"; } static const char* NegatedDesc() { return "is equal to"; } }; template -class LtMatcher : public ComparisonBase, Rhs, AnyLt> { +class LtMatcher : public ComparisonBase, Rhs, std::less<>> { public: explicit LtMatcher(const Rhs& rhs) - : ComparisonBase, Rhs, AnyLt>(rhs) {} + : ComparisonBase, Rhs, std::less<>>(rhs) {} static const char* Desc() { return "is <"; } static const char* NegatedDesc() { return "isn't <"; } }; template -class GtMatcher : public ComparisonBase, Rhs, AnyGt> { +class GtMatcher : public ComparisonBase, Rhs, std::greater<>> { public: explicit GtMatcher(const Rhs& rhs) - : ComparisonBase, Rhs, AnyGt>(rhs) {} + : ComparisonBase, Rhs, std::greater<>>(rhs) {} static const char* Desc() { return "is >"; } static const char* NegatedDesc() { return "isn't >"; } }; template -class LeMatcher : public ComparisonBase, Rhs, AnyLe> { +class LeMatcher + : public ComparisonBase, Rhs, std::less_equal<>> { public: explicit LeMatcher(const Rhs& rhs) - : ComparisonBase, Rhs, AnyLe>(rhs) {} + : ComparisonBase, Rhs, std::less_equal<>>(rhs) {} static const char* Desc() { return "is <="; } static const char* NegatedDesc() { return "isn't <="; } }; template -class GeMatcher : public ComparisonBase, Rhs, AnyGe> { +class GeMatcher + : public ComparisonBase, Rhs, std::greater_equal<>> { public: explicit GeMatcher(const Rhs& rhs) - : ComparisonBase, Rhs, AnyGe>(rhs) {} + : ComparisonBase, Rhs, std::greater_equal<>>(rhs) {} static const char* Desc() { return "is >="; } static const char* NegatedDesc() { return "isn't >="; } }; diff --git a/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/gtest-message.h b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/gtest-message.h index 4d4b152b1d8..448ac6b7ee2 100644 --- a/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/gtest-message.h +++ b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/gtest-message.h @@ -56,6 +56,13 @@ #include "gtest/internal/gtest-port.h" +#ifdef GTEST_HAS_ABSL +#include + +#include "absl/strings/has_absl_stringify.h" +#include "absl/strings/str_cat.h" +#endif // GTEST_HAS_ABSL + GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \ /* class A needs to have dll-interface to be used by clients of class B */) @@ -111,8 +118,17 @@ class GTEST_API_ Message { *ss_ << str; } - // Streams a non-pointer value to this object. - template + // Streams a non-pointer value to this object. If building a version of + // GoogleTest with ABSL, this overload is only enabled if the value does not + // have an AbslStringify definition. + template < + typename T +#ifdef GTEST_HAS_ABSL + , + typename std::enable_if::value, // NOLINT + int>::type = 0 +#endif // GTEST_HAS_ABSL + > inline Message& operator<<(const T& val) { // Some libraries overload << for STL containers. These // overloads are defined in the global namespace instead of ::std. @@ -133,6 +149,21 @@ class GTEST_API_ Message { return *this; } +#ifdef GTEST_HAS_ABSL + // Streams a non-pointer value with an AbslStringify definition to this + // object. + template ::value, // NOLINT + int>::type = 0> + inline Message& operator<<(const T& val) { + // ::operator<< is needed here for a similar reason as with the non-Abseil + // version above + using ::operator<<; + *ss_ << absl::StrCat(val); + return *this; + } +#endif // GTEST_HAS_ABSL + // Streams a pointer value to this object. // // This function is an overload of the previous one. When you diff --git a/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/gtest-param-test.h b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/gtest-param-test.h index 1adb9a72520..55ee088b93f 100644 --- a/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/gtest-param-test.h +++ b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/gtest-param-test.h @@ -178,7 +178,7 @@ TEST_P(DerivedTest, DoesBlah) { #include #include "gtest/internal/gtest-internal.h" -#include "gtest/internal/gtest-param-util.h" +#include "gtest/internal/gtest-param-util.h" // IWYU pragma: export #include "gtest/internal/gtest-port.h" namespace testing { @@ -449,7 +449,8 @@ internal::ParamConverterGenerator ConvertGenerator( #define TEST_P(test_suite_name, test_name) \ class GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \ - : public test_suite_name, private ::testing::internal::GTestNonCopyable {\ + : public test_suite_name, \ + private ::testing::internal::GTestNonCopyable { \ public: \ GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() {} \ void TestBody() override; \ @@ -468,7 +469,7 @@ internal::ParamConverterGenerator ConvertGenerator( ::testing::internal::CodeLocation(__FILE__, __LINE__)); \ return 0; \ } \ - static int gtest_registering_dummy_ GTEST_ATTRIBUTE_UNUSED_; \ + GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED static int gtest_registering_dummy_; \ }; \ int GTEST_TEST_CLASS_NAME_(test_suite_name, \ test_name)::gtest_registering_dummy_ = \ @@ -513,8 +514,8 @@ internal::ParamConverterGenerator ConvertGenerator( ::testing::internal::DefaultParamName, \ DUMMY_PARAM_))))(info); \ } \ - static int gtest_##prefix##test_suite_name##_dummy_ \ - GTEST_ATTRIBUTE_UNUSED_ = \ + GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED static int \ + gtest_##prefix##test_suite_name##_dummy_ = \ ::testing::UnitTest::GetInstance() \ ->parameterized_test_registry() \ .GetTestSuitePatternHolder( \ diff --git a/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/gtest-printers.h b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/gtest-printers.h index 0055e37ffa7..b2822bcde23 100644 --- a/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/gtest-printers.h +++ b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/gtest-printers.h @@ -43,6 +43,9 @@ // 1. foo::PrintTo(const T&, ostream*) // 2. operator<<(ostream&, const T&) defined in either foo or the // global namespace. +// * Prefer AbslStringify(..) to operator<<(..), per https://abseil.io/tips/215. +// * Define foo::PrintTo(..) if the type already has AbslStringify(..), but an +// alternative presentation in test results is of interest. // // However if T is an STL-style container then it is printed element-wise // unless foo::PrintTo(const T&, ostream*) is defined. Note that @@ -112,9 +115,17 @@ #include #include +#ifdef GTEST_HAS_ABSL +#include "absl/strings/has_absl_stringify.h" +#include "absl/strings/str_cat.h" +#endif // GTEST_HAS_ABSL #include "gtest/internal/gtest-internal.h" #include "gtest/internal/gtest-port.h" +#if GTEST_INTERNAL_HAS_STD_SPAN +#include // NOLINT +#endif // GTEST_INTERNAL_HAS_STD_SPAN + namespace testing { // Definitions in the internal* namespaces are subject to change without notice. @@ -124,13 +135,32 @@ namespace internal { template void UniversalPrint(const T& value, ::std::ostream* os); +template +struct IsStdSpan { + static constexpr bool value = false; +}; + +#if GTEST_INTERNAL_HAS_STD_SPAN +template +struct IsStdSpan> { + static constexpr bool value = true; +}; +#endif // GTEST_INTERNAL_HAS_STD_SPAN + // Used to print an STL-style container when the user doesn't define // a PrintTo() for it. +// +// NOTE: Since std::span does not have const_iterator until C++23, it would +// fail IsContainerTest before C++23. However, IsContainerTest only uses +// the presence of const_iterator to avoid treating iterators as containers +// because of iterator::iterator. Which means std::span satisfies the *intended* +// condition of IsContainerTest. struct ContainerPrinter { template (0)) == sizeof(IsContainer)) && - !IsRecursiveContainer::value>::type> + ((sizeof(IsContainerTest(0)) == sizeof(IsContainer)) && + !IsRecursiveContainer::value) || + IsStdSpan::value>::type> static void PrintValue(const T& container, std::ostream* os) { const size_t kMaxCount = 32; // The maximum number of elements to print. *os << '{'; @@ -206,12 +236,13 @@ struct StreamPrinter { // Don't accept member pointers here. We'd print them via implicit // conversion to bool, which isn't useful. typename = typename std::enable_if< - !std::is_member_pointer::value>::type, - // Only accept types for which we can find a streaming operator via - // ADL (possibly involving implicit conversions). - typename = decltype(std::declval() - << std::declval())> - static void PrintValue(const T& value, ::std::ostream* os) { + !std::is_member_pointer::value>::type> + // Only accept types for which we can find a streaming operator via + // ADL (possibly involving implicit conversions). + // (Use SFINAE via return type, because it seems GCC < 12 doesn't handle name + // lookup properly when we do it in the template parameter list.) + static auto PrintValue(const T& value, + ::std::ostream* os) -> decltype((void)(*os << value)) { // Call streaming operator found by ADL, possibly with implicit conversions // of the arguments. *os << value; @@ -259,6 +290,17 @@ struct ConvertibleToStringViewPrinter { #endif }; +#ifdef GTEST_HAS_ABSL +struct ConvertibleToAbslStringifyPrinter { + template ::value>::type> // NOLINT + static void PrintValue(const T& value, ::std::ostream* os) { + *os << absl::StrCat(value); + } +}; +#endif // GTEST_HAS_ABSL + // Prints the given number of bytes in the given object to the given // ostream. GTEST_API_ void PrintBytesInObjectTo(const unsigned char* obj_bytes, @@ -297,8 +339,8 @@ struct FindFirstPrinter< // - Print containers (they have begin/end/etc). // - Print function pointers. // - Print object pointers. -// - Use the stream operator, if available. // - Print protocol buffers. +// - Use the stream operator, if available. // - Print types convertible to BiggestInt. // - Print types convertible to StringView, if available. // - Fallback to printing the raw bytes of the object. @@ -306,9 +348,13 @@ template void PrintWithFallback(const T& value, ::std::ostream* os) { using Printer = typename FindFirstPrinter< T, void, ContainerPrinter, FunctionPointerPrinter, PointerPrinter, + ProtobufPrinter, +#ifdef GTEST_HAS_ABSL + ConvertibleToAbslStringifyPrinter, +#endif // GTEST_HAS_ABSL internal_stream_operator_without_lexical_name_lookup::StreamPrinter, - ProtobufPrinter, ConvertibleToIntegerPrinter, - ConvertibleToStringViewPrinter, RawBytesPrinter, FallbackPrinter>::type; + ConvertibleToIntegerPrinter, ConvertibleToStringViewPrinter, + RawBytesPrinter, FallbackPrinter>::type; Printer::PrintValue(value, os); } @@ -473,7 +519,7 @@ GTEST_API_ void PrintTo(char32_t c, ::std::ostream* os); inline void PrintTo(char16_t c, ::std::ostream* os) { PrintTo(ImplicitCast_(c), os); } -#ifdef __cpp_char8_t +#ifdef __cpp_lib_char8_t inline void PrintTo(char8_t c, ::std::ostream* os) { PrintTo(ImplicitCast_(c), os); } @@ -506,43 +552,63 @@ int AppropriateResolution(FloatType val) { int full = std::numeric_limits::max_digits10; if (val < 0) val = -val; +#ifdef __GNUC__ +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wfloat-equal" +#endif if (val < 1000000) { FloatType mulfor6 = 1e10; - if (val >= 100000.0) { // 100,000 to 999,999 + // Without these static casts, the template instantiation for float would + // fail to compile when -Wdouble-promotion is enabled, as the arithmetic and + // comparison logic would promote floats to doubles. + if (val >= static_cast(100000.0)) { // 100,000 to 999,999 mulfor6 = 1.0; - } else if (val >= 10000.0) { + } else if (val >= static_cast(10000.0)) { mulfor6 = 1e1; - } else if (val >= 1000.0) { + } else if (val >= static_cast(1000.0)) { mulfor6 = 1e2; - } else if (val >= 100.0) { + } else if (val >= static_cast(100.0)) { mulfor6 = 1e3; - } else if (val >= 10.0) { + } else if (val >= static_cast(10.0)) { mulfor6 = 1e4; - } else if (val >= 1.0) { + } else if (val >= static_cast(1.0)) { mulfor6 = 1e5; - } else if (val >= 0.1) { + } else if (val >= static_cast(0.1)) { mulfor6 = 1e6; - } else if (val >= 0.01) { + } else if (val >= static_cast(0.01)) { mulfor6 = 1e7; - } else if (val >= 0.001) { + } else if (val >= static_cast(0.001)) { mulfor6 = 1e8; - } else if (val >= 0.0001) { + } else if (val >= static_cast(0.0001)) { mulfor6 = 1e9; } - if (static_cast(val * mulfor6 + 0.5) / mulfor6 == val) return 6; - } else if (val < 1e10) { - FloatType divfor6 = 1.0; - if (val >= 1e9) { // 1,000,000,000 to 9,999,999,999 + if (static_cast(static_cast( + val * mulfor6 + (static_cast(0.5)))) / + mulfor6 == + val) + return 6; + } else if (val < static_cast(1e10)) { + FloatType divfor6 = static_cast(1.0); + if (val >= static_cast(1e9)) { // 1,000,000,000 to 9,999,999,999 divfor6 = 10000; - } else if (val >= 1e8) { // 100,000,000 to 999,999,999 + } else if (val >= + static_cast(1e8)) { // 100,000,000 to 999,999,999 divfor6 = 1000; - } else if (val >= 1e7) { // 10,000,000 to 99,999,999 + } else if (val >= + static_cast(1e7)) { // 10,000,000 to 99,999,999 divfor6 = 100; - } else if (val >= 1e6) { // 1,000,000 to 9,999,999 + } else if (val >= static_cast(1e6)) { // 1,000,000 to 9,999,999 divfor6 = 10; } - if (static_cast(val / divfor6 + 0.5) * divfor6 == val) return 6; + if (static_cast(static_cast( + val / divfor6 + (static_cast(0.5)))) * + divfor6 == + val) + return 6; } +#ifdef __GNUC__ +#pragma GCC diagnostic pop +#endif return full; } @@ -580,7 +646,7 @@ inline void PrintTo(const unsigned char* s, ::std::ostream* os) { inline void PrintTo(unsigned char* s, ::std::ostream* os) { PrintTo(ImplicitCast_(s), os); } -#ifdef __cpp_char8_t +#ifdef __cpp_lib_char8_t // Overloads for u8 strings. GTEST_API_ void PrintTo(const char8_t* s, ::std::ostream* os); inline void PrintTo(char8_t* s, ::std::ostream* os) { @@ -850,7 +916,7 @@ class UniversalPrinter> { public: static void Print(const Variant& value, ::std::ostream* os) { *os << '('; -#if GTEST_HAS_ABSL +#ifdef GTEST_HAS_ABSL absl::visit(Visitor{os, value.index()}, value); #else std::visit(Visitor{os, value.index()}, value); @@ -900,7 +966,7 @@ void UniversalPrintArray(const T* begin, size_t len, ::std::ostream* os) { GTEST_API_ void UniversalPrintArray(const char* begin, size_t len, ::std::ostream* os); -#ifdef __cpp_char8_t +#ifdef __cpp_lib_char8_t // This overload prints a (const) char8_t array compactly. GTEST_API_ void UniversalPrintArray(const char8_t* begin, size_t len, ::std::ostream* os); @@ -996,7 +1062,7 @@ template <> class UniversalTersePrinter : public UniversalTersePrinter { }; -#ifdef __cpp_char8_t +#ifdef __cpp_lib_char8_t template <> class UniversalTersePrinter { public: diff --git a/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/gtest-test-part.h b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/gtest-test-part.h index 8290b4d653d..41c8a9a0d0e 100644 --- a/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/gtest-test-part.h +++ b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/gtest-test-part.h @@ -133,7 +133,7 @@ std::ostream& operator<<(std::ostream& os, const TestPartResult& result); // virtual. class GTEST_API_ TestPartResultArray { public: - TestPartResultArray() {} + TestPartResultArray() = default; // Appends the given TestPartResult to the array. void Append(const TestPartResult& result); @@ -154,7 +154,7 @@ class GTEST_API_ TestPartResultArray { // This interface knows how to report a test part result. class GTEST_API_ TestPartResultReporterInterface { public: - virtual ~TestPartResultReporterInterface() {} + virtual ~TestPartResultReporterInterface() = default; virtual void ReportTestPartResult(const TestPartResult& result) = 0; }; diff --git a/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/gtest-typed-test.h b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/gtest-typed-test.h index bd35a326601..305b0b50dd4 100644 --- a/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/gtest-typed-test.h +++ b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/gtest-typed-test.h @@ -194,33 +194,34 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes); typedef ::testing::internal::NameGeneratorSelector<__VA_ARGS__>::type \ GTEST_NAME_GENERATOR_(CaseName) -#define TYPED_TEST(CaseName, TestName) \ - static_assert(sizeof(GTEST_STRINGIFY_(TestName)) > 1, \ - "test-name must not be empty"); \ - template \ - class GTEST_TEST_CLASS_NAME_(CaseName, TestName) \ - : public CaseName { \ - private: \ - typedef CaseName TestFixture; \ - typedef gtest_TypeParam_ TypeParam; \ - void TestBody() override; \ - }; \ - static bool gtest_##CaseName##_##TestName##_registered_ \ - GTEST_ATTRIBUTE_UNUSED_ = ::testing::internal::TypeParameterizedTest< \ - CaseName, \ - ::testing::internal::TemplateSel, \ - GTEST_TYPE_PARAMS_( \ - CaseName)>::Register("", \ - ::testing::internal::CodeLocation( \ - __FILE__, __LINE__), \ - GTEST_STRINGIFY_(CaseName), \ - GTEST_STRINGIFY_(TestName), 0, \ - ::testing::internal::GenerateNames< \ - GTEST_NAME_GENERATOR_(CaseName), \ - GTEST_TYPE_PARAMS_(CaseName)>()); \ - template \ - void GTEST_TEST_CLASS_NAME_(CaseName, \ +#define TYPED_TEST(CaseName, TestName) \ + static_assert(sizeof(GTEST_STRINGIFY_(TestName)) > 1, \ + "test-name must not be empty"); \ + template \ + class GTEST_TEST_CLASS_NAME_(CaseName, TestName) \ + : public CaseName { \ + private: \ + typedef CaseName TestFixture; \ + typedef gtest_TypeParam_ TypeParam; \ + void TestBody() override; \ + }; \ + GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED static bool \ + gtest_##CaseName##_##TestName##_registered_ = \ + ::testing::internal::TypeParameterizedTest< \ + CaseName, \ + ::testing::internal::TemplateSel, \ + GTEST_TYPE_PARAMS_( \ + CaseName)>::Register("", \ + ::testing::internal::CodeLocation( \ + __FILE__, __LINE__), \ + GTEST_STRINGIFY_(CaseName), \ + GTEST_STRINGIFY_(TestName), 0, \ + ::testing::internal::GenerateNames< \ + GTEST_NAME_GENERATOR_(CaseName), \ + GTEST_TYPE_PARAMS_(CaseName)>()); \ + template \ + void GTEST_TEST_CLASS_NAME_(CaseName, \ TestName)::TestBody() // Legacy API is deprecated but still available @@ -267,31 +268,32 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes); TYPED_TEST_SUITE_P #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ -#define TYPED_TEST_P(SuiteName, TestName) \ - namespace GTEST_SUITE_NAMESPACE_(SuiteName) { \ - template \ - class TestName : public SuiteName { \ - private: \ - typedef SuiteName TestFixture; \ - typedef gtest_TypeParam_ TypeParam; \ - void TestBody() override; \ - }; \ - static bool gtest_##TestName##_defined_ GTEST_ATTRIBUTE_UNUSED_ = \ - GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).AddTestName( \ - __FILE__, __LINE__, GTEST_STRINGIFY_(SuiteName), \ - GTEST_STRINGIFY_(TestName)); \ - } \ - template \ - void GTEST_SUITE_NAMESPACE_( \ +#define TYPED_TEST_P(SuiteName, TestName) \ + namespace GTEST_SUITE_NAMESPACE_(SuiteName) { \ + template \ + class TestName : public SuiteName { \ + private: \ + typedef SuiteName TestFixture; \ + typedef gtest_TypeParam_ TypeParam; \ + void TestBody() override; \ + }; \ + GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED static bool \ + gtest_##TestName##_defined_ = \ + GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).AddTestName( \ + __FILE__, __LINE__, GTEST_STRINGIFY_(SuiteName), \ + GTEST_STRINGIFY_(TestName)); \ + } \ + template \ + void GTEST_SUITE_NAMESPACE_( \ SuiteName)::TestName::TestBody() // Note: this won't work correctly if the trailing arguments are macros. #define REGISTER_TYPED_TEST_SUITE_P(SuiteName, ...) \ namespace GTEST_SUITE_NAMESPACE_(SuiteName) { \ - typedef ::testing::internal::Templates<__VA_ARGS__> gtest_AllTests_; \ + typedef ::testing::internal::Templates<__VA_ARGS__> gtest_AllTests_; \ } \ - static const char* const GTEST_REGISTERED_TEST_NAMES_( \ - SuiteName) GTEST_ATTRIBUTE_UNUSED_ = \ + GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED static const char* const \ + GTEST_REGISTERED_TEST_NAMES_(SuiteName) = \ GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).VerifyRegisteredTestNames( \ GTEST_STRINGIFY_(SuiteName), __FILE__, __LINE__, #__VA_ARGS__) @@ -303,22 +305,24 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes); REGISTER_TYPED_TEST_SUITE_P #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ -#define INSTANTIATE_TYPED_TEST_SUITE_P(Prefix, SuiteName, Types, ...) \ - static_assert(sizeof(GTEST_STRINGIFY_(Prefix)) > 1, \ - "test-suit-prefix must not be empty"); \ - static bool gtest_##Prefix##_##SuiteName GTEST_ATTRIBUTE_UNUSED_ = \ - ::testing::internal::TypeParameterizedTestSuite< \ - SuiteName, GTEST_SUITE_NAMESPACE_(SuiteName)::gtest_AllTests_, \ - ::testing::internal::GenerateTypeList::type>:: \ - Register(GTEST_STRINGIFY_(Prefix), \ - ::testing::internal::CodeLocation(__FILE__, __LINE__), \ - >EST_TYPED_TEST_SUITE_P_STATE_(SuiteName), \ - GTEST_STRINGIFY_(SuiteName), \ - GTEST_REGISTERED_TEST_NAMES_(SuiteName), \ - ::testing::internal::GenerateNames< \ - ::testing::internal::NameGeneratorSelector< \ - __VA_ARGS__>::type, \ - ::testing::internal::GenerateTypeList::type>()) +#define INSTANTIATE_TYPED_TEST_SUITE_P(Prefix, SuiteName, Types, ...) \ + static_assert(sizeof(GTEST_STRINGIFY_(Prefix)) > 1, \ + "test-suit-prefix must not be empty"); \ + GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED static bool \ + gtest_##Prefix##_##SuiteName = \ + ::testing::internal::TypeParameterizedTestSuite< \ + SuiteName, GTEST_SUITE_NAMESPACE_(SuiteName)::gtest_AllTests_, \ + ::testing::internal::GenerateTypeList::type>:: \ + Register( \ + GTEST_STRINGIFY_(Prefix), \ + ::testing::internal::CodeLocation(__FILE__, __LINE__), \ + >EST_TYPED_TEST_SUITE_P_STATE_(SuiteName), \ + GTEST_STRINGIFY_(SuiteName), \ + GTEST_REGISTERED_TEST_NAMES_(SuiteName), \ + ::testing::internal::GenerateNames< \ + ::testing::internal::NameGeneratorSelector< \ + __VA_ARGS__>::type, \ + ::testing::internal::GenerateTypeList::type>()) // Legacy API is deprecated but still available #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ diff --git a/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/gtest.h b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/gtest.h index 3e452a503f8..c8996695203 100644 --- a/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/gtest.h +++ b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/gtest.h @@ -51,7 +51,6 @@ #include #include -#include #include #include #include @@ -61,16 +60,16 @@ #include #include -#include "gtest/gtest-assertion-result.h" -#include "gtest/gtest-death-test.h" -#include "gtest/gtest-matchers.h" -#include "gtest/gtest-message.h" -#include "gtest/gtest-param-test.h" -#include "gtest/gtest-printers.h" -#include "gtest/gtest-test-part.h" -#include "gtest/gtest-typed-test.h" -#include "gtest/gtest_pred_impl.h" -#include "gtest/gtest_prod.h" +#include "gtest/gtest-assertion-result.h" // IWYU pragma: export +#include "gtest/gtest-death-test.h" // IWYU pragma: export +#include "gtest/gtest-matchers.h" // IWYU pragma: export +#include "gtest/gtest-message.h" // IWYU pragma: export +#include "gtest/gtest-param-test.h" // IWYU pragma: export +#include "gtest/gtest-printers.h" // IWYU pragma: export +#include "gtest/gtest-test-part.h" // IWYU pragma: export +#include "gtest/gtest-typed-test.h" // IWYU pragma: export +#include "gtest/gtest_pred_impl.h" // IWYU pragma: export +#include "gtest/gtest_prod.h" // IWYU pragma: export #include "gtest/internal/gtest-internal.h" #include "gtest/internal/gtest-string.h" @@ -166,11 +165,7 @@ namespace testing { // Silence C4100 (unreferenced formal parameter) and 4805 // unsafe mix of type 'const int' and type 'const bool' -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable : 4805) -#pragma warning(disable : 4100) -#endif +GTEST_DISABLE_MSC_WARNINGS_PUSH_(4805 4100) // The upper limit for valid stack trace depths. const int kMaxStackTraceDepth = 100; @@ -201,8 +196,8 @@ std::set* GetIgnoredParameterizedTestSuites(); class GTestNonCopyable { public: GTestNonCopyable() = default; - GTestNonCopyable(const GTestNonCopyable &) = delete; - GTestNonCopyable &operator=(const GTestNonCopyable &) = delete; + GTestNonCopyable(const GTestNonCopyable&) = delete; + GTestNonCopyable& operator=(const GTestNonCopyable&) = delete; ~GTestNonCopyable() = default; }; @@ -301,7 +296,13 @@ class GTEST_API_ Test { // SetUp/TearDown method of Environment objects registered with Google // Test) will be output as attributes of the element. static void RecordProperty(const std::string& key, const std::string& value); - static void RecordProperty(const std::string& key, int64_t value); + // We do not define a custom serialization except for values that can be + // converted to int64_t, but other values could be logged in this way. + template ::value, + bool> = true> + static void RecordProperty(const std::string& key, const T& value) { + RecordProperty(key, (Message() << value).GetString()); + } protected: // Creates a Test object. @@ -549,14 +550,14 @@ class GTEST_API_ TestInfo { // Returns the name of the parameter type, or NULL if this is not a typed // or a type-parameterized test. const char* type_param() const { - if (type_param_.get() != nullptr) return type_param_->c_str(); + if (type_param_ != nullptr) return type_param_->c_str(); return nullptr; } // Returns the text representation of the value parameter, or NULL if this // is not a value-parameterized test. const char* value_param() const { - if (value_param_.get() != nullptr) return value_param_->c_str(); + if (value_param_ != nullptr) return value_param_->c_str(); return nullptr; } @@ -598,7 +599,7 @@ class GTEST_API_ TestInfo { const TestResult* result() const { return &result_; } private: -#if GTEST_HAS_DEATH_TEST +#ifdef GTEST_HAS_DEATH_TEST friend class internal::DefaultDeathTestFactory; #endif // GTEST_HAS_DEATH_TEST friend class Test; @@ -606,7 +607,7 @@ class GTEST_API_ TestInfo { friend class internal::UnitTestImpl; friend class internal::StreamingListenerTest; friend TestInfo* internal::MakeAndRegisterTestInfo( - const char* test_suite_name, const char* name, const char* type_param, + std::string test_suite_name, const char* name, const char* type_param, const char* value_param, internal::CodeLocation code_location, internal::TypeId fixture_class_id, internal::SetUpTestSuiteFunc set_up_tc, internal::TearDownTestSuiteFunc tear_down_tc, @@ -614,7 +615,7 @@ class GTEST_API_ TestInfo { // Constructs a TestInfo object. The newly constructed instance assumes // ownership of the factory object. - TestInfo(const std::string& test_suite_name, const std::string& name, + TestInfo(std::string test_suite_name, std::string name, const char* a_type_param, // NULL if not a type-parameterized test const char* a_value_param, // NULL if not a value-parameterized test internal::CodeLocation a_code_location, @@ -682,7 +683,7 @@ class GTEST_API_ TestSuite { // this is not a type-parameterized test. // 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(const char* name, const char* a_type_param, + TestSuite(const std::string& name, const char* a_type_param, internal::SetUpTestSuiteFunc set_up_tc, internal::TearDownTestSuiteFunc tear_down_tc); @@ -695,7 +696,7 @@ class GTEST_API_ TestSuite { // Returns the name of the parameter type, or NULL if this is not a // type-parameterized test suite. const char* type_param() const { - if (type_param_.get() != nullptr) return type_param_->c_str(); + if (type_param_ != nullptr) return type_param_->c_str(); return nullptr; } @@ -892,7 +893,7 @@ class GTEST_API_ TestSuite { class Environment { public: // The d'tor is virtual as we need to subclass Environment. - virtual ~Environment() {} + virtual ~Environment() = default; // Override this to define how to set up the environment. virtual void SetUp() {} @@ -923,7 +924,7 @@ class GTEST_API_ AssertionException // the order the corresponding events are fired. class TestEventListener { public: - virtual ~TestEventListener() {} + virtual ~TestEventListener() = default; // Fired before any test activity starts. virtual void OnTestProgramStart(const UnitTest& unit_test) = 0; @@ -1053,6 +1054,10 @@ class GTEST_API_ TestEventListeners { return default_xml_generator_; } + // Controls whether events will be forwarded by the repeater to the + // listeners in the list. + void SuppressEventForwarding(bool); + private: friend class TestSuite; friend class TestInfo; @@ -1082,7 +1087,6 @@ class GTEST_API_ TestEventListeners { // Controls whether events will be forwarded by the repeater to the // listeners in the list. bool EventForwardingEnabled() const; - void SuppressEventForwarding(); // The actual list of listeners. internal::TestEventRepeater* repeater_; @@ -1258,6 +1262,20 @@ class GTEST_API_ UnitTest { // total_test_suite_count() - 1. If i is not in that range, returns NULL. TestSuite* GetMutableTestSuite(int i); + // Invokes OsStackTrackGetterInterface::UponLeavingGTest. UponLeavingGTest() + // should be called immediately before Google Test calls user code. It saves + // some information about the current stack that CurrentStackTrace() will use + // to find and hide Google Test stack frames. + void UponLeavingGTest(); + + // Sets the TestSuite object for the test that's currently running. + void set_current_test_suite(TestSuite* a_current_test_suite) + GTEST_LOCK_EXCLUDED_(mutex_); + + // Sets the TestInfo object for the test that's currently running. + void set_current_test_info(TestInfo* a_current_test_info) + GTEST_LOCK_EXCLUDED_(mutex_); + // Accessors for the implementation object. internal::UnitTestImpl* impl() { return impl_; } const internal::UnitTestImpl* impl() const { return impl_; } @@ -1266,6 +1284,8 @@ class GTEST_API_ UnitTest { // members of UnitTest. friend class ScopedTrace; friend class Test; + friend class TestInfo; + friend class TestSuite; friend class internal::AssertHelper; friend class internal::StreamingListenerTest; friend class internal::UnitTestRecordPropertyTestHelper; @@ -1569,12 +1589,12 @@ AssertionResult CmpHelperFloatingPointEQ(const char* lhs_expression, } ::std::stringstream lhs_ss; - lhs_ss << std::setprecision(std::numeric_limits::digits10 + 2) - << lhs_value; + lhs_ss.precision(std::numeric_limits::digits10 + 2); + lhs_ss << lhs_value; ::std::stringstream rhs_ss; - rhs_ss << std::setprecision(std::numeric_limits::digits10 + 2) - << rhs_value; + rhs_ss.precision(std::numeric_limits::digits10 + 2); + rhs_ss << rhs_value; return EqFailure(lhs_expression, rhs_expression, StringStreamToString(&lhs_ss), StringStreamToString(&rhs_ss), @@ -1669,7 +1689,7 @@ template class WithParamInterface { public: typedef T ParamType; - virtual ~WithParamInterface() {} + virtual ~WithParamInterface() = default; // The current parameter value. Is also available in the test fixture's // constructor. @@ -1745,8 +1765,9 @@ class TestWithParam : public Test, public WithParamInterface {}; // Define this macro to 1 to omit the definition of FAIL(), which is a // generic name and clashes with some other libraries. -#if !GTEST_DONT_DEFINE_FAIL +#if !(defined(GTEST_DONT_DEFINE_FAIL) && GTEST_DONT_DEFINE_FAIL) #define FAIL() GTEST_FAIL() +#define FAIL_AT(file, line) GTEST_FAIL_AT(file, line) #endif // Generates a success with a generic message. @@ -1754,7 +1775,7 @@ class TestWithParam : public Test, public WithParamInterface {}; // Define this macro to 1 to omit the definition of SUCCEED(), which // is a generic name and clashes with some other libraries. -#if !GTEST_DONT_DEFINE_SUCCEED +#if !(defined(GTEST_DONT_DEFINE_SUCCEED) && GTEST_DONT_DEFINE_SUCCEED) #define SUCCEED() GTEST_SUCCEED() #endif @@ -1798,19 +1819,19 @@ class TestWithParam : public Test, public WithParamInterface {}; // Define these macros to 1 to omit the definition of the corresponding // EXPECT or ASSERT, which clashes with some users' own code. -#if !GTEST_DONT_DEFINE_EXPECT_TRUE +#if !(defined(GTEST_DONT_DEFINE_EXPECT_TRUE) && GTEST_DONT_DEFINE_EXPECT_TRUE) #define EXPECT_TRUE(condition) GTEST_EXPECT_TRUE(condition) #endif -#if !GTEST_DONT_DEFINE_EXPECT_FALSE +#if !(defined(GTEST_DONT_DEFINE_EXPECT_FALSE) && GTEST_DONT_DEFINE_EXPECT_FALSE) #define EXPECT_FALSE(condition) GTEST_EXPECT_FALSE(condition) #endif -#if !GTEST_DONT_DEFINE_ASSERT_TRUE +#if !(defined(GTEST_DONT_DEFINE_ASSERT_TRUE) && GTEST_DONT_DEFINE_ASSERT_TRUE) #define ASSERT_TRUE(condition) GTEST_ASSERT_TRUE(condition) #endif -#if !GTEST_DONT_DEFINE_ASSERT_FALSE +#if !(defined(GTEST_DONT_DEFINE_ASSERT_FALSE) && GTEST_DONT_DEFINE_ASSERT_FALSE) #define ASSERT_FALSE(condition) GTEST_ASSERT_FALSE(condition) #endif @@ -1889,27 +1910,27 @@ class TestWithParam : public Test, public WithParamInterface {}; // Define macro GTEST_DONT_DEFINE_ASSERT_XY to 1 to omit the definition of // ASSERT_XY(), which clashes with some users' own code. -#if !GTEST_DONT_DEFINE_ASSERT_EQ +#if !(defined(GTEST_DONT_DEFINE_ASSERT_EQ) && GTEST_DONT_DEFINE_ASSERT_EQ) #define ASSERT_EQ(val1, val2) GTEST_ASSERT_EQ(val1, val2) #endif -#if !GTEST_DONT_DEFINE_ASSERT_NE +#if !(defined(GTEST_DONT_DEFINE_ASSERT_NE) && GTEST_DONT_DEFINE_ASSERT_NE) #define ASSERT_NE(val1, val2) GTEST_ASSERT_NE(val1, val2) #endif -#if !GTEST_DONT_DEFINE_ASSERT_LE +#if !(defined(GTEST_DONT_DEFINE_ASSERT_LE) && GTEST_DONT_DEFINE_ASSERT_LE) #define ASSERT_LE(val1, val2) GTEST_ASSERT_LE(val1, val2) #endif -#if !GTEST_DONT_DEFINE_ASSERT_LT +#if !(defined(GTEST_DONT_DEFINE_ASSERT_LT) && GTEST_DONT_DEFINE_ASSERT_LT) #define ASSERT_LT(val1, val2) GTEST_ASSERT_LT(val1, val2) #endif -#if !GTEST_DONT_DEFINE_ASSERT_GE +#if !(defined(GTEST_DONT_DEFINE_ASSERT_GE) && GTEST_DONT_DEFINE_ASSERT_GE) #define ASSERT_GE(val1, val2) GTEST_ASSERT_GE(val1, val2) #endif -#if !GTEST_DONT_DEFINE_ASSERT_GT +#if !(defined(GTEST_DONT_DEFINE_ASSERT_GT) && GTEST_DONT_DEFINE_ASSERT_GT) #define ASSERT_GT(val1, val2) GTEST_ASSERT_GT(val1, val2) #endif @@ -1997,7 +2018,7 @@ GTEST_API_ AssertionResult FloatLE(const char* expr1, const char* expr2, GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2, double val1, double val2); -#if GTEST_OS_WINDOWS +#ifdef GTEST_OS_WINDOWS // Macros that test for HRESULT failure and success, these are only useful // on Windows, and rely on Windows SDK macros and APIs to compile. @@ -2096,8 +2117,8 @@ class GTEST_API_ ScopedTrace { // Assuming that each thread maintains its own stack of traces. // Therefore, a SCOPED_TRACE() would (correctly) only affect the // assertions in its own thread. -#define SCOPED_TRACE(message) \ - ::testing::ScopedTrace GTEST_CONCAT_TOKEN_(gtest_trace_, __LINE__)( \ +#define SCOPED_TRACE(message) \ + const ::testing::ScopedTrace GTEST_CONCAT_TOKEN_(gtest_trace_, __LINE__)( \ __FILE__, __LINE__, (message)) // Compile-time assertion for type equality. @@ -2167,7 +2188,7 @@ constexpr bool StaticAssertTypeEq() noexcept { // Define this macro to 1 to omit the definition of TEST(), which // is a generic name and clashes with some other libraries. -#if !GTEST_DONT_DEFINE_TEST +#if !(defined(GTEST_DONT_DEFINE_TEST) && GTEST_DONT_DEFINE_TEST) #define TEST(test_suite_name, test_name) GTEST_TEST(test_suite_name, test_name) #endif @@ -2199,7 +2220,7 @@ constexpr bool StaticAssertTypeEq() noexcept { #define GTEST_TEST_F(test_fixture, test_name) \ GTEST_TEST_(test_fixture, test_name, test_fixture, \ ::testing::internal::GetTypeId()) -#if !GTEST_DONT_DEFINE_TEST_F +#if !(defined(GTEST_DONT_DEFINE_TEST_F) && GTEST_DONT_DEFINE_TEST_F) #define TEST_F(test_fixture, test_name) GTEST_TEST_F(test_fixture, test_name) #endif @@ -2214,9 +2235,7 @@ GTEST_API_ std::string TempDir(); // in it should be considered read-only. GTEST_API_ std::string SrcDir(); -#ifdef _MSC_VER -#pragma warning(pop) -#endif +GTEST_DISABLE_MSC_WARNINGS_POP_() // 4805 4100 // Dynamically registers a test with the framework. // @@ -2305,7 +2324,8 @@ TestInfo* RegisterTest(const char* test_suite_name, const char* test_name, // tests are successful, or 1 otherwise. // // RUN_ALL_TESTS() should be invoked after the command line has been -// parsed by InitGoogleTest(). +// parsed by InitGoogleTest(). RUN_ALL_TESTS will tear down and delete any +// installed environments and should only be called once per binary. // // This function was formerly a macro; thus, it is in the global // namespace and has an all-caps name. diff --git a/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/internal/gtest-death-test-internal.h b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/internal/gtest-death-test-internal.h index 4687dae2b46..b363259ec60 100644 --- a/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/internal/gtest-death-test-internal.h +++ b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/internal/gtest-death-test-internal.h @@ -46,18 +46,39 @@ #include "gtest/gtest-matchers.h" #include "gtest/internal/gtest-internal.h" +#include "gtest/internal/gtest-port.h" GTEST_DECLARE_string_(internal_run_death_test); namespace testing { namespace internal { -// Names of the flags (needed for parsing Google Test flags). -const char kDeathTestStyleFlag[] = "death_test_style"; -const char kDeathTestUseFork[] = "death_test_use_fork"; +// Name of the flag (needed for parsing Google Test flag). const char kInternalRunDeathTestFlag[] = "internal_run_death_test"; -#if GTEST_HAS_DEATH_TEST +// A string passed to EXPECT_DEATH (etc.) is caught by one of these overloads +// and interpreted as a regex (rather than an Eq matcher) for legacy +// compatibility. +inline Matcher MakeDeathTestMatcher( + ::testing::internal::RE regex) { + return ContainsRegex(regex.pattern()); +} +inline Matcher MakeDeathTestMatcher(const char* regex) { + return ContainsRegex(regex); +} +inline Matcher MakeDeathTestMatcher( + const ::std::string& regex) { + return ContainsRegex(regex); +} + +// If a Matcher is passed to EXPECT_DEATH (etc.), it's +// used directly. +inline Matcher MakeDeathTestMatcher( + Matcher matcher) { + return matcher; +} + +#ifdef GTEST_HAS_DEATH_TEST GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \ /* class A needs to have dll-interface to be used by clients of class B */) @@ -73,7 +94,7 @@ GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \ // // exit status: The integer exit information in the format specified // by wait(2) -// exit code: The integer code passed to exit(3), _exit(2), or +// exit code: The integer code passed to exit(3), _Exit(2), or // returned from main() class GTEST_API_ DeathTest { public: @@ -88,7 +109,7 @@ class GTEST_API_ DeathTest { static bool Create(const char* statement, Matcher matcher, const char* file, int line, DeathTest** test); DeathTest(); - virtual ~DeathTest() {} + virtual ~DeathTest() = default; // A helper class that aborts a death test when it's deleted. class ReturnSentinel { @@ -153,7 +174,7 @@ GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 // Factory interface for death tests. May be mocked out for testing. class DeathTestFactory { public: - virtual ~DeathTestFactory() {} + virtual ~DeathTestFactory() = default; virtual bool Create(const char* statement, Matcher matcher, const char* file, int line, DeathTest** test) = 0; @@ -170,28 +191,6 @@ class DefaultDeathTestFactory : public DeathTestFactory { // by a signal, or exited normally with a nonzero exit code. GTEST_API_ bool ExitedUnsuccessfully(int exit_status); -// A string passed to EXPECT_DEATH (etc.) is caught by one of these overloads -// and interpreted as a regex (rather than an Eq matcher) for legacy -// compatibility. -inline Matcher MakeDeathTestMatcher( - ::testing::internal::RE regex) { - return ContainsRegex(regex.pattern()); -} -inline Matcher MakeDeathTestMatcher(const char* regex) { - return ContainsRegex(regex); -} -inline Matcher MakeDeathTestMatcher( - const ::std::string& regex) { - return ContainsRegex(regex); -} - -// If a Matcher is passed to EXPECT_DEATH (etc.), it's -// used directly. -inline Matcher MakeDeathTestMatcher( - Matcher matcher) { - return matcher; -} - // Traps C++ exceptions escaping statement and reports them as test // failures. Note that trapping SEH exceptions is not implemented here. #if GTEST_HAS_EXCEPTIONS @@ -238,7 +237,7 @@ inline Matcher MakeDeathTestMatcher( } \ break; \ case ::testing::internal::DeathTest::EXECUTE_TEST: { \ - ::testing::internal::DeathTest::ReturnSentinel gtest_sentinel( \ + const ::testing::internal::DeathTest::ReturnSentinel gtest_sentinel( \ gtest_dt); \ GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, gtest_dt); \ gtest_dt->Abort(::testing::internal::DeathTest::TEST_DID_NOT_DIE); \ diff --git a/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/internal/gtest-filepath.h b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/internal/gtest-filepath.h index 5189c81dabf..6dc47be54ad 100644 --- a/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/internal/gtest-filepath.h +++ b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/internal/gtest-filepath.h @@ -43,6 +43,7 @@ #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_ #include +#include #include "gtest/internal/gtest-port.h" #include "gtest/internal/gtest-string.h" @@ -70,8 +71,9 @@ class GTEST_API_ FilePath { public: FilePath() : pathname_("") {} FilePath(const FilePath& rhs) : pathname_(rhs.pathname_) {} + FilePath(FilePath&& rhs) noexcept : pathname_(std::move(rhs.pathname_)) {} - explicit FilePath(const std::string& pathname) : pathname_(pathname) { + explicit FilePath(std::string pathname) : pathname_(std::move(pathname)) { Normalize(); } @@ -79,6 +81,10 @@ class GTEST_API_ FilePath { Set(rhs); return *this; } + FilePath& operator=(FilePath&& rhs) noexcept { + pathname_ = std::move(rhs.pathname_); + return *this; + } void Set(const FilePath& rhs) { pathname_ = rhs.pathname_; } diff --git a/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/internal/gtest-internal.h b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/internal/gtest-internal.h index 3121d428b39..7e55dc605cb 100644 --- a/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/internal/gtest-internal.h +++ b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/internal/gtest-internal.h @@ -41,7 +41,7 @@ #include "gtest/internal/gtest-port.h" -#if GTEST_OS_LINUX +#ifdef GTEST_OS_LINUX #include #include #include @@ -58,7 +58,6 @@ #include #include -#include #include #include #include @@ -79,7 +78,7 @@ // // will result in the token foo__LINE__, instead of foo followed by // the current line number. For more details, see -// http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.6 +// https://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.6 #define GTEST_CONCAT_TOKEN_(foo, bar) GTEST_CONCAT_TOKEN_IMPL_(foo, bar) #define GTEST_CONCAT_TOKEN_IMPL_(foo, bar) foo##bar @@ -170,7 +169,7 @@ namespace edit_distance { // All edits cost the same, with replace having lower priority than // add/remove. // Simple implementation of the Wagner-Fischer algorithm. -// See http://en.wikipedia.org/wiki/Wagner-Fischer_algorithm +// See https://en.wikipedia.org/wiki/Wagner-Fischer_algorithm enum EditType { kMatch, kAdd, kRemove, kReplace }; GTEST_API_ std::vector CalculateOptimalEdits( const std::vector& left, const std::vector& right); @@ -237,7 +236,7 @@ GTEST_API_ std::string GetBoolAssertionFailureMessage( // For double, there are 11 exponent bits and 52 fraction bits. // // More details can be found at -// http://en.wikipedia.org/wiki/IEEE_floating-point_standard. +// https://en.wikipedia.org/wiki/IEEE_floating-point_standard. // // Template parameter: // @@ -282,7 +281,7 @@ class FloatingPoint { // bits. Therefore, 4 should be enough for ordinary use. // // See the following article for more details on ULP: - // http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/ + // https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/ static const uint32_t kMaxUlps = 4; // Constructs a FloatingPoint from a raw floating-point number. @@ -307,9 +306,6 @@ class FloatingPoint { // Returns the floating-point number that represent positive infinity. static RawType Infinity() { return ReinterpretBits(kExponentBitMask); } - // Returns the maximum representable finite floating-point number. - static RawType Max(); - // Non-static methods // Returns the bits that represents this number. @@ -366,7 +362,7 @@ class FloatingPoint { // N - 1 (the biggest number representable using // sign-and-magnitude) is represented by 2N - 1. // - // Read http://en.wikipedia.org/wiki/Signed_number_representations + // Read https://en.wikipedia.org/wiki/Signed_number_representations // for more details on signed number representations. static Bits SignAndMagnitudeToBiased(const Bits& sam) { if (kSignBitMask & sam) { @@ -390,17 +386,6 @@ class FloatingPoint { FloatingPointUnion u_; }; -// We cannot use std::numeric_limits::max() as it clashes with the max() -// macro defined by . -template <> -inline float FloatingPoint::Max() { - return FLT_MAX; -} -template <> -inline double FloatingPoint::Max() { - return DBL_MAX; -} - // Typedefs the instances of the FloatingPoint template class that we // care to use. typedef FloatingPoint Float; @@ -449,7 +434,7 @@ GTEST_API_ TypeId GetTestTypeId(); // of a Test object. class TestFactoryBase { public: - virtual ~TestFactoryBase() {} + virtual ~TestFactoryBase() = default; // Creates a test instance to run. The instance is both created and destroyed // within TestInfoImpl::Run() @@ -471,7 +456,7 @@ class TestFactoryImpl : public TestFactoryBase { Test* CreateTest() override { return new TestClass; } }; -#if GTEST_OS_WINDOWS +#ifdef GTEST_OS_WINDOWS // Predicate-formatters for implementing the HRESULT checking macros // {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED} @@ -489,8 +474,8 @@ using SetUpTestSuiteFunc = void (*)(); using TearDownTestSuiteFunc = void (*)(); struct CodeLocation { - CodeLocation(const std::string& a_file, int a_line) - : file(a_file), line(a_line) {} + CodeLocation(std::string a_file, int a_line) + : file(std::move(a_file)), line(a_line) {} std::string file; int line; @@ -570,7 +555,7 @@ struct SuiteApiResolver : T { // 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 type-parameterized test. +// 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 @@ -579,7 +564,7 @@ struct SuiteApiResolver : T { // The newly created TestInfo instance will assume // ownership of the factory object. GTEST_API_ TestInfo* MakeAndRegisterTestInfo( - const char* test_suite_name, const char* name, const char* type_param, + 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); @@ -610,8 +595,7 @@ class GTEST_API_ TypedTestSuitePState { fflush(stderr); posix::Abort(); } - registered_tests_.insert( - ::std::make_pair(test_name, CodeLocation(file, line))); + registered_tests_.emplace(test_name, CodeLocation(file, line)); return true; } @@ -715,7 +699,7 @@ class TypeParameterizedTest { // specified in INSTANTIATE_TYPED_TEST_SUITE_P(Prefix, TestSuite, // Types). Valid values for 'index' are [0, N - 1] where N is the // length of Types. - static bool Register(const char* prefix, const CodeLocation& code_location, + static bool Register(const char* prefix, CodeLocation code_location, const char* case_name, const char* test_names, int index, const std::vector& type_names = GenerateNames()) { @@ -727,8 +711,7 @@ class TypeParameterizedTest { // list. MakeAndRegisterTestInfo( (std::string(prefix) + (prefix[0] == '\0' ? "" : "/") + case_name + - "/" + type_names[static_cast(index)]) - .c_str(), + "/" + type_names[static_cast(index)]), StripTrailingSpaces(GetPrefixUntilComma(test_names)).c_str(), GetTypeName().c_str(), nullptr, // No value parameter. @@ -740,13 +723,9 @@ class TypeParameterizedTest { new TestFactoryImpl); // Next, recurses (at compile time) with the tail of the type list. - return TypeParameterizedTest::Register(prefix, - code_location, - case_name, - test_names, - index + 1, - type_names); + return TypeParameterizedTest:: + Register(prefix, std::move(code_location), case_name, test_names, + index + 1, type_names); } }; @@ -754,7 +733,7 @@ class TypeParameterizedTest { template class TypeParameterizedTest { public: - static bool Register(const char* /*prefix*/, const CodeLocation&, + static bool Register(const char* /*prefix*/, CodeLocation, const char* /*case_name*/, const char* /*test_names*/, int /*index*/, const std::vector& = @@ -801,7 +780,8 @@ class TypeParameterizedTestSuite { // Next, recurses (at compile time) with the tail of the test list. return TypeParameterizedTestSuite::Register(prefix, code_location, + Types>::Register(prefix, + std::move(code_location), state, case_name, SkipComma(test_names), type_names); @@ -914,8 +894,10 @@ class HasDebugStringAndShortDebugString { HasDebugStringType::value && HasShortDebugStringType::value; }; +#ifdef GTEST_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL template constexpr bool HasDebugStringAndShortDebugString::value; +#endif // When the compiler sees expression IsContainerTest(0), if C is an // STL-style container class, the first overload of IsContainerTest @@ -1155,40 +1137,6 @@ class NativeArray { void (NativeArray::*clone_)(const Element*, size_t); }; -// Backport of std::index_sequence. -template -struct IndexSequence { - using type = IndexSequence; -}; - -// Double the IndexSequence, and one if plus_one is true. -template -struct DoubleSequence; -template -struct DoubleSequence, sizeofT> { - using type = IndexSequence; -}; -template -struct DoubleSequence, sizeofT> { - using type = IndexSequence; -}; - -// Backport of std::make_index_sequence. -// It uses O(ln(N)) instantiation depth. -template -struct MakeIndexSequenceImpl - : DoubleSequence::type, - N / 2>::type {}; - -template <> -struct MakeIndexSequenceImpl<0> : IndexSequence<> {}; - -template -using MakeIndexSequence = typename MakeIndexSequenceImpl::type; - -template -using IndexSequenceFor = typename MakeIndexSequence::type; - template struct Ignore { Ignore(...); // NOLINT @@ -1197,7 +1145,7 @@ struct Ignore { template struct ElemFromListImpl; template -struct ElemFromListImpl> { +struct ElemFromListImpl> { // We make Ignore a template to solve a problem with MSVC. // A non-template Ignore would work fine with `decltype(Ignore(I))...`, but // MSVC doesn't understand how to deal with that pack expansion. @@ -1208,9 +1156,8 @@ struct ElemFromListImpl> { template struct ElemFromList { - using type = - decltype(ElemFromListImpl::type>::Apply( - static_cast(nullptr)...)); + using type = decltype(ElemFromListImpl>::Apply( + static_cast(nullptr)...)); }; struct FlatTupleConstructTag {}; @@ -1235,9 +1182,9 @@ template struct FlatTupleBase; template -struct FlatTupleBase, IndexSequence> +struct FlatTupleBase, std::index_sequence> : FlatTupleElemBase, Idx>... { - using Indices = IndexSequence; + using Indices = std::index_sequence; FlatTupleBase() = default; template explicit FlatTupleBase(FlatTupleConstructTag, Args&&... args) @@ -1272,14 +1219,15 @@ struct FlatTupleBase, IndexSequence> // implementations. // FlatTuple and ElemFromList are not recursive and have a fixed depth // regardless of T... -// MakeIndexSequence, on the other hand, it is recursive but with an +// std::make_index_sequence, on the other hand, it is recursive but with an // instantiation depth of O(ln(N)). template class FlatTuple : private FlatTupleBase, - typename MakeIndexSequence::type> { - using Indices = typename FlatTupleBase< - FlatTuple, typename MakeIndexSequence::type>::Indices; + std::make_index_sequence> { + using Indices = + typename FlatTupleBase, + std::make_index_sequence>::Indices; public: FlatTuple() = default; @@ -1509,19 +1457,20 @@ class NeverThrown { gtest_ar_, text, #actual, #expected) \ .c_str()) -#define GTEST_TEST_NO_FATAL_FAILURE_(statement, fail) \ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (::testing::internal::AlwaysTrue()) { \ - ::testing::internal::HasNewFatalFailureHelper gtest_fatal_failure_checker; \ - GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ - if (gtest_fatal_failure_checker.has_new_fatal_failure()) { \ - goto GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__); \ - } \ - } else \ - GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__) \ - : fail("Expected: " #statement \ - " doesn't generate new fatal " \ - "failures in the current thread.\n" \ +#define GTEST_TEST_NO_FATAL_FAILURE_(statement, fail) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (::testing::internal::AlwaysTrue()) { \ + const ::testing::internal::HasNewFatalFailureHelper \ + gtest_fatal_failure_checker; \ + GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ + if (gtest_fatal_failure_checker.has_new_fatal_failure()) { \ + goto GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__); \ + } \ + } else /* NOLINT */ \ + GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__) \ + : fail("Expected: " #statement \ + " doesn't generate new fatal " \ + "failures in the current thread.\n" \ " Actual: it does.") // Expands to the name of the class that implements the given test. @@ -1552,7 +1501,8 @@ class NeverThrown { \ private: \ void TestBody() override; \ - static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_; \ + GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED static ::testing::TestInfo* const \ + test_info_; \ }; \ \ ::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_suite_name, \ diff --git a/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/internal/gtest-param-util.h b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/internal/gtest-param-util.h index 7092d10e677..cc7ea531738 100644 --- a/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/internal/gtest-param-util.h +++ b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/internal/gtest-param-util.h @@ -47,6 +47,7 @@ #include #include #include +#include #include #include @@ -85,7 +86,7 @@ namespace internal { // TEST_P macro is used to define two tests with the same name // but in different namespaces. GTEST_API_ void ReportInvalidTestSuiteType(const char* test_suite_name, - CodeLocation code_location); + const CodeLocation& code_location); template class ParamGeneratorInterface; @@ -97,7 +98,7 @@ class ParamGenerator; template class ParamIteratorInterface { public: - virtual ~ParamIteratorInterface() {} + virtual ~ParamIteratorInterface() = default; // A pointer to the base generator instance. // Used only for the purposes of iterator comparison // to make sure that two iterators belong to the same generator. @@ -171,7 +172,7 @@ class ParamGeneratorInterface { public: typedef T ParamType; - virtual ~ParamGeneratorInterface() {} + virtual ~ParamGeneratorInterface() = default; // Generator interface definition virtual ParamIteratorInterface* Begin() const = 0; @@ -215,7 +216,7 @@ class RangeGenerator : public ParamGeneratorInterface { end_(end), step_(step), end_index_(CalculateEndIndex(begin, end, step)) {} - ~RangeGenerator() override {} + ~RangeGenerator() override = default; ParamIteratorInterface* Begin() const override { return new Iterator(this, begin_, 0, step_); @@ -230,7 +231,7 @@ class RangeGenerator : public ParamGeneratorInterface { Iterator(const ParamGeneratorInterface* base, T value, int index, IncrementT step) : base_(base), value_(value), index_(index), step_(step) {} - ~Iterator() override {} + ~Iterator() override = default; const ParamGeneratorInterface* BaseGenerator() const override { return base_; @@ -299,7 +300,7 @@ class ValuesInIteratorRangeGenerator : public ParamGeneratorInterface { template ValuesInIteratorRangeGenerator(ForwardIterator begin, ForwardIterator end) : container_(begin, end) {} - ~ValuesInIteratorRangeGenerator() override {} + ~ValuesInIteratorRangeGenerator() override = default; ParamIteratorInterface* Begin() const override { return new Iterator(this, container_.begin()); @@ -316,7 +317,7 @@ class ValuesInIteratorRangeGenerator : public ParamGeneratorInterface { Iterator(const ParamGeneratorInterface* base, typename ContainerType::const_iterator iterator) : base_(base), iterator_(iterator) {} - ~Iterator() override {} + ~Iterator() override = default; const ParamGeneratorInterface* BaseGenerator() const override { return base_; @@ -379,9 +380,7 @@ class ValuesInIteratorRangeGenerator : public ParamGeneratorInterface { // integer test parameter index. template std::string DefaultParamName(const TestParamInfo& info) { - Message name_stream; - name_stream << info.index; - return name_stream.GetString(); + return std::to_string(info.index); } template @@ -420,7 +419,7 @@ class ParameterizedTestFactory : public TestFactoryBase { template class TestMetaFactoryBase { public: - virtual ~TestMetaFactoryBase() {} + virtual ~TestMetaFactoryBase() = default; virtual TestFactoryBase* CreateTestFactory(ParamType parameter) = 0; }; @@ -439,7 +438,7 @@ class TestMetaFactory public: using ParamType = typename TestSuite::ParamType; - TestMetaFactory() {} + TestMetaFactory() = default; TestFactoryBase* CreateTestFactory(ParamType parameter) override { return new ParameterizedTestFactory(parameter); @@ -462,7 +461,7 @@ class TestMetaFactory // and calls RegisterTests() on each of them when asked. class ParameterizedTestSuiteInfoBase { public: - virtual ~ParameterizedTestSuiteInfoBase() {} + virtual ~ParameterizedTestSuiteInfoBase() = default; // Base part of test suite name for display purposes. virtual const std::string& GetTestSuiteName() const = 0; @@ -513,9 +512,10 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase { typedef ParamGenerator(GeneratorCreationFunc)(); using ParamNameGeneratorFunc = std::string(const TestParamInfo&); - explicit ParameterizedTestSuiteInfo(const char* name, + explicit ParameterizedTestSuiteInfo(std::string name, CodeLocation code_location) - : test_suite_name_(name), code_location_(code_location) {} + : test_suite_name_(std::move(name)), + code_location_(std::move(code_location)) {} // Test suite base name for display purposes. const std::string& GetTestSuiteName() const override { @@ -529,20 +529,21 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase { // prefix). test_base_name is the name of an individual test without // parameter index. For the test SequenceA/FooTest.DoBar/1 FooTest is // test suite base name and DoBar is test base name. - void AddTestPattern(const char* test_suite_name, const char* test_base_name, + void AddTestPattern(const char*, + const char* test_base_name, TestMetaFactoryBase* meta_factory, CodeLocation code_location) { - tests_.push_back(std::shared_ptr(new TestInfo( - test_suite_name, test_base_name, meta_factory, code_location))); + tests_.emplace_back( + new TestInfo(test_base_name, meta_factory, std::move(code_location))); } // INSTANTIATE_TEST_SUITE_P macro uses AddGenerator() to record information // about a generator. - int AddTestSuiteInstantiation(const std::string& instantiation_name, + int AddTestSuiteInstantiation(std::string instantiation_name, GeneratorCreationFunc* func, ParamNameGeneratorFunc* name_func, const char* file, int line) { - instantiations_.push_back( - InstantiationInfo(instantiation_name, func, name_func, file, line)); + instantiations_.emplace_back(std::move(instantiation_name), func, name_func, + file, line); return 0; // Return value used only to run this method in namespace scope. } // UnitTest class invokes this method to register tests in this test suite @@ -553,60 +554,61 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase { void RegisterTests() override { bool generated_instantiations = false; - for (typename TestInfoContainer::iterator test_it = tests_.begin(); - test_it != tests_.end(); ++test_it) { - std::shared_ptr test_info = *test_it; - for (typename InstantiationContainer::iterator gen_it = - instantiations_.begin(); - gen_it != instantiations_.end(); ++gen_it) { - const std::string& instantiation_name = gen_it->name; - ParamGenerator generator((*gen_it->generator)()); - ParamNameGeneratorFunc* name_func = gen_it->name_func; - const char* file = gen_it->file; - int line = gen_it->line; - - std::string test_suite_name; + std::string test_suite_name; + std::string test_name; + for (const std::shared_ptr& test_info : tests_) { + for (const InstantiationInfo& instantiation : instantiations_) { + const std::string& instantiation_name = instantiation.name; + ParamGenerator generator((*instantiation.generator)()); + ParamNameGeneratorFunc* name_func = instantiation.name_func; + const char* file = instantiation.file; + int line = instantiation.line; + if (!instantiation_name.empty()) test_suite_name = instantiation_name + "/"; - test_suite_name += test_info->test_suite_base_name; + else + test_suite_name.clear(); + test_suite_name += test_suite_name_; size_t i = 0; std::set test_param_names; - for (typename ParamGenerator::iterator param_it = - generator.begin(); - param_it != generator.end(); ++param_it, ++i) { + for (const auto& param : generator) { generated_instantiations = true; - Message test_name_stream; + test_name.clear(); std::string param_name = - name_func(TestParamInfo(*param_it, i)); + name_func(TestParamInfo(param, i)); GTEST_CHECK_(IsValidParamName(param_name)) << "Parameterized test name '" << param_name - << "' is invalid, in " << file << " line " << line << std::endl; + << "' is invalid (contains spaces, dashes, or any " + "non-alphanumeric characters other than underscores), in " + << file << " line " << line << "" << std::endl; GTEST_CHECK_(test_param_names.count(param_name) == 0) << "Duplicate parameterized test name '" << param_name << "', in " << file << " line " << line << std::endl; - test_param_names.insert(param_name); - if (!test_info->test_base_name.empty()) { - test_name_stream << test_info->test_base_name << "/"; + test_name.append(test_info->test_base_name).append("/"); } - test_name_stream << param_name; + test_name += param_name; + + test_param_names.insert(std::move(param_name)); + MakeAndRegisterTestInfo( - test_suite_name.c_str(), test_name_stream.GetString().c_str(), + test_suite_name, test_name.c_str(), nullptr, // No type parameter. - PrintToString(*param_it).c_str(), test_info->code_location, + PrintToString(param).c_str(), test_info->code_location, GetTestSuiteTypeId(), SuiteApiResolver::GetSetUpCaseOrSuite(file, line), SuiteApiResolver::GetTearDownCaseOrSuite(file, line), - test_info->test_meta_factory->CreateTestFactory(*param_it)); - } // for param_it - } // for gen_it - } // for test_it + test_info->test_meta_factory->CreateTestFactory(param)); + ++i; + } // for param + } // for instantiation + } // for test_info if (!generated_instantiations) { // There are no generaotrs, or they all generate nothing ... @@ -619,15 +621,13 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase { // LocalTestInfo structure keeps information about a single test registered // with TEST_P macro. struct TestInfo { - TestInfo(const char* a_test_suite_base_name, const char* a_test_base_name, + TestInfo(const char* a_test_base_name, TestMetaFactoryBase* a_test_meta_factory, CodeLocation a_code_location) - : test_suite_base_name(a_test_suite_base_name), - test_base_name(a_test_base_name), + : test_base_name(a_test_base_name), test_meta_factory(a_test_meta_factory), - code_location(a_code_location) {} + code_location(std::move(a_code_location)) {} - const std::string test_suite_base_name; const std::string test_base_name; const std::unique_ptr> test_meta_factory; const CodeLocation code_location; @@ -637,11 +637,10 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase { // struct InstantiationInfo { - InstantiationInfo(const std::string& name_in, - GeneratorCreationFunc* generator_in, + InstantiationInfo(std::string name_in, GeneratorCreationFunc* generator_in, ParamNameGeneratorFunc* name_func_in, const char* file_in, int line_in) - : name(name_in), + : name(std::move(name_in)), generator(generator_in), name_func(name_func_in), file(file_in), @@ -691,7 +690,7 @@ using ParameterizedTestCaseInfo = ParameterizedTestSuiteInfo; // ParameterizedTestSuiteInfo descriptors. class ParameterizedTestSuiteRegistry { public: - ParameterizedTestSuiteRegistry() {} + ParameterizedTestSuiteRegistry() = default; ~ParameterizedTestSuiteRegistry() { for (auto& test_suite_info : test_suite_infos_) { delete test_suite_info; @@ -702,29 +701,32 @@ class ParameterizedTestSuiteRegistry { // tests and instantiations of a particular test suite. template ParameterizedTestSuiteInfo* GetTestSuitePatternHolder( - const char* test_suite_name, CodeLocation code_location) { + std::string test_suite_name, CodeLocation code_location) { ParameterizedTestSuiteInfo* typed_test_info = nullptr; - for (auto& test_suite_info : test_suite_infos_) { - if (test_suite_info->GetTestSuiteName() == test_suite_name) { - if (test_suite_info->GetTestSuiteTypeId() != GetTypeId()) { - // Complain about incorrect usage of Google Test facilities - // and terminate the program since we cannot guaranty correct - // test suite setup and tear-down in this case. - ReportInvalidTestSuiteType(test_suite_name, code_location); - posix::Abort(); - } else { - // At this point we are sure that the object we found is of the same - // type we are looking for, so we downcast it to that type - // without further checks. - typed_test_info = CheckedDowncastToActualType< - ParameterizedTestSuiteInfo>(test_suite_info); - } - break; + + auto item_it = suite_name_to_info_index_.find(test_suite_name); + if (item_it != suite_name_to_info_index_.end()) { + auto* test_suite_info = test_suite_infos_[item_it->second]; + if (test_suite_info->GetTestSuiteTypeId() != GetTypeId()) { + // Complain about incorrect usage of Google Test facilities + // and terminate the program since we cannot guaranty correct + // test suite setup and tear-down in this case. + ReportInvalidTestSuiteType(test_suite_name.c_str(), code_location); + posix::Abort(); + } else { + // At this point we are sure that the object we found is of the same + // type we are looking for, so we downcast it to that type + // without further checks. + typed_test_info = + CheckedDowncastToActualType>( + test_suite_info); } } if (typed_test_info == nullptr) { typed_test_info = new ParameterizedTestSuiteInfo( - test_suite_name, code_location); + test_suite_name, std::move(code_location)); + suite_name_to_info_index_.emplace(std::move(test_suite_name), + test_suite_infos_.size()); test_suite_infos_.push_back(typed_test_info); } return typed_test_info; @@ -738,8 +740,9 @@ class ParameterizedTestSuiteRegistry { #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ template ParameterizedTestCaseInfo* GetTestCasePatternHolder( - const char* test_case_name, CodeLocation code_location) { - return GetTestSuitePatternHolder(test_case_name, code_location); + std::string test_case_name, CodeLocation code_location) { + return GetTestSuitePatternHolder(std::move(test_case_name), + std::move(code_location)); } #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ @@ -748,6 +751,7 @@ class ParameterizedTestSuiteRegistry { using TestSuiteInfoContainer = ::std::vector; TestSuiteInfoContainer test_suite_infos_; + ::std::unordered_map suite_name_to_info_index_; ParameterizedTestSuiteRegistry(const ParameterizedTestSuiteRegistry&) = delete; @@ -774,7 +778,7 @@ class TypeParameterizedTestSuiteRegistry { private: struct TypeParameterizedTestSuiteInfo { explicit TypeParameterizedTestSuiteInfo(CodeLocation c) - : code_location(c), instantiated(false) {} + : code_location(std::move(c)), instantiated(false) {} CodeLocation code_location; bool instantiated; @@ -794,10 +798,7 @@ internal::ParamGenerator ValuesIn( namespace internal { // Used in the Values() function to provide polymorphic capabilities. -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable : 4100) -#endif +GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100) template class ValueArray { @@ -806,21 +807,19 @@ class ValueArray { template operator ParamGenerator() const { // NOLINT - return ValuesIn(MakeVector(MakeIndexSequence())); + return ValuesIn(MakeVector(std::make_index_sequence())); } private: template - std::vector MakeVector(IndexSequence) const { + std::vector MakeVector(std::index_sequence) const { return std::vector{static_cast(v_.template Get())...}; } FlatTuple v_; }; -#ifdef _MSC_VER -#pragma warning(pop) -#endif +GTEST_DISABLE_MSC_WARNINGS_POP_() // 4100 template class CartesianProductGenerator @@ -830,7 +829,7 @@ class CartesianProductGenerator CartesianProductGenerator(const std::tuple...>& g) : generators_(g) {} - ~CartesianProductGenerator() override {} + ~CartesianProductGenerator() override = default; ParamIteratorInterface* Begin() const override { return new Iterator(this, generators_, false); @@ -843,7 +842,7 @@ class CartesianProductGenerator template class IteratorImpl; template - class IteratorImpl> + class IteratorImpl> : public ParamIteratorInterface { public: IteratorImpl(const ParamGeneratorInterface* base, @@ -855,7 +854,7 @@ class CartesianProductGenerator current_(is_end ? end_ : begin_) { ComputeCurrentValue(); } - ~IteratorImpl() override {} + ~IteratorImpl() override = default; const ParamGeneratorInterface* BaseGenerator() const override { return base_; @@ -934,7 +933,7 @@ class CartesianProductGenerator std::shared_ptr current_value_; }; - using Iterator = IteratorImpl::type>; + using Iterator = IteratorImpl>; std::tuple...> generators_; }; @@ -956,7 +955,7 @@ class CartesianProductHolder { template class ParamGeneratorConverter : public ParamGeneratorInterface { public: - ParamGeneratorConverter(ParamGenerator gen) // NOLINT + ParamGeneratorConverter(ParamGenerator gen) // NOLINT : generator_(std::move(gen)) {} ParamIteratorInterface* Begin() const override { @@ -974,7 +973,7 @@ class ParamGeneratorConverter : public ParamGeneratorInterface { : base_(base), it_(it), end_(end) { if (it_ != end_) value_ = std::make_shared(static_cast(*it_)); } - ~Iterator() override {} + ~Iterator() override = default; const ParamGeneratorInterface* BaseGenerator() const override { return base_; diff --git a/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/internal/gtest-port-arch.h b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/internal/gtest-port-arch.h index 04064606f5d..7ec968f312e 100644 --- a/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/internal/gtest-port-arch.h +++ b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/internal/gtest-port-arch.h @@ -56,6 +56,8 @@ #elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_TV_TITLE) #define GTEST_OS_WINDOWS_PHONE 1 #define GTEST_OS_WINDOWS_TV_TITLE 1 +#elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_GAMES) +#define GTEST_OS_WINDOWS_GAMES 1 #else // WINAPI_FAMILY defined but no known partition matched. // Default to desktop. @@ -113,6 +115,10 @@ #define GTEST_OS_XTENSA 1 #elif defined(__hexagon__) #define GTEST_OS_QURT 1 +#elif defined(CPU_QN9090) || defined(CPU_QN9090HN) +#define GTEST_OS_NXP_QN9090 1 +#elif defined(NRF52) +#define GTEST_OS_NRF52 1 #endif // __CYGWIN__ #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_ diff --git a/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/internal/gtest-port.h b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/internal/gtest-port.h index 6db191b7a06..8d27c2c4f72 100644 --- a/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/internal/gtest-port.h +++ b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/internal/gtest-port.h @@ -161,10 +161,10 @@ // NOT define them. // // These macros are public so that portable tests can be written. -// Such tests typically surround code using a feature with an #if +// Such tests typically surround code using a feature with an #ifdef // which controls that code. For example: // -// #if GTEST_HAS_DEATH_TEST +// #ifdef GTEST_HAS_DEATH_TEST // EXPECT_DEATH(DoSomethingDeadly()); // #endif // @@ -178,6 +178,7 @@ // define themselves. // GTEST_USES_SIMPLE_RE - our own simple regex is used; // the above RE\b(s) are mutually exclusive. +// GTEST_HAS_ABSL - Google Test is compiled with Abseil. // Misc public macros // ------------------ @@ -193,8 +194,6 @@ // // Macros for basic C++ coding: // GTEST_AMBIGUOUS_ELSE_BLOCKER_ - for disabling a gcc warning. -// GTEST_ATTRIBUTE_UNUSED_ - declares that a class' instances or a -// variable don't have to be used. // GTEST_MUST_USE_RESULT_ - declares that a function's result must be used. // GTEST_INTENTIONAL_CONST_COND_PUSH_ - start code section where MSVC C4127 is // suppressed (constant conditional). @@ -202,16 +201,26 @@ // is suppressed. // GTEST_INTERNAL_HAS_ANY - for enabling UniversalPrinter or // UniversalPrinter specializations. +// Always defined to 0 or 1. // GTEST_INTERNAL_HAS_OPTIONAL - for enabling UniversalPrinter // or // UniversalPrinter -// specializations. +// specializations. Always defined to 0 or 1. +// GTEST_INTERNAL_HAS_STD_SPAN - for enabling UniversalPrinter +// specializations. Always defined to 0 or 1 // GTEST_INTERNAL_HAS_STRING_VIEW - for enabling Matcher or // Matcher -// specializations. +// specializations. Always defined to 0 or 1. // GTEST_INTERNAL_HAS_VARIANT - for enabling UniversalPrinter or // UniversalPrinter -// specializations. +// specializations. Always defined to 0 or 1. +// GTEST_USE_OWN_FLAGFILE_FLAG_ - Always defined to 0 or 1. +// GTEST_HAS_CXXABI_H_ - Always defined to 0 or 1. +// GTEST_CAN_STREAM_RESULTS_ - Always defined to 0 or 1. +// GTEST_HAS_ALT_PATH_SEP_ - Always defined to 0 or 1. +// GTEST_WIDE_STRING_USES_UTF16_ - Always defined to 0 or 1. +// GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ - Always defined to 0 or 1. +// GTEST_HAS_NOTIFICATION_- Always defined to 0 or 1. // // Synchronization: // Mutex, MutexLock, ThreadLocal, GetThreadCount() @@ -270,6 +279,22 @@ #error C++ versions less than C++14 are not supported. #endif +// MSVC >= 19.11 (VS 2017 Update 3) supports __has_include. +#ifdef __has_include +#define GTEST_INTERNAL_HAS_INCLUDE __has_include +#else +#define GTEST_INTERNAL_HAS_INCLUDE(...) 0 +#endif + +// Detect C++ feature test macros as gracefully as possible. +// MSVC >= 19.15, Clang >= 3.4.1, and GCC >= 4.1.2 support feature test macros. +#if GTEST_INTERNAL_CPLUSPLUS_LANG >= 202002L && \ + (!defined(__has_include) || GTEST_INTERNAL_HAS_INCLUDE()) +#include // C++20 and later +#elif (!defined(__has_include) || GTEST_INTERNAL_HAS_INCLUDE()) +#include // Pre-C++20 +#endif + #include // for isspace, etc #include // for ptrdiff_t #include @@ -303,7 +328,16 @@ #include "gtest/internal/custom/gtest-port.h" #include "gtest/internal/gtest-port-arch.h" -#if GTEST_HAS_ABSL +#ifndef GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ +#define GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ 0 +#endif + +#ifndef GTEST_HAS_NOTIFICATION_ +#define GTEST_HAS_NOTIFICATION_ 0 +#endif + +#if defined(GTEST_HAS_ABSL) && !defined(GTEST_NO_ABSL_FLAGS) +#define GTEST_INTERNAL_HAS_ABSL_FLAGS // Used only in this file. #include "absl/flags/declare.h" #include "absl/flags/flag.h" #include "absl/flags/reflection.h" @@ -361,13 +395,13 @@ // Brings in definitions for functions used in the testing::internal::posix // namespace (read, write, close, chdir, isatty, stat). We do not currently // use them on Windows Mobile. -#if GTEST_OS_WINDOWS -#if !GTEST_OS_WINDOWS_MOBILE +#ifdef GTEST_OS_WINDOWS +#ifndef GTEST_OS_WINDOWS_MOBILE #include #include #endif // In order to avoid having to include , use forward declaration -#if GTEST_OS_WINDOWS_MINGW && !defined(__MINGW64_VERSION_MAJOR) +#if defined(GTEST_OS_WINDOWS_MINGW) && !defined(__MINGW64_VERSION_MAJOR) // MinGW defined _CRITICAL_SECTION and _RTL_CRITICAL_SECTION as two // separate (equivalent) structs, instead of using typedef typedef struct _CRITICAL_SECTION GTEST_CRITICAL_SECTION; @@ -377,7 +411,7 @@ typedef struct _CRITICAL_SECTION GTEST_CRITICAL_SECTION; // WindowsTypesTest.CRITICAL_SECTIONIs_RTL_CRITICAL_SECTION. typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; #endif -#elif GTEST_OS_XTENSA +#elif defined(GTEST_OS_XTENSA) #include // Xtensa toolchains define strcasecmp in the string.h header instead of // strings.h. string.h is already included. @@ -389,7 +423,7 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; #include #endif // GTEST_OS_WINDOWS -#if GTEST_OS_LINUX_ANDROID +#ifdef GTEST_OS_LINUX_ANDROID // Used to define __ANDROID_API__ matching the target NDK API level. #include // NOLINT #endif @@ -397,17 +431,21 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; // Defines this to true if and only if Google Test can use POSIX regular // expressions. #ifndef GTEST_HAS_POSIX_RE -#if GTEST_OS_LINUX_ANDROID +#ifdef GTEST_OS_LINUX_ANDROID // On Android, is only available starting with Gingerbread. #define GTEST_HAS_POSIX_RE (__ANDROID_API__ >= 9) #else -#define GTEST_HAS_POSIX_RE \ - !(GTEST_OS_WINDOWS || GTEST_OS_XTENSA || GTEST_OS_QURT) +#if !(defined(GTEST_OS_WINDOWS) || defined(GTEST_OS_XTENSA) || \ + defined(GTEST_OS_QURT)) +#define GTEST_HAS_POSIX_RE 1 +#else +#define GTEST_HAS_POSIX_RE 0 #endif +#endif // GTEST_OS_LINUX_ANDROID #endif // Select the regular expression implementation. -#if GTEST_HAS_ABSL +#ifdef GTEST_HAS_ABSL // When using Abseil, RE2 is required. #include "absl/strings/string_view.h" #include "re2/re2.h" @@ -443,8 +481,12 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; // cleanups prior to that. To reliably check for C++ exception availability with // clang, check for // __EXCEPTIONS && __has_feature(cxx_exceptions). -#define GTEST_HAS_EXCEPTIONS (__EXCEPTIONS && __has_feature(cxx_exceptions)) -#elif defined(__GNUC__) && __EXCEPTIONS +#if defined(__EXCEPTIONS) && __EXCEPTIONS && __has_feature(cxx_exceptions) +#define GTEST_HAS_EXCEPTIONS 1 +#else +#define GTEST_HAS_EXCEPTIONS 0 +#endif +#elif defined(__GNUC__) && defined(__EXCEPTIONS) && __EXCEPTIONS // gcc defines __EXCEPTIONS to 1 if and only if exceptions are enabled. #define GTEST_HAS_EXCEPTIONS 1 #elif defined(__SUNPRO_CC) @@ -452,7 +494,7 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; // detecting whether they are enabled or not. Therefore, we assume that // they are enabled unless the user tells us otherwise. #define GTEST_HAS_EXCEPTIONS 1 -#elif defined(__IBMCPP__) && __EXCEPTIONS +#elif defined(__IBMCPP__) && defined(__EXCEPTIONS) && __EXCEPTIONS // xlC defines __EXCEPTIONS to 1 if and only if exceptions are enabled. #define GTEST_HAS_EXCEPTIONS 1 #elif defined(__HP_aCC) @@ -472,11 +514,15 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; // Cygwin 1.7 and below doesn't support ::std::wstring. // Solaris' libc++ doesn't support it either. Android has // no support for it at least as recent as Froyo (2.2). -#define GTEST_HAS_STD_WSTRING \ - (!(GTEST_OS_LINUX_ANDROID || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \ - GTEST_OS_HAIKU || GTEST_OS_ESP32 || GTEST_OS_ESP8266 || \ - GTEST_OS_XTENSA || GTEST_OS_QURT)) - +#if (!(defined(GTEST_OS_LINUX_ANDROID) || defined(GTEST_OS_CYGWIN) || \ + defined(GTEST_OS_SOLARIS) || defined(GTEST_OS_HAIKU) || \ + defined(GTEST_OS_ESP32) || defined(GTEST_OS_ESP8266) || \ + defined(GTEST_OS_XTENSA) || defined(GTEST_OS_QURT) || \ + defined(GTEST_OS_NXP_QN9090) || defined(GTEST_OS_NRF52))) +#define GTEST_HAS_STD_WSTRING 1 +#else +#define GTEST_HAS_STD_WSTRING 0 +#endif #endif // GTEST_HAS_STD_WSTRING #ifndef GTEST_HAS_FILE_SYSTEM @@ -506,7 +552,8 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; // -frtti -fno-exceptions, the build fails at link time with undefined // references to __cxa_bad_typeid. Note sure if STL or toolchain bug, // so disable RTTI when detected. -#if GTEST_OS_LINUX_ANDROID && defined(_STLPORT_MAJOR) && !defined(__EXCEPTIONS) +#if defined(GTEST_OS_LINUX_ANDROID) && defined(_STLPORT_MAJOR) && \ + !defined(__EXCEPTIONS) #define GTEST_HAS_RTTI 0 #else #define GTEST_HAS_RTTI 1 @@ -554,11 +601,18 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; // // To disable threading support in Google Test, add -DGTEST_HAS_PTHREAD=0 // to your compiler flags. -#define GTEST_HAS_PTHREAD \ - (GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_HPUX || GTEST_OS_QNX || \ - GTEST_OS_FREEBSD || GTEST_OS_NACL || GTEST_OS_NETBSD || GTEST_OS_FUCHSIA || \ - GTEST_OS_DRAGONFLY || GTEST_OS_GNU_KFREEBSD || GTEST_OS_OPENBSD || \ - GTEST_OS_HAIKU || GTEST_OS_GNU_HURD) +#if (defined(GTEST_OS_LINUX) || defined(GTEST_OS_MAC) || \ + defined(GTEST_OS_HPUX) || defined(GTEST_OS_QNX) || \ + defined(GTEST_OS_FREEBSD) || defined(GTEST_OS_NACL) || \ + defined(GTEST_OS_NETBSD) || defined(GTEST_OS_FUCHSIA) || \ + defined(GTEST_OS_DRAGONFLY) || defined(GTEST_OS_GNU_KFREEBSD) || \ + defined(GTEST_OS_OPENBSD) || defined(GTEST_OS_HAIKU) || \ + defined(GTEST_OS_GNU_HURD) || defined(GTEST_OS_SOLARIS) || \ + defined(GTEST_OS_AIX) || defined(GTEST_OS_ZOS)) +#define GTEST_HAS_PTHREAD 1 +#else +#define GTEST_HAS_PTHREAD 0 +#endif #endif // GTEST_HAS_PTHREAD #if GTEST_HAS_PTHREAD @@ -573,12 +627,12 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; // Determines whether clone(2) is supported. // Usually it will only be available on Linux, excluding // Linux on the Itanium architecture. -// Also see http://linux.die.net/man/2/clone. +// Also see https://linux.die.net/man/2/clone. #ifndef GTEST_HAS_CLONE // The user didn't tell us, so we need to figure it out. -#if GTEST_OS_LINUX && !defined(__ia64__) -#if GTEST_OS_LINUX_ANDROID +#if defined(GTEST_OS_LINUX) && !defined(__ia64__) +#if defined(GTEST_OS_LINUX_ANDROID) // On Android, clone() became available at different API levels for each 32-bit // architecture. #if defined(__LP64__) || (defined(__arm__) && __ANDROID_API__ >= 9) || \ @@ -603,9 +657,10 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; // By default, we assume that stream redirection is supported on all // platforms except known mobile / embedded ones. Also, if the port doesn't have // a file system, stream redirection is not supported. -#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || \ - GTEST_OS_WINDOWS_RT || GTEST_OS_ESP8266 || GTEST_OS_XTENSA || \ - GTEST_OS_QURT || !GTEST_HAS_FILE_SYSTEM +#if defined(GTEST_OS_WINDOWS_MOBILE) || defined(GTEST_OS_WINDOWS_PHONE) || \ + defined(GTEST_OS_WINDOWS_RT) || defined(GTEST_OS_WINDOWS_GAMES) || \ + defined(GTEST_OS_ESP8266) || defined(GTEST_OS_XTENSA) || \ + defined(GTEST_OS_QURT) || !GTEST_HAS_FILE_SYSTEM #define GTEST_HAS_STREAM_REDIRECTION 0 #else #define GTEST_HAS_STREAM_REDIRECTION 1 @@ -614,13 +669,16 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; // Determines whether to support death tests. // pops up a dialog window that cannot be suppressed programmatically. -#if (GTEST_OS_LINUX || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \ - (GTEST_OS_MAC && !GTEST_OS_IOS) || \ - (GTEST_OS_WINDOWS_DESKTOP && _MSC_VER) || GTEST_OS_WINDOWS_MINGW || \ - GTEST_OS_AIX || GTEST_OS_HPUX || GTEST_OS_OPENBSD || GTEST_OS_QNX || \ - GTEST_OS_FREEBSD || GTEST_OS_NETBSD || GTEST_OS_FUCHSIA || \ - GTEST_OS_DRAGONFLY || GTEST_OS_GNU_KFREEBSD || GTEST_OS_HAIKU || \ - GTEST_OS_GNU_HURD) +#if (defined(GTEST_OS_LINUX) || defined(GTEST_OS_CYGWIN) || \ + defined(GTEST_OS_SOLARIS) || defined(GTEST_OS_ZOS) || \ + (defined(GTEST_OS_MAC) && !defined(GTEST_OS_IOS)) || \ + (defined(GTEST_OS_WINDOWS_DESKTOP) && _MSC_VER) || \ + defined(GTEST_OS_WINDOWS_MINGW) || defined(GTEST_OS_AIX) || \ + defined(GTEST_OS_HPUX) || defined(GTEST_OS_OPENBSD) || \ + defined(GTEST_OS_QNX) || defined(GTEST_OS_FREEBSD) || \ + defined(GTEST_OS_NETBSD) || defined(GTEST_OS_FUCHSIA) || \ + defined(GTEST_OS_DRAGONFLY) || defined(GTEST_OS_GNU_KFREEBSD) || \ + defined(GTEST_OS_HAIKU) || defined(GTEST_OS_GNU_HURD)) // Death tests require a file system to work properly. #if GTEST_HAS_FILE_SYSTEM #define GTEST_HAS_DEATH_TEST 1 @@ -638,14 +696,21 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; #endif // Determines whether the system compiler uses UTF-16 for encoding wide strings. -#define GTEST_WIDE_STRING_USES_UTF16_ \ - (GTEST_OS_WINDOWS || GTEST_OS_CYGWIN || GTEST_OS_AIX || GTEST_OS_OS2) +#if defined(GTEST_OS_WINDOWS) || defined(GTEST_OS_CYGWIN) || \ + defined(GTEST_OS_AIX) || defined(GTEST_OS_OS2) +#define GTEST_WIDE_STRING_USES_UTF16_ 1 +#else +#define GTEST_WIDE_STRING_USES_UTF16_ 0 +#endif // Determines whether test results can be streamed to a socket. -#if GTEST_OS_LINUX || GTEST_OS_GNU_KFREEBSD || GTEST_OS_DRAGONFLY || \ - GTEST_OS_FREEBSD || GTEST_OS_NETBSD || GTEST_OS_OPENBSD || \ - GTEST_OS_GNU_HURD +#if defined(GTEST_OS_LINUX) || defined(GTEST_OS_GNU_KFREEBSD) || \ + defined(GTEST_OS_DRAGONFLY) || defined(GTEST_OS_FREEBSD) || \ + defined(GTEST_OS_NETBSD) || defined(GTEST_OS_OPENBSD) || \ + defined(GTEST_OS_GNU_HURD) || defined(GTEST_OS_MAC) #define GTEST_CAN_STREAM_RESULTS_ 1 +#else +#define GTEST_CAN_STREAM_RESULTS_ 0 #endif // Defines some utility macros. @@ -683,6 +748,20 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; #define GTEST_HAVE_ATTRIBUTE_(x) 0 #endif +// GTEST_INTERNAL_HAVE_CPP_ATTRIBUTE +// +// A function-like feature checking macro that accepts C++11 style attributes. +// It's a wrapper around `__has_cpp_attribute`, defined by ISO C++ SD-6 +// (https://en.cppreference.com/w/cpp/experimental/feature_test). If we don't +// find `__has_cpp_attribute`, will evaluate to 0. +#if defined(__has_cpp_attribute) +// NOTE: requiring __cplusplus above should not be necessary, but +// works around https://bugs.llvm.org/show_bug.cgi?id=23435. +#define GTEST_INTERNAL_HAVE_CPP_ATTRIBUTE(x) __has_cpp_attribute(x) +#else +#define GTEST_INTERNAL_HAVE_CPP_ATTRIBUTE(x) 0 +#endif + // GTEST_HAVE_FEATURE_ // // A function-like feature checking macro that is a wrapper around @@ -694,14 +773,22 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; #endif // Use this annotation after a variable or parameter declaration to tell the -// compiler the variable/parameter does not have to be used. +// compiler the variable/parameter may be used. // Example: // -// GTEST_ATTRIBUTE_UNUSED_ int foo = bar(); -#if GTEST_HAVE_ATTRIBUTE_(unused) -#define GTEST_ATTRIBUTE_UNUSED_ __attribute__((unused)) +// GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED int foo = bar(); +// +// This can be removed once we only support only C++17 or newer and +// [[maybe_unused]] is available on all supported platforms. +#if GTEST_INTERNAL_HAVE_CPP_ATTRIBUTE(maybe_unused) +#define GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED [[maybe_unused]] +#elif GTEST_HAVE_ATTRIBUTE_(unused) +// This is inferior to [[maybe_unused]] as it can produce a +// -Wused-but-marked-unused warning on optionally used symbols, but it is all we +// have. +#define GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED __attribute__((__unused__)) #else -#define GTEST_ATTRIBUTE_UNUSED_ +#define GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED #endif // Use this annotation before a function that takes a printf format string. @@ -712,7 +799,7 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; #define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check) \ __attribute__((format(__MINGW_PRINTF_FORMAT, string_index, first_to_check))) #elif GTEST_HAVE_ATTRIBUTE_(format) -#define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check) \ +#define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check) \ __attribute__((format(printf, string_index, first_to_check))) #else #define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check) @@ -759,14 +846,16 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; #ifndef GTEST_IS_THREADSAFE -#define GTEST_IS_THREADSAFE \ - (GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ || \ - (GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT) || \ - GTEST_HAS_PTHREAD) +#if (GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ || \ + (defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_PHONE) && \ + !defined(GTEST_OS_WINDOWS_RT)) || \ + GTEST_HAS_PTHREAD) +#define GTEST_IS_THREADSAFE 1 +#endif #endif // GTEST_IS_THREADSAFE -#if GTEST_IS_THREADSAFE +#ifdef GTEST_IS_THREADSAFE // Some platforms don't support including these threading related headers. #include // NOLINT #include // NOLINT @@ -778,9 +867,9 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; #ifndef GTEST_API_ #ifdef _MSC_VER -#if GTEST_LINKED_AS_SHARED_LIBRARY +#if defined(GTEST_LINKED_AS_SHARED_LIBRARY) && GTEST_LINKED_AS_SHARED_LIBRARY #define GTEST_API_ __declspec(dllimport) -#elif GTEST_CREATE_SHARED_LIBRARY +#elif defined(GTEST_CREATE_SHARED_LIBRARY) && GTEST_CREATE_SHARED_LIBRARY #define GTEST_API_ __declspec(dllexport) #endif #elif GTEST_HAVE_ATTRIBUTE_(visibility) @@ -808,7 +897,7 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; // Ask the compiler not to perform tail call optimization inside // the marked function. #define GTEST_NO_TAIL_CALL_ __attribute__((disable_tail_calls)) -#elif __GNUC__ +#elif defined(__GNUC__) && !defined(__NVCOMPILER) #define GTEST_NO_TAIL_CALL_ \ __attribute__((optimize("no-optimize-sibling-calls"))) #else @@ -871,9 +960,11 @@ using std::tuple_size; namespace internal { // A secret type that Google Test users don't know about. It has no -// definition on purpose. Therefore it's impossible to create a +// accessible constructors on purpose. Therefore it's impossible to create a // Secret object, which is what we want. -class Secret; +class Secret { + Secret(const Secret&) = delete; +}; // A helper for suppressing warnings on constant condition. It just // returns 'condition'. @@ -881,7 +972,7 @@ GTEST_API_ bool IsTrue(bool condition); // Defines RE. -#if GTEST_USES_RE2 +#ifdef GTEST_USES_RE2 // This is almost `using RE = ::RE2`, except it is copy-constructible, and it // needs to disambiguate the `std::string`, `absl::string_view`, and `const @@ -906,7 +997,9 @@ class GTEST_API_ RE { RE2 regex_; }; -#elif GTEST_USES_POSIX_RE || GTEST_USES_SIMPLE_RE +#elif defined(GTEST_USES_POSIX_RE) || defined(GTEST_USES_SIMPLE_RE) +GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \ +/* class A needs to have dll-interface to be used by clients of class B */) // A simple C++ wrapper for . It uses the POSIX Extended // Regular Expression syntax. @@ -923,7 +1016,7 @@ class GTEST_API_ RE { ~RE(); // Returns the string representation of the regex. - const char* pattern() const { return pattern_; } + const char* pattern() const { return pattern_.c_str(); } // FullMatch(str, re) returns true if and only if regular expression re // matches the entire str. @@ -941,21 +1034,21 @@ class GTEST_API_ RE { private: void Init(const char* regex); - const char* pattern_; + std::string pattern_; bool is_valid_; -#if GTEST_USES_POSIX_RE +#ifdef GTEST_USES_POSIX_RE regex_t full_regex_; // For FullMatch(). regex_t partial_regex_; // For PartialMatch(). #else // GTEST_USES_SIMPLE_RE - const char* full_pattern_; // For FullMatch(); + std::string full_pattern_; // For FullMatch(); #endif }; - +GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 #endif // ::testing::internal::RE implementation // Formats a source file path and a line number as they would appear @@ -1088,47 +1181,6 @@ inline To ImplicitCast_(To x) { return x; } -// When you upcast (that is, cast a pointer from type Foo to type -// SuperclassOfFoo), it's fine to use ImplicitCast_<>, since upcasts -// always succeed. When you downcast (that is, cast a pointer from -// type Foo to type SubclassOfFoo), static_cast<> isn't safe, because -// how do you know the pointer is really of type SubclassOfFoo? It -// could be a bare Foo, or of type DifferentSubclassOfFoo. Thus, -// when you downcast, you should use this macro. In debug mode, we -// use dynamic_cast<> to double-check the downcast is legal (we die -// if it's not). In normal mode, we do the efficient static_cast<> -// instead. Thus, it's important to test in debug mode to make sure -// the cast is legal! -// This is the only place in the code we should use dynamic_cast<>. -// In particular, you SHOULDN'T be using dynamic_cast<> in order to -// do RTTI (eg code like this: -// if (dynamic_cast(foo)) HandleASubclass1Object(foo); -// if (dynamic_cast(foo)) HandleASubclass2Object(foo); -// You should design the code some other way not to need this. -// -// This relatively ugly name is intentional. It prevents clashes with -// similar functions users may have (e.g., down_cast). The internal -// namespace alone is not enough because the function can be found by ADL. -template // use like this: DownCast_(foo); -inline To DownCast_(From* f) { // so we only accept pointers - // Ensures that To is a sub-type of From *. This test is here only - // for compile-time type checking, and has no overhead in an - // optimized build at run-time, as it will be optimized away - // completely. - GTEST_INTENTIONAL_CONST_COND_PUSH_() - if (false) { - GTEST_INTENTIONAL_CONST_COND_POP_() - const To to = nullptr; - ::testing::internal::ImplicitCast_(to); - } - -#if GTEST_HAS_RTTI - // RTTI: debug mode only! - GTEST_CHECK_(f == nullptr || dynamic_cast(f) != nullptr); -#endif - return static_cast(f); -} - // Downcasts the pointer of type Base to Derived. // Derived must be a subclass of Base. The parameter MUST // point to a class of type Derived, not any subclass of it. @@ -1136,17 +1188,12 @@ inline To DownCast_(From* f) { // so we only accept pointers // check to enforce this. template Derived* CheckedDowncastToActualType(Base* base) { + static_assert(std::is_base_of::value, + "target type not derived from source type"); #if GTEST_HAS_RTTI - GTEST_CHECK_(typeid(*base) == typeid(Derived)); -#endif - -#if GTEST_HAS_DOWNCAST_ - return ::down_cast(base); -#elif GTEST_HAS_RTTI - return dynamic_cast(base); // NOLINT -#else - return static_cast(base); // Poor man's downcast. + GTEST_CHECK_(base == nullptr || dynamic_cast(base) != nullptr); #endif + return static_cast(base); } #if GTEST_HAS_STREAM_REDIRECTION @@ -1172,7 +1219,7 @@ GTEST_API_ std::string ReadEntireFile(FILE* file); // All command line arguments. GTEST_API_ std::vector GetArgvs(); -#if GTEST_HAS_DEATH_TEST +#ifdef GTEST_HAS_DEATH_TEST std::vector GetInjectableArgvs(); // Deprecated: pass the args vector by value instead. @@ -1183,9 +1230,9 @@ void ClearInjectableArgvs(); #endif // GTEST_HAS_DEATH_TEST // Defines synchronization primitives. -#if GTEST_IS_THREADSAFE +#ifdef GTEST_IS_THREADSAFE -#if GTEST_OS_WINDOWS +#ifdef GTEST_OS_WINDOWS // Provides leak-safe Windows kernel handle ownership. // Used in death tests and in threading support. class GTEST_API_ AutoHandle { @@ -1264,7 +1311,7 @@ GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 // On MinGW, we can have both GTEST_OS_WINDOWS and GTEST_HAS_PTHREAD // defined, but we don't want to use MinGW's pthreads implementation, which // has conformance problems with some versions of the POSIX standard. -#if GTEST_HAS_PTHREAD && !GTEST_OS_WINDOWS_MINGW +#if GTEST_HAS_PTHREAD && !defined(GTEST_OS_WINDOWS_MINGW) // As a C-function, ThreadFuncWithCLinkage cannot be templated itself. // Consequently, it cannot select a correct instantiation of ThreadWithParam @@ -1273,7 +1320,7 @@ GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 // problem. class ThreadWithParamBase { public: - virtual ~ThreadWithParamBase() {} + virtual ~ThreadWithParamBase() = default; virtual void Run() = 0; }; @@ -1350,7 +1397,8 @@ class ThreadWithParam : public ThreadWithParamBase { // Mutex and ThreadLocal have already been imported into the namespace. // Nothing to do here. -#elif GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT +#elif defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_PHONE) && \ + !defined(GTEST_OS_WINDOWS_RT) // Mutex implements mutex on Windows platforms. It is used in conjunction // with class MutexLock: @@ -1734,7 +1782,7 @@ typedef GTestMutexLock MutexLock; // ThreadLocalValueHolderBase. class GTEST_API_ ThreadLocalValueHolderBase { public: - virtual ~ThreadLocalValueHolderBase() {} + virtual ~ThreadLocalValueHolderBase() = default; }; // Called by pthread to delete thread-local data stored by @@ -1806,8 +1854,8 @@ class GTEST_API_ ThreadLocal { class ValueHolderFactory { public: - ValueHolderFactory() {} - virtual ~ValueHolderFactory() {} + ValueHolderFactory() = default; + virtual ~ValueHolderFactory() = default; virtual ValueHolder* MakeNewHolder() const = 0; private: @@ -1817,7 +1865,7 @@ class GTEST_API_ ThreadLocal { class DefaultValueHolderFactory : public ValueHolderFactory { public: - DefaultValueHolderFactory() {} + DefaultValueHolderFactory() = default; ValueHolder* MakeNewHolder() const override { return new ValueHolder(); } private: @@ -1903,7 +1951,7 @@ class GTEST_API_ ThreadLocal { // we cannot detect it. GTEST_API_ size_t GetThreadCount(); -#if GTEST_OS_WINDOWS +#ifdef GTEST_OS_WINDOWS #define GTEST_PATH_SEP_ "\\" #define GTEST_HAS_ALT_PATH_SEP_ 1 #else @@ -1939,7 +1987,7 @@ inline bool IsUpper(char ch) { inline bool IsXDigit(char ch) { return isxdigit(static_cast(ch)) != 0; } -#ifdef __cpp_char8_t +#ifdef __cpp_lib_char8_t inline bool IsXDigit(char8_t ch) { return isxdigit(static_cast(ch)) != 0; } @@ -1979,63 +2027,70 @@ inline std::string StripTrailingSpaces(std::string str) { namespace posix { // File system porting. -#if GTEST_HAS_FILE_SYSTEM -#if GTEST_OS_WINDOWS +// Note: Not every I/O-related function is related to file systems, so don't +// just disable all of them here. For example, fileno() and isatty(), etc. must +// always be available in order to detect if a pipe points to a terminal. +#ifdef GTEST_OS_WINDOWS typedef struct _stat StatStruct; -#if GTEST_OS_WINDOWS_MOBILE +#ifdef GTEST_OS_WINDOWS_MOBILE inline int FileNo(FILE* file) { return reinterpret_cast(_fileno(file)); } // Stat(), RmDir(), and IsDir() are not needed on Windows CE at this // time and thus not defined there. #else inline int FileNo(FILE* file) { return _fileno(file); } +#if GTEST_HAS_FILE_SYSTEM inline int Stat(const char* path, StatStruct* buf) { return _stat(path, buf); } inline int RmDir(const char* dir) { return _rmdir(dir); } inline bool IsDir(const StatStruct& st) { return (_S_IFDIR & st.st_mode) != 0; } +#endif #endif // GTEST_OS_WINDOWS_MOBILE -#elif GTEST_OS_ESP8266 +#elif defined(GTEST_OS_ESP8266) typedef struct stat StatStruct; inline int FileNo(FILE* file) { return fileno(file); } +#if GTEST_HAS_FILE_SYSTEM inline int Stat(const char* path, StatStruct* buf) { // stat function not implemented on ESP8266 return 0; } inline int RmDir(const char* dir) { return rmdir(dir); } inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); } +#endif #else typedef struct stat StatStruct; inline int FileNo(FILE* file) { return fileno(file); } +#if GTEST_HAS_FILE_SYSTEM inline int Stat(const char* path, StatStruct* buf) { return stat(path, buf); } -#if GTEST_OS_QURT +#ifdef GTEST_OS_QURT // QuRT doesn't support any directory functions, including rmdir inline int RmDir(const char*) { return 0; } #else inline int RmDir(const char* dir) { return rmdir(dir); } #endif inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); } +#endif #endif // GTEST_OS_WINDOWS -#endif // GTEST_HAS_FILE_SYSTEM // Other functions with a different name on Windows. -#if GTEST_OS_WINDOWS +#ifdef GTEST_OS_WINDOWS #ifdef __BORLANDC__ inline int DoIsATTY(int fd) { return isatty(fd); } inline int StrCaseCmp(const char* s1, const char* s2) { return stricmp(s1, s2); } -inline char* StrDup(const char* src) { return strdup(src); } #else // !__BORLANDC__ -#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_ZOS || GTEST_OS_IOS || \ - GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT || defined(ESP_PLATFORM) +#if defined(GTEST_OS_WINDOWS_MOBILE) || defined(GTEST_OS_ZOS) || \ + defined(GTEST_OS_IOS) || defined(GTEST_OS_WINDOWS_PHONE) || \ + defined(GTEST_OS_WINDOWS_RT) || defined(ESP_PLATFORM) inline int DoIsATTY(int /* fd */) { return 0; } #else inline int DoIsATTY(int fd) { return _isatty(fd); } @@ -2043,24 +2098,14 @@ inline int DoIsATTY(int fd) { return _isatty(fd); } inline int StrCaseCmp(const char* s1, const char* s2) { return _stricmp(s1, s2); } -inline char* StrDup(const char* src) { return _strdup(src); } #endif // __BORLANDC__ -#elif GTEST_OS_ESP8266 - -inline int DoIsATTY(int fd) { return isatty(fd); } -inline int StrCaseCmp(const char* s1, const char* s2) { - return strcasecmp(s1, s2); -} -inline char* StrDup(const char* src) { return strdup(src); } - #else inline int DoIsATTY(int fd) { return isatty(fd); } inline int StrCaseCmp(const char* s1, const char* s2) { return strcasecmp(s1, s2); } -inline char* StrDup(const char* src) { return strdup(src); } #endif // GTEST_OS_WINDOWS @@ -2083,13 +2128,14 @@ GTEST_DISABLE_MSC_DEPRECATED_PUSH_() // StrError() aren't needed on Windows CE at this time and thus not // defined there. #if GTEST_HAS_FILE_SYSTEM -#if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && \ - !GTEST_OS_WINDOWS_RT && !GTEST_OS_ESP8266 && !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_WINDOWS_GAMES) && \ + !defined(GTEST_OS_ESP8266) && !defined(GTEST_OS_XTENSA) && \ + !defined(GTEST_OS_QURT) inline int ChDir(const char* dir) { return chdir(dir); } #endif inline FILE* FOpen(const char* path, const char* mode) { -#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW +#if defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_MINGW) struct wchar_codecvt : public std::codecvt {}; std::wstring_convert converter; std::wstring wide_path = converter.from_bytes(path); @@ -2099,14 +2145,14 @@ inline FILE* FOpen(const char* path, const char* mode) { return fopen(path, mode); #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW } -#if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_QURT +#if !defined(GTEST_OS_WINDOWS_MOBILE) && !defined(GTEST_OS_QURT) inline FILE* FReopen(const char* path, const char* mode, FILE* stream) { return freopen(path, mode, stream); } inline FILE* FDOpen(int fd, const char* mode) { return fdopen(fd, mode); } #endif // !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_QURT inline int FClose(FILE* fp) { return fclose(fp); } -#if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_QURT +#if !defined(GTEST_OS_WINDOWS_MOBILE) && !defined(GTEST_OS_QURT) inline int Read(int fd, void* buf, unsigned int count) { return static_cast(read(fd, buf, count)); } @@ -2117,14 +2163,14 @@ inline int Close(int fd) { return close(fd); } #endif // !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_QURT #endif // GTEST_HAS_FILE_SYSTEM -#if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_QURT +#if !defined(GTEST_OS_WINDOWS_MOBILE) && !defined(GTEST_OS_QURT) inline const char* StrError(int errnum) { return strerror(errnum); } #endif // !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_QURT inline const char* GetEnv(const char* name) { -#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || \ - GTEST_OS_WINDOWS_RT || GTEST_OS_ESP8266 || GTEST_OS_XTENSA || \ - GTEST_OS_QURT +#if defined(GTEST_OS_WINDOWS_MOBILE) || defined(GTEST_OS_WINDOWS_PHONE) || \ + defined(GTEST_OS_ESP8266) || defined(GTEST_OS_XTENSA) || \ + defined(GTEST_OS_QURT) // We are on an embedded platform, which has no environment variables. static_cast(name); // To prevent 'unused argument' warning. return nullptr; @@ -2140,7 +2186,7 @@ inline const char* GetEnv(const char* name) { GTEST_DISABLE_MSC_DEPRECATED_POP_() -#if GTEST_OS_WINDOWS_MOBILE +#ifdef GTEST_OS_WINDOWS_MOBILE // Windows CE has no C library. The abort() function is used in // several places in Google Test. This implementation provides a reasonable // imitation of standard behaviour. @@ -2156,7 +2202,7 @@ GTEST_DISABLE_MSC_DEPRECATED_POP_() // MSVC-based platforms. We map the GTEST_SNPRINTF_ macro to the appropriate // function in order to achieve that. We use macro definition here because // snprintf is a variadic function. -#if defined(_MSC_VER) && !GTEST_OS_WINDOWS_MOBILE +#if defined(_MSC_VER) && !defined(GTEST_OS_WINDOWS_MOBILE) // MSVC 2005 and above support variadic macros. #define GTEST_SNPRINTF_(buffer, size, format, ...) \ _snprintf_s(buffer, size, size, format, __VA_ARGS__) @@ -2229,7 +2275,7 @@ using TimeInMillis = int64_t; // Represents time in milliseconds. #endif // !defined(GTEST_FLAG) // Pick a command line flags implementation. -#if GTEST_HAS_ABSL +#ifdef GTEST_INTERNAL_HAS_ABSL_FLAGS // Macros for defining flags. #define GTEST_DEFINE_bool_(name, default_val, doc) \ @@ -2254,7 +2300,8 @@ using TimeInMillis = int64_t; // Represents time in milliseconds. (void)(::absl::SetFlag(>EST_FLAG(name), value)) #define GTEST_USE_OWN_FLAGFILE_FLAG_ 0 -#else // GTEST_HAS_ABSL +#undef GTEST_INTERNAL_HAS_ABSL_FLAGS +#else // ndef GTEST_INTERNAL_HAS_ABSL_FLAGS // Macros for defining flags. #define GTEST_DEFINE_bool_(name, default_val, doc) \ @@ -2296,7 +2343,7 @@ using TimeInMillis = int64_t; // Represents time in milliseconds. #define GTEST_FLAG_SET(name, value) (void)(::testing::GTEST_FLAG(name) = value) #define GTEST_USE_OWN_FLAGFILE_FLAG_ 1 -#endif // GTEST_HAS_ABSL +#endif // GTEST_INTERNAL_HAS_ABSL_FLAGS // Thread annotations #if !defined(GTEST_EXCLUSIVE_LOCK_REQUIRED_) @@ -2340,7 +2387,7 @@ const char* StringFromGTestEnv(const char* flag, const char* default_val); #endif // !defined(GTEST_INTERNAL_DEPRECATED) -#if GTEST_HAS_ABSL +#ifdef GTEST_HAS_ABSL // Always use absl::any for UniversalPrinter<> specializations if googletest // is built with absl support. #define GTEST_INTERNAL_HAS_ANY 1 @@ -2351,8 +2398,9 @@ using Any = ::absl::any; } // namespace internal } // namespace testing #else -#ifdef __has_include -#if __has_include() && __cplusplus >= 201703L +#if defined(__cpp_lib_any) || (GTEST_INTERNAL_HAS_INCLUDE() && \ + GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L && \ + (!defined(_MSC_VER) || GTEST_HAS_RTTI)) // Otherwise for C++17 and higher use std::any for UniversalPrinter<> // specializations. #define GTEST_INTERNAL_HAS_ANY 1 @@ -2364,11 +2412,14 @@ using Any = ::std::any; } // namespace testing // The case where absl is configured NOT to alias std::any is not // supported. -#endif // __has_include() && __cplusplus >= 201703L -#endif // __has_include +#endif // __cpp_lib_any #endif // GTEST_HAS_ABSL -#if GTEST_HAS_ABSL +#ifndef GTEST_INTERNAL_HAS_ANY +#define GTEST_INTERNAL_HAS_ANY 0 +#endif + +#ifdef GTEST_HAS_ABSL // Always use absl::optional for UniversalPrinter<> specializations if // googletest is built with absl support. #define GTEST_INTERNAL_HAS_OPTIONAL 1 @@ -2381,8 +2432,8 @@ inline ::absl::nullopt_t Nullopt() { return ::absl::nullopt; } } // namespace internal } // namespace testing #else -#ifdef __has_include -#if __has_include() && __cplusplus >= 201703L +#if defined(__cpp_lib_optional) || (GTEST_INTERNAL_HAS_INCLUDE() && \ + GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L) // Otherwise for C++17 and higher use std::optional for UniversalPrinter<> // specializations. #define GTEST_INTERNAL_HAS_OPTIONAL 1 @@ -2396,11 +2447,23 @@ inline ::std::nullopt_t Nullopt() { return ::std::nullopt; } } // namespace testing // The case where absl is configured NOT to alias std::optional is not // supported. -#endif // __has_include() && __cplusplus >= 201703L -#endif // __has_include +#endif // __cpp_lib_optional #endif // GTEST_HAS_ABSL -#if GTEST_HAS_ABSL +#ifndef GTEST_INTERNAL_HAS_OPTIONAL +#define GTEST_INTERNAL_HAS_OPTIONAL 0 +#endif + +#if defined(__cpp_lib_span) || (GTEST_INTERNAL_HAS_INCLUDE() && \ + GTEST_INTERNAL_CPLUSPLUS_LANG >= 202002L) +#define GTEST_INTERNAL_HAS_STD_SPAN 1 +#endif // __cpp_lib_span + +#ifndef GTEST_INTERNAL_HAS_STD_SPAN +#define GTEST_INTERNAL_HAS_STD_SPAN 0 +#endif + +#ifdef GTEST_HAS_ABSL // Always use absl::string_view for Matcher<> specializations if googletest // is built with absl support. #define GTEST_INTERNAL_HAS_STRING_VIEW 1 @@ -2411,8 +2474,9 @@ using StringView = ::absl::string_view; } // namespace internal } // namespace testing #else -#ifdef __has_include -#if __has_include() && __cplusplus >= 201703L +#if defined(__cpp_lib_string_view) || \ + (GTEST_INTERNAL_HAS_INCLUDE() && \ + GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L) // Otherwise for C++17 and higher use std::string_view for Matcher<> // specializations. #define GTEST_INTERNAL_HAS_STRING_VIEW 1 @@ -2424,11 +2488,14 @@ using StringView = ::std::string_view; } // namespace testing // The case where absl is configured NOT to alias std::string_view is not // supported. -#endif // __has_include() && __cplusplus >= 201703L -#endif // __has_include +#endif // __cpp_lib_string_view #endif // GTEST_HAS_ABSL -#if GTEST_HAS_ABSL +#ifndef GTEST_INTERNAL_HAS_STRING_VIEW +#define GTEST_INTERNAL_HAS_STRING_VIEW 0 +#endif + +#ifdef GTEST_HAS_ABSL // Always use absl::variant for UniversalPrinter<> specializations if googletest // is built with absl support. #define GTEST_INTERNAL_HAS_VARIANT 1 @@ -2440,8 +2507,8 @@ using Variant = ::absl::variant; } // namespace internal } // namespace testing #else -#ifdef __has_include -#if __has_include() && __cplusplus >= 201703L +#if defined(__cpp_lib_variant) || (GTEST_INTERNAL_HAS_INCLUDE() && \ + GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L) // Otherwise for C++17 and higher use std::variant for UniversalPrinter<> // specializations. #define GTEST_INTERNAL_HAS_VARIANT 1 @@ -2453,8 +2520,17 @@ using Variant = ::std::variant; } // namespace internal } // namespace testing // The case where absl is configured NOT to alias std::variant is not supported. -#endif // __has_include() && __cplusplus >= 201703L -#endif // __has_include +#endif // __cpp_lib_variant #endif // GTEST_HAS_ABSL +#ifndef GTEST_INTERNAL_HAS_VARIANT +#define GTEST_INTERNAL_HAS_VARIANT 0 +#endif + +#if (defined(__cpp_constexpr) && !defined(__cpp_inline_variables)) || \ + (defined(GTEST_INTERNAL_CPLUSPLUS_LANG) && \ + GTEST_INTERNAL_CPLUSPLUS_LANG < 201703L) +#define GTEST_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL 1 +#endif + #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_ diff --git a/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/internal/gtest-string.h b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/internal/gtest-string.h index cc0dd7529c1..7c05b58339f 100644 --- a/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/internal/gtest-string.h +++ b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/internal/gtest-string.h @@ -73,7 +73,7 @@ class GTEST_API_ String { // memory using malloc(). static const char* CloneCString(const char* c_str); -#if GTEST_OS_WINDOWS_MOBILE +#ifdef GTEST_OS_WINDOWS_MOBILE // Windows CE does not have the 'ANSI' versions of Win32 APIs. To be // able to pass strings to Win32 APIs on CE we need to convert them // to 'Unicode', UTF-16. diff --git a/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/internal/gtest-type-util.h b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/internal/gtest-type-util.h index 17a470b6265..78da05316d6 100644 --- a/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/internal/gtest-type-util.h +++ b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/include/gtest/internal/gtest-type-util.h @@ -67,6 +67,22 @@ inline std::string CanonicalizeForStdLibVersioning(std::string s) { s.erase(strlen("std"), end - strlen("std")); } } + + // Strip redundant spaces in typename to match MSVC + // For example, std::pair -> std::pair + static const char to_search[] = ", "; + const char replace_char = ','; + size_t pos = 0; + while (true) { + // Get the next occurrence from the current position + pos = s.find(to_search, pos); + if (pos == std::string::npos) { + break; + } + // Replace this occurrence of substring + s.replace(pos, strlen(to_search), 1, replace_char); + ++pos; + } return s; } @@ -85,6 +101,20 @@ inline std::string GetTypeName(const std::type_info& type) { const std::string name_str(status == 0 ? readable_name : name); free(readable_name); return CanonicalizeForStdLibVersioning(name_str); +#elif defined(_MSC_VER) + // Strip struct and class due to differences between + // MSVC and other compilers. std::pair is printed as + // "struct std::pair" when using MSVC vs "std::pair" with + // other compilers. + std::string s = name; + // Only strip the leading "struct " and "class ", so uses rfind == 0 to + // ensure that + if (s.rfind("struct ", 0) == 0) { + s = s.substr(strlen("struct ")); + } else if (s.rfind("class ", 0) == 0) { + s = s.substr(strlen("class ")); + } + return s; #else return name; #endif // GTEST_HAS_CXXABI_H_ || __HP_aCC diff --git a/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/src/gtest-assertion-result.cc b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/src/gtest-assertion-result.cc index f1c0b10dc9e..39989216741 100644 --- a/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/src/gtest-assertion-result.cc +++ b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/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/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/src/gtest-death-test.cc b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/src/gtest-death-test.cc index b6968a9c949..15472f1a792 100644 --- a/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/src/gtest-death-test.cc +++ b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/src/gtest-death-test.cc @@ -32,15 +32,21 @@ #include "gtest/gtest-death-test.h" +#include + #include +#include +#include +#include #include +#include #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 #endif // GTEST_OS_MAC @@ -48,24 +54,24 @@ #include #include -#if GTEST_OS_LINUX +#ifdef GTEST_OS_LINUX #include #endif // GTEST_OS_LINUX #include -#if GTEST_OS_WINDOWS +#ifdef GTEST_OS_WINDOWS #include #else #include #include #endif // GTEST_OS_WINDOWS -#if GTEST_OS_QNX +#ifdef GTEST_OS_QNX #include #endif // GTEST_OS_QNX -#if GTEST_OS_FUCHSIA +#ifdef GTEST_OS_FUCHSIA #include #include #include @@ -111,7 +117,7 @@ GTEST_DEFINE_string_( GTEST_DEFINE_bool_( death_test_use_fork, testing::internal::BoolFromGTestEnv("death_test_use_fork", false), - "Instructs to use fork()/_exit() instead of clone() in death tests. " + "Instructs to use fork()/_Exit() instead of clone() in death tests. " "Ignored and always uses fork() on POSIX systems where clone() is not " "implemented. Useful when running under valgrind or similar tools if " "those do not support clone(). Valgrind 3.3.1 will just fail if " @@ -131,13 +137,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 +153,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 +175,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 +186,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 +213,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 +240,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 +269,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; @@ -295,7 +301,7 @@ enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW }; fputc(kDeathTestInternalError, parent); fprintf(parent, "%s", message.c_str()); fflush(parent); - _exit(1); + _Exit(1); } else { fprintf(stderr, "%s", message.c_str()); fflush(stderr); @@ -507,7 +513,7 @@ std::string DeathTestImpl::GetErrorLogs() { return GetCapturedStderr(); } // Signals that the death test code which should have exited, didn't. // Should be called only in a death test child process. // Writes a status byte to the child's status file descriptor, then -// calls _exit(1). +// calls _Exit(1). void DeathTestImpl::Abort(AbortReason reason) { // The parent process considers the death test to be a failure if // it finds any data in our pipe. So, here we write a single flag byte @@ -519,13 +525,13 @@ void DeathTestImpl::Abort(AbortReason reason) { GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1)); // We are leaking the descriptor here because on some platforms (i.e., // when built as Windows DLL), destructors of global objects will still - // run after calling _exit(). On such systems, write_fd_ will be + // run after calling _Exit(). On such systems, write_fd_ will be // indirectly closed from the destructor of UnitTestImpl, causing double // close if it is also closed here. On debug configurations, double close // may assert. As there are no in-process buffers to flush here, we are // relying on the OS to close the descriptor after the process terminates // when the destructors are not run. - _exit(1); // Exits w/o any normal exit hooks (we were supposed to crash) + _Exit(1); // Exits w/o any normal exit hooks (we were supposed to crash) } // Returns an indented copy of stderr output for a death test. @@ -621,7 +627,21 @@ bool DeathTestImpl::Passed(bool status_ok) { return success; } -#if GTEST_OS_WINDOWS +#ifndef GTEST_OS_WINDOWS +// Note: The return value points into args, so the return value's lifetime is +// bound to that of args. +static std::vector CreateArgvFromArgs(std::vector& args) { + std::vector result; + result.reserve(args.size() + 1); + for (auto& arg : args) { + result.push_back(&arg[0]); + } + result.push_back(nullptr); // Extra null terminator. + return result; +} +#endif + +#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 @@ -765,7 +785,7 @@ DeathTest::TestRole WindowsDeathTest::AssumeRole() { StreamableToString(static_cast(::GetCurrentProcessId())) + // size_t has the same width as pointers on both 32-bit and 64-bit // Windows platforms. - // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx. + // See https://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx. "|" + StreamableToString(reinterpret_cast(write_handle)) + "|" + StreamableToString(reinterpret_cast(event_handle_.Get())); @@ -808,7 +828,7 @@ DeathTest::TestRole WindowsDeathTest::AssumeRole() { return OVERSEE_TEST; } -#elif GTEST_OS_FUCHSIA +#elif defined(GTEST_OS_FUCHSIA) class FuchsiaDeathTest : public DeathTestImpl { public: @@ -836,36 +856,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::iterator i = args_.begin(); i != args_.end(); - ++i) { - free(*i); - } - } - void AddArgument(const char* argument) { - args_.insert(args_.end() - 1, posix::StrDup(argument)); - } - - template - void AddArguments(const ::std::vector& arguments) { - for (typename ::std::vector::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(args_.size()) - 1; } - - private: - std::vector 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 +976,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 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 +1031,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::vector argv = CreateArgvFromArgs(args); + status = fdio_spawn_etc(child_job, FDIO_SPAWN_CLONE_ALL, argv[0], argv.data(), + nullptr, 2, spawn_actions, child_process_.reset_and_get_address(), nullptr); GTEST_DEATH_TEST_CHECK_(status == ZX_OK); @@ -1134,7 +1130,7 @@ DeathTest::TestRole NoExecDeathTest::AssumeRole() { LogToStderr(); // Event forwarding to the listeners of event listener API mush be shut // down in death test subprocesses. - GetUnitTestImpl()->listeners()->SuppressEventForwarding(); + GetUnitTestImpl()->listeners()->SuppressEventForwarding(true); g_in_fast_death_test_child = true; return EXECUTE_TEST; } else { @@ -1173,34 +1169,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::iterator i = args_.begin(); i != args_.end(); - ++i) { - free(*i); - } - } - void AddArgument(const char* argument) { - args_.insert(args_.end() - 1, posix::StrDup(argument)); - } - - template - void AddArguments(const ::std::vector& arguments) { - for (typename ::std::vector::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 args_; -}; - // A struct that encompasses the arguments to the child process of a // threadsafe-style death test process. struct ExecDeathTestArgs { @@ -1208,7 +1176,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 +1257,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 +1288,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 +1335,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 +1377,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 args = GetArgvsForDeathTestChildProcess(); + args.push_back(filter_flag); + args.push_back(internal_flag); DeathTest::set_last_death_test_message(""); @@ -1422,7 +1388,8 @@ DeathTest::TestRole ExecDeathTest::AssumeRole() { // is necessary. FlushInfoLog(); - const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]); + std::vector argv = CreateArgvFromArgs(args); + const pid_t child_pid = ExecDeathTestSpawnChild(argv.data(), 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 +1430,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 +1464,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 +1531,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 +1541,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 +1558,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/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/src/gtest-filepath.cc b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/src/gtest-filepath.cc index 9d79ea49d8a..902d8c7f64b 100644 --- a/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/src/gtest-filepath.cc +++ b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/src/gtest-filepath.cc @@ -31,12 +31,15 @@ #include +#include +#include + #include "gtest/gtest-message.h" #include "gtest/internal/gtest-port.h" -#if GTEST_OS_WINDOWS_MOBILE +#ifdef GTEST_OS_WINDOWS_MOBILE #include -#elif GTEST_OS_WINDOWS +#elif defined(GTEST_OS_WINDOWS) #include #include #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,21 @@ 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) || defined(GTEST_OS_NXP_QN9090) || \ + defined(GTEST_OS_NRF52) // 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. @@ -148,20 +153,19 @@ const char* FilePath::FindLastPathSeparator() const { } size_t FilePath::CalculateRootLength() const { - const auto &path = pathname_; + const auto& path = pathname_; auto s = path.begin(); auto end = path.end(); -#if GTEST_OS_WINDOWS - if (end - s >= 2 && s[1] == ':' && - (end - s == 2 || IsPathSeparator(s[2])) && +#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:" s += 2; if (s != end) { ++s; } - } else if (end - s >= 3 && IsPathSeparator(*s) && IsPathSeparator(*(s + 1)) - && !IsPathSeparator(*(s + 2))) { + } else if (end - s >= 3 && IsPathSeparator(*s) && IsPathSeparator(*(s + 1)) && + !IsPathSeparator(*(s + 2))) { // Move past the "\\" prefix in a UNC path like "\\Server\Share\Folder" s += 2; // Skip 2 components and their following separators ("Server\" and "Share\") @@ -245,7 +249,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; @@ -260,7 +264,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 @@ -269,7 +273,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; @@ -295,9 +299,7 @@ bool FilePath::IsRootDirectory() const { } // Returns true if pathname describes an absolute path. -bool FilePath::IsAbsolutePath() const { - return CalculateRootLength() > 0; -} +bool FilePath::IsAbsolutePath() const { return CalculateRootLength() > 0; } // Returns a pathname for a file that does not currently exist. The pathname // will be directory/base_name.extension or @@ -334,7 +336,7 @@ bool FilePath::CreateDirectoriesRecursively() const { return false; } - if (pathname_.length() == 0 || this->DirectoryExists()) { + if (pathname_.empty() || this->DirectoryExists()) { return true; } @@ -347,14 +349,16 @@ 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) || defined(GTEST_OS_NXP_QN9090) || \ + defined(GTEST_OS_NRF52) // do nothing int result = 0; #else @@ -383,7 +387,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/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/src/gtest-internal-inl.h b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/src/gtest-internal-inl.h index 2c9db4f2078..cc6f00488f9 100644 --- a/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/src/gtest-internal-inl.h +++ b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/src/gtest-internal-inl.h @@ -46,6 +46,7 @@ #include #include #include +#include #include #include "gtest/internal/gtest-port.h" @@ -55,7 +56,7 @@ #include // NOLINT #endif -#if GTEST_OS_WINDOWS +#ifdef GTEST_OS_WINDOWS #include // NOLINT #endif // GTEST_OS_WINDOWS @@ -92,7 +93,8 @@ GTEST_API_ TimeInMillis GetTimeInMillis(); // Returns true if and only if Google Test should use colors in the output. GTEST_API_ bool ShouldUseColor(bool stdout_is_tty); -// Formats the given time in milliseconds as seconds. +// 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." instead of "N"). GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms); // Converts the given time in milliseconds to a date string in the ISO 8601 @@ -311,7 +313,7 @@ void ShuffleRange(internal::Random* random, int begin, int end, << begin << ", " << size << "]."; // Fisher-Yates shuffle, from - // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle + // https://en.wikipedia.org/wiki/Fisher-Yates_shuffle for (int range_width = end - begin; range_width >= 2; range_width--) { const int last_in_range = begin + range_width - 1; const int selected = @@ -383,13 +385,13 @@ 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 - // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise. + // Returns EXCEPTION_EXECUTE_HANDLER if given SEH exception was handled, or + // EXCEPTION_CONTINUE_SEARCH otherwise. // This function is useful as an __except condition. - static int GTestShouldProcessSEH(DWORD exception_code); + static int GTestProcessSEH(DWORD seh_code, const char* location); #endif // GTEST_OS_WINDOWS // Returns true if "name" matches the ':' separated list of glob-style @@ -406,8 +408,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: // @@ -435,13 +437,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. @@ -648,13 +650,15 @@ class GTEST_API_ UnitTestImpl { // this is not a typed or a type-parameterized test. // 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* GetTestSuite(const char* test_suite_name, const char* type_param, + TestSuite* GetTestSuite(const std::string& test_suite_name, + const char* type_param, internal::SetUpTestSuiteFunc set_up_tc, internal::TearDownTestSuiteFunc tear_down_tc); // Legacy API is deprecated but still available #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ - TestCase* GetTestCase(const char* test_case_name, const char* type_param, + TestCase* GetTestCase(const std::string& test_case_name, + const char* type_param, internal::SetUpTestSuiteFunc set_up_tc, internal::TearDownTestSuiteFunc tear_down_tc) { return GetTestSuite(test_case_name, type_param, set_up_tc, tear_down_tc); @@ -671,7 +675,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 +#if GTEST_HAS_FILE_SYSTEM // 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 @@ -680,13 +684,13 @@ class GTEST_API_ UnitTestImpl { // AddTestInfo(), which is called to register a TEST or TEST_F // before main() is reached. if (original_working_dir_.IsEmpty()) { - original_working_dir_.Set(FilePath::GetCurrentDir()); + original_working_dir_ = FilePath::GetCurrentDir(); GTEST_CHECK_(!original_working_dir_.IsEmpty()) << "Failed to get the current working directory."; } -#endif // GTEST_HAS_DEATH_TEST +#endif // GTEST_HAS_FILE_SYSTEM - GetTestSuite(test_info->test_suite_name(), test_info->type_param(), + GetTestSuite(test_info->test_suite_name_, test_info->type_param(), set_up_tc, tear_down_tc) ->AddTestInfo(test_info); } @@ -708,18 +712,6 @@ class GTEST_API_ UnitTestImpl { return type_parameterized_test_registry_; } - // Sets the TestSuite object for the test that's currently running. - void set_current_test_suite(TestSuite* a_current_test_suite) { - current_test_suite_ = a_current_test_suite; - } - - // Sets the TestInfo object for the test that's currently running. If - // current_test_info is NULL, the assertion results will be stored in - // ad_hoc_test_result_. - void set_current_test_info(TestInfo* a_current_test_info) { - current_test_info_ = a_current_test_info; - } - // Registers all parameterized tests defined using TEST_P and // INSTANTIATE_TEST_SUITE_P, creating regular tests for each test/parameter // combination. This method can be called more then once; it has guards @@ -777,7 +769,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()); } @@ -834,12 +826,30 @@ class GTEST_API_ UnitTestImpl { bool catch_exceptions() const { return catch_exceptions_; } private: + struct CompareTestSuitesByPointer { + bool operator()(const TestSuite* lhs, const TestSuite* rhs) const { + return lhs->name_ < rhs->name_; + } + }; + friend class ::testing::UnitTest; // Used by UnitTest::Run() to capture the state of // GTEST_FLAG(catch_exceptions) at the moment it starts. void set_catch_exceptions(bool value) { catch_exceptions_ = value; } + // Sets the TestSuite object for the test that's currently running. + void set_current_test_suite(TestSuite* a_current_test_suite) { + current_test_suite_ = a_current_test_suite; + } + + // Sets the TestInfo object for the test that's currently running. If + // current_test_info is NULL, the assertion results will be stored in + // ad_hoc_test_result_. + void set_current_test_info(TestInfo* a_current_test_info) { + current_test_info_ = a_current_test_info; + } + // The UnitTest object that owns this implementation object. UnitTest* const parent_; @@ -872,6 +882,9 @@ class GTEST_API_ UnitTestImpl { // elements in the vector. std::vector test_suites_; + // The set of TestSuites by name. + std::unordered_map test_suites_by_name_; + // Provides a level of indirection for the test suite list to allow // easy shuffling and restoring the test suite order. The i-th // element of this vector is the index of the i-th test suite in the @@ -942,7 +955,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 internal_run_death_test_flag_; @@ -966,7 +979,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. @@ -992,7 +1005,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. @@ -1063,7 +1076,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/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/src/gtest-port.cc b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/src/gtest-port.cc index d797fe4d586..1038ad7bf60 100644 --- a/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/src/gtest-port.cc +++ b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/src/gtest-port.cc @@ -37,8 +37,12 @@ #include #include #include +#include +#include +#include +#include -#if GTEST_OS_WINDOWS +#ifdef GTEST_OS_WINDOWS #include #include #include @@ -51,32 +55,34 @@ #include #endif // GTEST_OS_WINDOWS -#if GTEST_OS_MAC +#ifdef GTEST_OS_MAC #include #include #include #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 -#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 #endif #endif -#if GTEST_OS_QNX +#ifdef GTEST_OS_QNX #include #include #include #endif // GTEST_OS_QNX -#if GTEST_OS_AIX +#ifdef GTEST_OS_AIX #include #include #endif // GTEST_OS_AIX -#if GTEST_OS_FUCHSIA +#ifdef GTEST_OS_FUCHSIA #include #include #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 @@ -113,7 +119,7 @@ size_t GetThreadCount() { return ReadProcFileField(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 @@ -152,13 +158,13 @@ size_t GetThreadCount() { // we cannot detect it. size_t GetThreadCount() { int mib[] = { - CTL_KERN, - KERN_PROC, - KERN_PROC_PID, - getpid(), -#if GTEST_OS_NETBSD - sizeof(struct kinfo_proc), - 1, + CTL_KERN, + KERN_PROC, + KERN_PROC_PID, + getpid(), +#ifdef GTEST_OS_NETBSD + sizeof(struct kinfo_proc), + 1, #endif }; u_int miblen = sizeof(mib) / sizeof(mib[0]); @@ -169,7 +175,7 @@ size_t GetThreadCount() { } return static_cast(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. @@ -193,8 +199,8 @@ size_t GetThreadCount() { mib[5] = static_cast(size / static_cast(mib[4])); // populate array of structs - struct kinfo_proc info[mib[5]]; - if (sysctl(mib, miblen, &info, &size, NULL, 0)) { + std::vector info(mib[5]); + if (sysctl(mib, miblen, info.data(), &size, NULL, 0)) { return 0; } @@ -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) {} @@ -581,9 +587,11 @@ class ThreadLocalRegistryImpl { // thread's ID. typedef std::map ThreadIdToThreadLocals; - // Holds the thread id and thread handle that we pass from - // StartWatcherThreadFor to WatcherThreadFunc. - typedef std::pair ThreadIdAndHandle; + struct WatcherThreadParams { + DWORD thread_id; + HANDLE handle; + Notification has_initialized; + }; static void StartWatcherThreadFor(DWORD thread_id) { // The returned handle will be kept in thread_map and closed by @@ -591,15 +599,20 @@ class ThreadLocalRegistryImpl { HANDLE thread = ::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION, FALSE, thread_id); GTEST_CHECK_(thread != nullptr); + + WatcherThreadParams* watcher_thread_params = new WatcherThreadParams; + watcher_thread_params->thread_id = thread_id; + watcher_thread_params->handle = thread; + // We need to pass a valid thread ID pointer into CreateThread for it // to work correctly under Win98. DWORD watcher_thread_id; - HANDLE watcher_thread = ::CreateThread( - nullptr, // Default security. - 0, // Default stack size - &ThreadLocalRegistryImpl::WatcherThreadFunc, - reinterpret_cast(new ThreadIdAndHandle(thread_id, thread)), - CREATE_SUSPENDED, &watcher_thread_id); + HANDLE watcher_thread = + ::CreateThread(nullptr, // Default security. + 0, // Default stack size + &ThreadLocalRegistryImpl::WatcherThreadFunc, + reinterpret_cast(watcher_thread_params), + CREATE_SUSPENDED, &watcher_thread_id); GTEST_CHECK_(watcher_thread != nullptr) << "CreateThread failed with error " << ::GetLastError() << "."; // Give the watcher thread the same priority as ours to avoid being @@ -608,17 +621,25 @@ class ThreadLocalRegistryImpl { ::GetThreadPriority(::GetCurrentThread())); ::ResumeThread(watcher_thread); ::CloseHandle(watcher_thread); + + // Wait for the watcher thread to start to avoid race conditions. + // One specific race condition that can happen is that we have returned + // from main and have started to tear down, the newly spawned watcher + // thread may access already-freed variables, like global shared_ptrs. + watcher_thread_params->has_initialized.WaitForNotification(); } // Monitors exit from a given thread and notifies those // ThreadIdToThreadLocals about thread termination. static DWORD WINAPI WatcherThreadFunc(LPVOID param) { - const ThreadIdAndHandle* tah = - reinterpret_cast(param); - GTEST_CHECK_(::WaitForSingleObject(tah->second, INFINITE) == WAIT_OBJECT_0); - OnThreadExit(tah->first); - ::CloseHandle(tah->second); - delete tah; + WatcherThreadParams* watcher_thread_params = + reinterpret_cast(param); + watcher_thread_params->has_initialized.Notify(); + GTEST_CHECK_(::WaitForSingleObject(watcher_thread_params->handle, + INFINITE) == WAIT_OBJECT_0); + OnThreadExit(watcher_thread_params->thread_id); + ::CloseHandle(watcher_thread_params->handle); + delete watcher_thread_params; return 0; } @@ -655,7 +676,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 +689,6 @@ RE::~RE() { regfree(&partial_regex_); regfree(&full_regex_); } - free(const_cast(pattern_)); } // Returns true if and only if regular expression re matches the entire str. @@ -690,7 +710,18 @@ 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; + + // NetBSD (and Android, which takes its regex implemntation from NetBSD) does + // not include the GNU regex extensions (such as Perl style character classes + // like \w) in REG_EXTENDED. REG_EXTENDED is only specified to include the + // [[:alpha:]] style character classes. Enable REG_GNU wherever it is defined + // so users can use those extensions. +#if defined(REG_GNU) + constexpr int reg_flags = REG_EXTENDED | REG_GNU; +#else + constexpr int reg_flags = REG_EXTENDED; +#endif // Reserves enough bytes to hold the regular expression used for a // full match. @@ -698,7 +729,7 @@ void RE::Init(const char* regex) { char* const full_pattern = new char[full_regex_len]; snprintf(full_pattern, full_regex_len, "^(%s)$", regex); - is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0; + is_valid_ = regcomp(&full_regex_, full_pattern, reg_flags) == 0; // We want to call regcomp(&partial_regex_, ...) even if the // previous expression returns false. Otherwise partial_regex_ may // not be properly initialized can may cause trouble when it's @@ -709,7 +740,7 @@ void RE::Init(const char* regex) { // regex. We change it to an equivalent form "()" to be safe. if (is_valid_) { const char* const partial_regex = (*regex == '\0') ? "()" : regex; - is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0; + is_valid_ = regcomp(&partial_regex_, partial_regex, reg_flags) == 0; } EXPECT_TRUE(is_valid_) << "Regular expression \"" << regex @@ -718,7 +749,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 +951,26 @@ bool MatchRegexAnywhere(const char* regex, const char* str) { // Implements the RE class. -RE::~RE() { - free(const_cast(pattern_)); - free(const_cast(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 +979,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(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 @@ -1024,18 +1048,28 @@ GTestLog::~GTestLog() { } } +#if GTEST_HAS_STREAM_REDIRECTION + // Disable Microsoft deprecation warnings for POSIX functions called from // this class (creat, dup, dup2, and close) GTEST_DISABLE_MSC_DEPRECATED_PUSH_() -#if GTEST_HAS_STREAM_REDIRECTION +namespace { + +#if defined(GTEST_OS_LINUX_ANDROID) || defined(GTEST_OS_IOS) +bool EndsWithPathSeparator(const std::string& path) { + return !path.empty() && path.back() == GTEST_PATH_SEP_[0]; +} +#endif + +} // namespace // Object that captures an output stream (stdout/stderr). 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 +1088,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, @@ -1066,8 +1100,14 @@ class CapturedStream { // The location /data/local/tmp is directly accessible from native code. // '/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 + // + // However, prefer using the TMPDIR environment variable if set, as newer + // devices may have /data/local/tmp read-only. + name_template = TempDir(); + if (!EndsWithPathSeparator(name_template)) + name_template.push_back(GTEST_PATH_SEP_[0]); + +#elif defined(GTEST_OS_IOS) char user_temp_dir[PATH_MAX + 1]; // Documented alternative to NSTemporaryDirectory() (for obtaining creating @@ -1086,7 +1126,7 @@ class CapturedStream { ::confstr(_CS_DARWIN_USER_TEMP_DIR, user_temp_dir, sizeof(user_temp_dir)); name_template = user_temp_dir; - if (name_template.back() != GTEST_PATH_SEP_[0]) + if (!EndsWithPathSeparator(name_template)) name_template.push_back(GTEST_PATH_SEP_[0]); #else name_template = "/tmp/"; @@ -1227,7 +1267,7 @@ std::string ReadEntireFile(FILE* file) { return content; } -#if GTEST_HAS_DEATH_TEST +#ifdef GTEST_HAS_DEATH_TEST static const std::vector* g_injected_test_argvs = nullptr; // Owned. @@ -1254,7 +1294,7 @@ void ClearInjectableArgvs() { } #endif // GTEST_HAS_DEATH_TEST -#if GTEST_OS_WINDOWS_MOBILE +#ifdef GTEST_OS_WINDOWS_MOBILE namespace posix { void Abort() { DebugBreak(); @@ -1308,8 +1348,8 @@ bool ParseInt32(const Message& src_text, const char* str, int32_t* value) { ) { Message msg; msg << "WARNING: " << src_text - << " is expected to be a 32-bit integer, but actually" - << " has value " << str << ", which overflows.\n"; + << " is expected to be a 32-bit integer, but actually" << " has value " + << str << ", which overflows.\n"; printf("%s", msg.GetString().c_str()); fflush(stdout); return false; diff --git a/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/src/gtest-printers.cc b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/src/gtest-printers.cc index d475ad36f5e..e3acecba8e4 100644 --- a/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/src/gtest-printers.cc +++ b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/src/gtest-printers.cc @@ -47,6 +47,8 @@ #include #include #include +#include +#include #include // NOLINT #include #include @@ -214,7 +216,7 @@ static const char* GetCharWidthPrefix(signed char) { return ""; } static const char* GetCharWidthPrefix(unsigned char) { return ""; } -#ifdef __cpp_char8_t +#ifdef __cpp_lib_char8_t static const char* GetCharWidthPrefix(char8_t) { return "u8"; } #endif @@ -230,7 +232,7 @@ static CharFormat PrintAsStringLiteralTo(char c, ostream* os) { return PrintAsStringLiteralTo(ToChar32(c), os); } -#ifdef __cpp_char8_t +#ifdef __cpp_lib_char8_t static CharFormat PrintAsStringLiteralTo(char8_t c, ostream* os) { return PrintAsStringLiteralTo(ToChar32(c), os); } @@ -393,7 +395,7 @@ void UniversalPrintArray(const char* begin, size_t len, ostream* os) { UniversalPrintCharArray(begin, len, os); } -#ifdef __cpp_char8_t +#ifdef __cpp_lib_char8_t // Prints a (const) char8_t array of 'len' elements, starting at address // 'begin'. void UniversalPrintArray(const char8_t* begin, size_t len, ostream* os) { @@ -436,7 +438,7 @@ void PrintCStringTo(const Char* s, ostream* os) { void PrintTo(const char* s, ostream* os) { PrintCStringTo(s, os); } -#ifdef __cpp_char8_t +#ifdef __cpp_lib_char8_t void PrintTo(const char8_t* s, ostream* os) { PrintCStringTo(s, os); } #endif @@ -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/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/src/gtest-test-part.cc b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/src/gtest-test-part.cc index eb7c8d1cf92..6f8ddd7c485 100644 --- a/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/src/gtest-test-part.cc +++ b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/src/gtest-test-part.cc @@ -32,13 +32,14 @@ #include "gtest/gtest-test-part.h" +#include +#include + #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/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/src/gtest-typed-test.cc b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/src/gtest-typed-test.cc index a2828b83c66..b251c09deb8 100644 --- a/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/src/gtest-typed-test.cc +++ b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/src/gtest-typed-test.cc @@ -29,6 +29,10 @@ #include "gtest/gtest-typed-test.h" +#include +#include +#include + #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/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/src/gtest.cc b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/src/gtest.cc index a64e887c969..6662a13ce14 100644 --- a/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/src/gtest.cc +++ b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/src/gtest.cc @@ -43,16 +43,23 @@ #include #include // NOLINT #include +#include // NOLINT: raise(3) is used on some platforms #include +#include +#include #include #include +#include +#include #include #include #include #include #include // NOLINT +#include #include #include +#include #include #include "gtest/gtest-assertion-result.h" @@ -60,7 +67,7 @@ #include "gtest/internal/custom/gtest.h" #include "gtest/internal/gtest-port.h" -#if GTEST_OS_LINUX +#ifdef GTEST_OS_LINUX #include // NOLINT #include // NOLINT @@ -73,18 +80,18 @@ #include -#elif GTEST_OS_ZOS +#elif defined(GTEST_OS_ZOS) #include // NOLINT // On z/OS we additionally need strings.h for strcasecmp. #include // NOLINT -#elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE. +#elif defined(GTEST_OS_WINDOWS_MOBILE) // We are on Windows CE. #include // NOLINT #undef min -#elif GTEST_OS_WINDOWS // We are on Windows proper. +#elif defined(GTEST_OS_WINDOWS) // We are on Windows proper. #include // NOLINT #undef min @@ -98,7 +105,7 @@ #include // NOLINT #include // NOLINT -#if GTEST_OS_WINDOWS_MINGW +#ifdef GTEST_OS_WINDOWS_MINGW #include // NOLINT #endif // GTEST_OS_WINDOWS_MINGW @@ -124,17 +131,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 #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" @@ -142,6 +150,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 @@ -152,6 +162,10 @@ #define GTEST_HAS_BUILTIN(x) 0 #endif // defined(__has_builtin) +#if defined(GTEST_HAS_ABSL) && !defined(GTEST_NO_ABSL_FLAGS) +#define GTEST_HAS_ABSL_FLAGS +#endif + namespace testing { using internal::CountIf; @@ -365,7 +379,7 @@ GTEST_DEFINE_string_( 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."); + "Linux and macOS."); GTEST_DEFINE_bool_( throw_on_failure, @@ -407,7 +421,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. @@ -437,6 +451,19 @@ static bool ShouldRunTestSuite(const TestSuite* test_suite) { return test_suite->should_run(); } +namespace { + +// Returns true if test part results of type `type` should include a stack +// trace. +bool ShouldEmitStackTraceForResultType(TestPartResult::Type type) { + // Suppress emission of the stack trace for SUCCEED() since it likely never + // requires investigation, and GTEST_SKIP() since skipping is an intentional + // act by the developer rather than a failure requiring investigation. + return type != TestPartResult::kSuccess && type != TestPartResult::kSkip; +} + +} // namespace + // AssertHelper constructor. AssertHelper::AssertHelper(TestPartResult::Type type, const char* file, int line, const char* message) @@ -449,7 +476,9 @@ void AssertHelper::operator=(const Message& message) const { UnitTest::GetInstance()->AddTestPartResult( data_->type, data_->file, data_->line, AppendUserMessage(data_->message, message), - UnitTest::GetInstance()->impl()->CurrentOsStackTraceExceptTop(1) + ShouldEmitStackTraceForResultType(data_->type) + ? UnitTest::GetInstance()->impl()->CurrentOsStackTraceExceptTop(1) + : "" // Skips the stack frame for this function itself. ); // NOLINT } @@ -507,7 +536,8 @@ void InsertSyntheticTestCase(const std::string& name, CodeLocation location, if (ignored.find(name) != ignored.end()) return; const char kMissingInstantiation[] = // - " is defined via TEST_P, but never instantiated. None of the test cases " + " is defined via TEST_P, but never instantiated. None of the test " + "cases " "will run. Either no INSTANTIATE_TEST_SUITE_P is provided or the only " "ones provided expand to nothing." "\n\n" @@ -548,7 +578,7 @@ void InsertSyntheticTestCase(const std::string& name, CodeLocation location, void RegisterTypeParameterizedTestSuite(const char* test_suite_name, CodeLocation code_location) { GetUnitTestImpl()->type_parameterized_test_registry().RegisterTestSuite( - test_suite_name, code_location); + test_suite_name, std::move(code_location)); } void RegisterTypeParameterizedTestSuiteInstantiation(const char* case_name) { @@ -559,7 +589,7 @@ void RegisterTypeParameterizedTestSuiteInstantiation(const char* case_name) { void TypeParameterizedTestSuiteRegistry::RegisterTestSuite( const char* test_suite_name, CodeLocation code_location) { suites_.emplace(std::string(test_suite_name), - TypeParameterizedTestSuiteInfo(code_location)); + TypeParameterizedTestSuiteInfo(std::move(code_location))); } void TypeParameterizedTestSuiteRegistry::RegisterInstantiation( @@ -586,10 +616,12 @@ void TypeParameterizedTestSuiteRegistry::CheckForInstantiations() { "\n\n" "Ideally, TYPED_TEST_P definitions should only ever be included as " "part of binaries that intend to use them. (As opposed to, for " - "example, being placed in a library that may be linked in to get other " + "example, being placed in a library that may be linked in to get " + "other " "utilities.)" "\n\n" - "To suppress this error for this test suite, insert the following line " + "To suppress this error for this test suite, insert the following " + "line " "(in a non-header) in the namespace it is defined in:" "\n\n" "GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(" + @@ -629,11 +661,14 @@ ::std::vector GetArgvs() { FilePath GetCurrentExecutableName() { FilePath result; -#if GTEST_OS_WINDOWS || GTEST_OS_OS2 - result.Set(FilePath(GetArgvs()[0]).RemoveExtension("exe")); + auto args = GetArgvs(); + if (!args.empty()) { +#if defined(GTEST_OS_WINDOWS) || defined(GTEST_OS_OS2) + result.Set(FilePath(args[0]).RemoveExtension("exe")); #else - result.Set(FilePath(GetArgvs()[0])); + result.Set(FilePath(args[0])); #endif // GTEST_OS_WINDOWS + } return result.RemoveDirectoryName(); } @@ -769,7 +804,7 @@ class UnitTestFilter { // Returns true if and only if name matches at least one of the patterns in // the filter. bool MatchesName(const std::string& name) const { - return exact_match_patterns_.count(name) > 0 || + return exact_match_patterns_.find(name) != exact_match_patterns_.end() || std::any_of(glob_patterns_.begin(), glob_patterns_.end(), [&name](const std::string& pattern) { return PatternMatchesString( @@ -854,30 +889,39 @@ bool UnitTestOptions::FilterMatchesTest(const std::string& test_suite_name, } #if GTEST_HAS_SEH -// Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the -// given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise. -// This function is useful as an __except condition. -int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) { +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, 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 http://support.microsoft.com/kb/185294 for more information). + // (see https://support.microsoft.com/kb/185294 for more information). const DWORD kCxxExceptionCode = 0xe06d7363; - bool should_handle = true; + 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 + } - if (!GTEST_FLAG_GET(catch_exceptions)) - should_handle = false; - else if (exception_code == EXCEPTION_BREAKPOINT) - should_handle = false; - else if (exception_code == kCxxExceptionCode) - should_handle = false; + internal::ReportFailureInUnknownLocation( + TestPartResult::kFatalFailure, + FormatSehExceptionMessage(seh_code, location) + + "\n" + "Stack trace:\n" + + ::testing::internal::GetCurrentOsStackTraceExceptTop(1)); - return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH; + return EXCEPTION_EXECUTE_HANDLER; } #endif // GTEST_HAS_SEH @@ -1134,8 +1178,8 @@ class Timer { // Return time elapsed in milliseconds since the timer was created. TimeInMillis Elapsed() { - return std::chrono::duration_cast( - clock::now() - start_) + return std::chrono::duration_cast(clock::now() - + start_) .count(); } @@ -1164,7 +1208,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 @@ -1866,14 +1910,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[] = ""; @@ -2134,9 +2178,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. @@ -2236,7 +2280,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, @@ -2299,7 +2343,7 @@ static const char* const kReservedTestCaseAttributes[] = { "type_param", "value_param", "file", "line"}; // Use a slightly different set for allowed output to ensure existing tests can -// still RecordProperty("result") or "RecordProperty(timestamp") +// still RecordProperty("result") or RecordProperty("timestamp") static const char* const kReservedOutputTestCaseAttributes[] = { "classname", "name", "status", "time", "type_param", "value_param", "file", "line", "result", "timestamp"}; @@ -2324,7 +2368,9 @@ static std::vector GetReservedAttributesForElement( return std::vector(); } +#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 GetReservedOutputAttributesForElement( const std::string& xml_element) { if (xml_element == "testsuites") { @@ -2339,6 +2385,7 @@ static std::vector GetReservedOutputAttributesForElement( // This code is unreachable but some compilers may not realizes that. return std::vector(); } +#endif static std::string FormatWordList(const std::vector& words) { Message word_list; @@ -2442,7 +2489,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. // @@ -2458,11 +2505,6 @@ void Test::TearDown() {} void Test::RecordProperty(const std::string& key, const std::string& value) { UnitTest::GetInstance()->RecordProperty(key, value); } -// We do not define a customary serialization except for integers, -// but other values could be logged in this way. -void Test::RecordProperty(const std::string& key, int64_t value) { - RecordProperty(key, (Message() << value).GetString()); -} namespace internal { @@ -2546,23 +2588,6 @@ bool Test::HasSameFixtureClass() { return true; } -#if GTEST_HAS_SEH - -// Adds an "exception thrown" fatal failure to the current test. This -// function returns its result via an output parameter pointer because VC++ -// prohibits creation of objects with destructors on stack in functions -// using __try (see error C2712). -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 new std::string(message.GetString()); -} - -#endif // GTEST_HAS_SEH - namespace internal { #if GTEST_HAS_EXCEPTIONS @@ -2604,16 +2629,8 @@ Result HandleSehExceptionsInMethodIfSupported(T* object, Result (T::*method)(), #if GTEST_HAS_SEH __try { return (object->*method)(); - } __except (internal::UnitTestOptions::GTestShouldProcessSEH( // NOLINT - GetExceptionCode())) { - // We create the exception message on the heap because VC++ prohibits - // creation of objects with destructors on stack in functions using __try - // (see error C2712). - std::string* exception_message = - FormatSehExceptionMessage(GetExceptionCode(), location); - internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure, - *exception_message); - delete exception_message; + } __except (internal::UnitTestOptions::GTestProcessSEH( // NOLINT + GetExceptionCode(), location)) { return static_cast(0); } #else @@ -2726,18 +2743,16 @@ bool Test::IsSkipped() { // Constructs a TestInfo object. It assumes ownership of the test factory // object. -TestInfo::TestInfo(const std::string& a_test_suite_name, - const std::string& a_name, const char* a_type_param, - const char* a_value_param, +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) - : test_suite_name_(a_test_suite_name), - // begin()/end() is MSVC 17.3.3 ASAN crash workaround (GitHub issue #3997) - name_(a_name.begin(), a_name.end()), + : test_suite_name_(std::move(a_test_suite_name)), + name_(std::move(a_name)), type_param_(a_type_param ? new std::string(a_type_param) : nullptr), value_param_(a_value_param ? new std::string(a_value_param) : nullptr), - location_(a_code_location), + location_(std::move(a_code_location)), fixture_class_id_(fixture_class_id), should_run_(false), is_disabled_(false), @@ -2770,19 +2785,19 @@ namespace internal { // The newly created TestInfo instance will assume // ownership of the factory object. TestInfo* MakeAndRegisterTestInfo( - const char* test_suite_name, const char* name, const char* type_param, + 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) { TestInfo* const test_info = - new TestInfo(test_suite_name, name, type_param, value_param, - code_location, fixture_class_id, factory); + new TestInfo(std::move(test_suite_name), name, type_param, value_param, + std::move(code_location), fixture_class_id, factory); GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info); return test_info; } void ReportInvalidTestSuiteType(const char* test_suite_name, - CodeLocation code_location) { + const CodeLocation& code_location) { Message errors; errors << "Attempted redefinition of test suite " << test_suite_name << ".\n" @@ -2822,14 +2837,13 @@ void TestInfo::Run() { } // Tells UnitTest where to store test result. - internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); - impl->set_current_test_info(this); + UnitTest::GetInstance()->set_current_test_info(this); // Notifies the unit test event listeners that a test is about to start. repeater->OnTestStart(*this); result_.set_start_timestamp(internal::GetTimeInMillis()); internal::Timer timer; - impl->os_stack_trace_getter()->UponLeavingGTest(); + UnitTest::GetInstance()->UponLeavingGTest(); // Creates the test object. Test* const test = internal::HandleExceptionsInMethodIfSupported( @@ -2847,7 +2861,7 @@ void TestInfo::Run() { if (test != nullptr) { // Deletes the test object. - impl->os_stack_trace_getter()->UponLeavingGTest(); + UnitTest::GetInstance()->UponLeavingGTest(); internal::HandleExceptionsInMethodIfSupported( test, &Test::DeleteSelf_, "the test fixture's destructor"); } @@ -2859,15 +2873,14 @@ void TestInfo::Run() { // Tells UnitTest to stop associating assertion results to this // test. - impl->set_current_test_info(nullptr); + UnitTest::GetInstance()->set_current_test_info(nullptr); } // Skip and records a skipped test result for this object. void TestInfo::Skip() { if (!should_run_) return; - internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); - impl->set_current_test_info(this); + UnitTest::GetInstance()->set_current_test_info(this); TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater(); @@ -2876,12 +2889,13 @@ void TestInfo::Skip() { const TestPartResult test_part_result = TestPartResult(TestPartResult::kSkip, this->file(), this->line(), ""); - impl->GetTestPartResultReporterForCurrentThread()->ReportTestPartResult( - test_part_result); + internal::GetUnitTestImpl() + ->GetTestPartResultReporterForCurrentThread() + ->ReportTestPartResult(test_part_result); // Notifies the unit test event listener that a test has just finished. repeater->OnTestEnd(*this); - impl->set_current_test_info(nullptr); + UnitTest::GetInstance()->set_current_test_info(nullptr); } // class TestSuite @@ -2935,7 +2949,7 @@ int TestSuite::total_test_count() const { // 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 char* a_name, const char* a_type_param, +TestSuite::TestSuite(const std::string& a_name, const char* a_type_param, internal::SetUpTestSuiteFunc set_up_tc, internal::TearDownTestSuiteFunc tear_down_tc) : name_(a_name), @@ -2977,11 +2991,29 @@ void TestSuite::AddTestInfo(TestInfo* test_info) { void TestSuite::Run() { if (!should_run_) return; - internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); - impl->set_current_test_suite(this); + UnitTest::GetInstance()->set_current_test_suite(this); 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 @@ -2989,11 +3021,12 @@ void TestSuite::Run() { repeater->OnTestCaseStart(*this); #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ - impl->os_stack_trace_getter()->UponLeavingGTest(); + UnitTest::GetInstance()->UponLeavingGTest(); internal::HandleExceptionsInMethodIfSupported( this, &TestSuite::RunSetUpTestSuite, "SetUpTestSuite()"); - const bool skip_all = ad_hoc_test_result().Failed(); + const bool skip_all = + ad_hoc_test_result().Failed() || ad_hoc_test_result().Skipped(); start_timestamp_ = internal::GetTimeInMillis(); internal::Timer timer; @@ -3013,7 +3046,7 @@ void TestSuite::Run() { } elapsed_time_ = timer.Elapsed(); - impl->os_stack_trace_getter()->UponLeavingGTest(); + UnitTest::GetInstance()->UponLeavingGTest(); internal::HandleExceptionsInMethodIfSupported( this, &TestSuite::RunTearDownTestSuite, "TearDownTestSuite()"); @@ -3024,15 +3057,14 @@ void TestSuite::Run() { repeater->OnTestCaseEnd(*this); #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ - impl->set_current_test_suite(nullptr); + UnitTest::GetInstance()->set_current_test_suite(nullptr); } // Skips all tests under this TestSuite. void TestSuite::Skip() { if (!should_run_) return; - internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); - impl->set_current_test_suite(this); + UnitTest::GetInstance()->set_current_test_suite(this); TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater(); @@ -3054,7 +3086,7 @@ void TestSuite::Skip() { repeater->OnTestCaseEnd(*this); #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ - impl->set_current_test_suite(nullptr); + UnitTest::GetInstance()->set_current_test_suite(nullptr); } // Clears the results of all tests in this test suite. @@ -3145,7 +3177,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. @@ -3155,8 +3187,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_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) { @@ -3216,7 +3249,8 @@ static const char* GetAnsiColorCode(GTestColor color) { case GTestColor::kYellow: return "3"; default: - return nullptr; + assert(false); + return "9"; } } @@ -3228,7 +3262,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; @@ -3239,6 +3273,7 @@ bool ShouldUseColor(bool stdout_is_tty) { term != nullptr && (String::CStringEquals(term, "xterm") || String::CStringEquals(term, "xterm-color") || String::CStringEquals(term, "xterm-kitty") || + String::CStringEquals(term, "alacritty") || String::CStringEquals(term, "screen") || String::CStringEquals(term, "tmux") || String::CStringEquals(term, "rxvt-unicode") || @@ -3269,11 +3304,9 @@ static void ColoredPrintf(GTestColor color, const char* fmt, ...) { va_start(args, fmt); static const bool in_color_mode = -#if GTEST_HAS_FILE_SYSTEM + // We don't condition this on GTEST_HAS_FILE_SYSTEM because we still need + // to be able to detect terminal I/O regardless. ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0); -#else - false; -#endif // GTEST_HAS_FILE_SYSTEM const bool use_color = in_color_mode && (color != GTestColor::kDefault); @@ -3283,8 +3316,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_GAMES) && !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. @@ -3338,7 +3372,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); } @@ -3646,7 +3680,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); } @@ -3761,28 +3795,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 @@ -4089,6 +4123,13 @@ std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters( // Formats the given time in milliseconds as seconds. std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) { ::std::stringstream ss; + // For the exact N seconds, makes sure output has a trailing decimal point. + // Sets precision so that we won't have many trailing zeros (e.g., 300 ms + // will be just 0.3, 410 ms 0.41, and so on) + ss << std::fixed + << std::setprecision( + ms % 1000 == 0 ? 0 : (ms % 100 == 0 ? 1 : (ms % 10 == 0 ? 2 : 3))) + << std::showpoint; ss << (static_cast(ms) * 1e-3); return ss.str(); } @@ -4400,8 +4441,8 @@ std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes( Message attributes; for (int i = 0; i < result.test_property_count(); ++i) { const TestProperty& property = result.GetTestProperty(i); - attributes << " " << property.key() << "=" - << "\"" << EscapeXmlAttribute(property.value()) << "\""; + attributes << " " << property.key() << "=" << "\"" + << EscapeXmlAttribute(property.value()) << "\""; } return attributes.GetString(); } @@ -4705,28 +4746,53 @@ void JsonUnitTestResultPrinter::OutputJsonTestResult(::std::ostream* stream, const TestResult& result) { const std::string kIndent = Indent(10); - int failures = 0; - for (int i = 0; i < result.total_part_count(); ++i) { - const TestPartResult& part = result.GetTestPartResult(i); - if (part.failed()) { - *stream << ",\n"; - if (++failures == 1) { - *stream << kIndent << "\"" - << "failures" - << "\": [\n"; + { + int failures = 0; + for (int i = 0; i < result.total_part_count(); ++i) { + const TestPartResult& part = result.GetTestPartResult(i); + if (part.failed()) { + *stream << ",\n"; + if (++failures == 1) { + *stream << kIndent << "\"" << "failures" << "\": [\n"; + } + const std::string location = + internal::FormatCompilerIndependentFileLocation(part.file_name(), + part.line_number()); + const std::string message = + EscapeJson(location + "\n" + part.message()); + *stream << kIndent << " {\n" + << kIndent << " \"failure\": \"" << message << "\",\n" + << kIndent << " \"type\": \"\"\n" + << kIndent << " }"; + } + } + + if (failures > 0) *stream << "\n" << kIndent << "]"; + } + + { + int skipped = 0; + for (int i = 0; i < result.total_part_count(); ++i) { + const TestPartResult& part = result.GetTestPartResult(i); + if (part.skipped()) { + *stream << ",\n"; + if (++skipped == 1) { + *stream << kIndent << "\"" << "skipped" << "\": [\n"; + } + const std::string location = + internal::FormatCompilerIndependentFileLocation(part.file_name(), + part.line_number()); + const std::string message = + EscapeJson(location + "\n" + part.message()); + *stream << kIndent << " {\n" + << kIndent << " \"message\": \"" << message << "\"\n" + << kIndent << " }"; } - const std::string location = - internal::FormatCompilerIndependentFileLocation(part.file_name(), - part.line_number()); - const std::string message = EscapeJson(location + "\n" + part.message()); - *stream << kIndent << " {\n" - << kIndent << " \"failure\": \"" << message << "\",\n" - << kIndent << " \"type\": \"\"\n" - << kIndent << " }"; } + + if (skipped > 0) *stream << "\n" << kIndent << "]"; } - if (failures > 0) *stream << "\n" << kIndent << "]"; *stream << "\n" << Indent(8) << "}"; } @@ -4863,8 +4929,8 @@ std::string JsonUnitTestResultPrinter::TestPropertiesAsJson( for (int i = 0; i < result.test_property_count(); ++i) { const TestProperty& property = result.GetTestProperty(i); attributes << ",\n" - << indent << "\"" << property.key() << "\": " - << "\"" << EscapeJson(property.value()) << "\""; + << indent << "\"" << property.key() << "\": " << "\"" + << EscapeJson(property.value()) << "\""; } return attributes.GetString(); } @@ -4950,7 +5016,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) { @@ -4999,7 +5065,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; @@ -5010,7 +5076,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 { @@ -5030,7 +5096,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) { @@ -5120,8 +5186,8 @@ bool TestEventListeners::EventForwardingEnabled() const { return repeater_->forwarding_enabled(); } -void TestEventListeners::SuppressEventForwarding() { - repeater_->set_forwarding_enabled(false); +void TestEventListeners::SuppressEventForwarding(bool suppress) { + repeater_->set_forwarding_enabled(!suppress); } // class UnitTest @@ -5262,6 +5328,22 @@ TestSuite* UnitTest::GetMutableTestSuite(int i) { return impl()->GetMutableSuiteCase(i); } +void UnitTest::UponLeavingGTest() { + impl()->os_stack_trace_getter()->UponLeavingGTest(); +} + +// Sets the TestSuite object for the test that's currently running. +void UnitTest::set_current_test_suite(TestSuite* a_current_test_suite) { + internal::MutexLock lock(&mutex_); + impl_->set_current_test_suite(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) { + internal::MutexLock lock(&mutex_); + impl_->set_current_test_info(a_current_test_info); +} + // Returns the list of event listeners that can be used to track events // inside Google Test. TestEventListeners& UnitTest::listeners() { return *impl()->listeners(); } @@ -5298,7 +5380,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) { @@ -5311,6 +5393,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( @@ -5326,7 +5410,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. @@ -5374,9 +5459,9 @@ 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; + !GTEST_FLAG_GET(internal_run_death_test).empty(); // Google Test implements this protocol for catching that a test // program exits before returning control to Google Test: @@ -5403,32 +5488,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) && !defined(GTEST_OS_WINDOWS_GAMES) // 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 @@ -5450,6 +5539,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( @@ -5545,7 +5636,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. @@ -5585,12 +5676,12 @@ 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) - listeners()->SuppressEventForwarding(); + if (internal_run_death_test_flag_ != nullptr) + listeners()->SuppressEventForwarding(true); } #endif // GTEST_HAS_DEATH_TEST @@ -5605,13 +5696,15 @@ 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."; } #else - GTEST_LOG_(ERROR) << "ERROR: alternative output formats require " - << "GTEST_HAS_FILE_SYSTEM to be enabled"; + if (!output_format.empty()) { + GTEST_LOG_(ERROR) << "ERROR: alternative output formats require " + << "GTEST_HAS_FILE_SYSTEM to be enabled"; + } #endif // GTEST_HAS_FILE_SYSTEM } @@ -5648,7 +5741,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 @@ -5671,7 +5764,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); @@ -5680,29 +5773,6 @@ void UnitTestImpl::PostFlagParsingInit() { } } -// A predicate that checks the name of a TestSuite against a known -// value. -// -// This is used for implementation of the UnitTest class only. We put -// it in the anonymous namespace to prevent polluting the outer -// namespace. -// -// TestSuiteNameIs is copyable. -class TestSuiteNameIs { - public: - // Constructor. - explicit TestSuiteNameIs(const std::string& name) : name_(name) {} - - // Returns true if and only if the name of test_suite matches name_. - bool operator()(const TestSuite* test_suite) const { - return test_suite != nullptr && - strcmp(test_suite->name(), name_.c_str()) == 0; - } - - private: - std::string name_; -}; - // 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 @@ -5716,19 +5786,27 @@ class TestSuiteNameIs { // 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 char* test_suite_name, const char* type_param, + const std::string& test_suite_name, const char* type_param, internal::SetUpTestSuiteFunc set_up_tc, internal::TearDownTestSuiteFunc tear_down_tc) { - // Can we find a TestSuite with the given name? - const auto test_suite = - std::find_if(test_suites_.rbegin(), test_suites_.rend(), - TestSuiteNameIs(test_suite_name)); + // During initialization, all TestInfos for a given suite are added in + // sequence. To optimize this case, see if the most recently added suite is + // the one being requested now. + if (!test_suites_.empty() && + (*test_suites_.rbegin())->name_ == test_suite_name) { + return *test_suites_.rbegin(); + } - if (test_suite != test_suites_.rend()) return *test_suite; + // Fall back to searching the collection. + auto item_it = test_suites_by_name_.find(test_suite_name); + if (item_it != test_suites_by_name_.end()) { + return item_it->second; + } - // No. Let's create one. + // Not found. Create a new instance. auto* const new_test_suite = new TestSuite(test_suite_name, type_param, set_up_tc, tear_down_tc); + test_suites_by_name_.emplace(test_suite_name, new_test_suite); const UnitTestFilter death_test_suite_filter(kDeathTestSuiteFilter); // Is this a death test suite? @@ -5786,9 +5864,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_(); @@ -5942,6 +6019,12 @@ bool UnitTestImpl::RunAllTests() { } repeater->OnTestProgramEnd(*parent_); + // Destroy environments in normal code, not in static teardown. + bool delete_environment_on_teardown = true; + if (delete_environment_on_teardown) { + ForEach(environments_, internal::Delete); + environments_.clear(); + } if (!gtest_is_initialized_before_run_all_tests) { ColoredPrintf( @@ -5951,10 +6034,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; @@ -6079,12 +6158,11 @@ int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) { int num_runnable_tests = 0; int num_selected_tests = 0; for (auto* test_suite : test_suites_) { - const std::string& test_suite_name = test_suite->name(); + const std::string& test_suite_name = test_suite->name_; test_suite->set_should_run(false); - for (size_t j = 0; j < test_suite->test_info_list().size(); j++) { - TestInfo* const test_info = test_suite->test_info_list()[j]; - const std::string test_name(test_info->name()); + for (TestInfo* test_info : test_suite->test_info_list()) { + const std::string& test_name = test_info->name_; // A test is disabled if test suite name or test name matches // kDisableTestFilter. const bool is_disabled = @@ -6172,11 +6250,11 @@ void UnitTestImpl::ListTestsMatchingFilter() { } } fflush(stdout); - #if GTEST_HAS_FILE_SYSTEM +#if GTEST_HAS_FILE_SYSTEM const std::string& output_format = UnitTestOptions::GetOutputFormat(); if (output_format == "xml" || output_format == "json") { - FILE* fileout = OpenFileForWriting( - UnitTestOptions::GetAbsolutePathToOutputFile().c_str()); + FILE* fileout = + OpenFileForWriting(UnitTestOptions::GetAbsolutePathToOutputFile()); std::stringstream stream; if (output_format == "xml") { XmlUnitTestResultPrinter( @@ -6510,7 +6588,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" @@ -6625,17 +6703,17 @@ void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) { } if (remove_flag) { - // Shift the remainder of the argv list left by one. Note - // that argv has (*argc + 1) elements, the last one always being - // NULL. The following loop moves the trailing NULL element as - // well. - for (int j = i; j != *argc; j++) { - argv[j] = argv[j + 1]; + // Shift the remainder of the argv list left by one. + for (int j = i + 1; j < *argc; ++j) { + argv[j - 1] = argv[j]; } // Decrements the argument count. (*argc)--; + // Terminate the array with nullptr. + argv[*argc] = nullptr; + // We also need to decrement the iterator as we just removed // an element. i--; @@ -6651,26 +6729,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(positional_args.size()) < *argc) { - argv[positional_args.size()] = nullptr; - *argc = static_cast(positional_args.size()); +#ifdef GTEST_HAS_ABSL_FLAGS + if (*argc <= 0) return; + + std::vector positional_args; + std::vector unrecognized_flags; + absl::ParseAbseilFlagsOnly(*argc, argv, positional_args, unrecognized_flags); + absl::flat_hash_set unrecognized; + for (const auto& flag : unrecognized_flags) { + unrecognized.insert(flag.flag_name); + } + absl::flat_hash_set 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 @@ -6678,7 +6790,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; @@ -6706,14 +6818,16 @@ 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()); +#ifdef GTEST_HAS_ABSL_FLAGS // When using the Abseil Flags library, set the program usage message to the // help message, but remove the color-encoding from the message first. absl::SetProgramUsageMessage(absl::StrReplaceAll( kColorEncodedHelpMessage, {{"@D", ""}, {"@R", ""}, {"@G", ""}, {"@Y", ""}, {"@@", "@"}})); +#endif // GTEST_HAS_ABSL_FLAGS #endif // GTEST_HAS_ABSL ParseGoogleTestFlagsOnly(argc, argv); @@ -6790,16 +6904,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() { @@ -6808,13 +6922,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 @@ -6822,6 +6937,7 @@ std::string SrcDir() { '/'); #endif } +#endif // Class ScopedTrace diff --git a/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/src/gtest_main.cc b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/src/gtest_main.cc index 5abaa29fa11..8141caf4ca0 100644 --- a/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/src/gtest_main.cc +++ b/Modules/ThirdParty/GoogleTest/src/itkgoogletest/googletest/src/gtest_main.cc @@ -31,10 +31,11 @@ #include "gtest/gtest.h" -#if GTEST_OS_ESP8266 || GTEST_OS_ESP32 +#if defined(GTEST_OS_ESP8266) || defined(GTEST_OS_ESP32) || \ + (defined(GTEST_OS_NRF52) && defined(ARDUINO)) // 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 +43,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() {